diff options
Diffstat (limited to 'Swiften/Base')
-rw-r--r-- | Swiften/Base/ByteArray.cpp | 10 | ||||
-rw-r--r-- | Swiften/Base/ByteArray.h | 4 | ||||
-rw-r--r-- | Swiften/Base/UnitTest/ByteArrayTest.cpp | 12 |
3 files changed, 21 insertions, 5 deletions
diff --git a/Swiften/Base/ByteArray.cpp b/Swiften/Base/ByteArray.cpp index c3869fc..323c866 100644 --- a/Swiften/Base/ByteArray.cpp +++ b/Swiften/Base/ByteArray.cpp @@ -72,4 +72,14 @@ std::vector<unsigned char> ByteArray::create(const unsigned char* c, size_t n) { return data; } +std::string ByteArray::toString() const { + size_t i; + for (i = data_.size(); i > 0; --i) { + if (data_[i - 1] != 0) { + break; + } + } + return i > 0 ? std::string(reinterpret_cast<const char*>(getData()), i) : ""; +} + } diff --git a/Swiften/Base/ByteArray.h b/Swiften/Base/ByteArray.h index d55da1f..ebc22d8 100644 --- a/Swiften/Base/ByteArray.h +++ b/Swiften/Base/ByteArray.h @@ -120,9 +120,7 @@ namespace Swift { return data_.end(); } - std::string toString() const { - return std::string(reinterpret_cast<const char*>(getData()), getSize()); - } + std::string toString() const; void readFromFile(const std::string& file); diff --git a/Swiften/Base/UnitTest/ByteArrayTest.cpp b/Swiften/Base/UnitTest/ByteArrayTest.cpp index b9797d2..069e68e 100644 --- a/Swiften/Base/UnitTest/ByteArrayTest.cpp +++ b/Swiften/Base/UnitTest/ByteArrayTest.cpp @@ -8,6 +8,7 @@ #include <cppunit/extensions/TestFactoryRegistry.h> #include "Swiften/Base/ByteArray.h" +#include <boost/lexical_cast.hpp> using namespace Swift; @@ -17,6 +18,7 @@ class ByteArrayTest : public CppUnit::TestFixture { CPPUNIT_TEST(testToString); CPPUNIT_TEST(testToString_NullTerminated); CPPUNIT_TEST(testToString_TwoNullTerminated); + CPPUNIT_TEST(testToString_AllNull); CPPUNIT_TEST_SUITE_END(); public: @@ -33,16 +35,22 @@ class ByteArrayTest : public CppUnit::TestFixture { } void testToString_NullTerminated() { - ByteArray testling(ByteArray::create("abcde\0")); + ByteArray testling(ByteArray::create("abcde\0", 6)); CPPUNIT_ASSERT_EQUAL(std::string("abcde"), testling.toString()); } void testToString_TwoNullTerminated() { - ByteArray testling(ByteArray::create("abcde\0\0")); + ByteArray testling(ByteArray::create("abcde\0\0", 7)); CPPUNIT_ASSERT_EQUAL(std::string("abcde"), testling.toString()); } + + void testToString_AllNull() { + ByteArray testling(ByteArray::create("\0\0", 2)); + + CPPUNIT_ASSERT_EQUAL(std::string(""), testling.toString()); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(ByteArrayTest); |