Skip to content

Commit

Permalink
Add truncation support to Zeroconf with test.
Browse files Browse the repository at this point in the history
  • Loading branch information
hatstand committed Feb 22, 2013
1 parent ebd2b1e commit def697c
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/networkremote/zeroconf.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
#include "tinysvcmdns.h"
#endif

#include <QTextCodec>

Zeroconf* Zeroconf::sInstance = NULL;

Zeroconf::~Zeroconf() {
Expand All @@ -35,3 +37,18 @@ Zeroconf* Zeroconf::GetZeroconf() {

return sInstance;
}

QByteArray Zeroconf::TruncateName(const QString& name) {
QTextCodec* codec = QTextCodec::codecForName("UTF-8");
QByteArray truncated_utf8;
foreach (QChar c, name) {
QByteArray rendered = codec->fromUnicode(&c, 1, NULL);
if (truncated_utf8.size() + rendered.size() >= 63) {
break;
}
truncated_utf8 += rendered;
}
// NULL-terminate the string.
truncated_utf8.append('\0');
return truncated_utf8;
}
3 changes: 3 additions & 0 deletions src/networkremote/zeroconf.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ class Zeroconf {

static Zeroconf* GetZeroconf();

// Truncate a QString to 63 bytes of UTF-8.
static QByteArray TruncateName(const QString& name);

private:
static Zeroconf* sInstance;
};
Expand Down
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ add_test_file(utilities_test.cpp false)
#add_test_file(xspfparser_test.cpp false)
add_test_file(closure_test.cpp false)
add_test_file(concurrentrun_test.cpp false)
add_test_file(zeroconf_test.cpp false)

#if(LINUX AND HAVE_DBUS)
# add_test_file(mpris1_test.cpp true)
Expand Down
42 changes: 42 additions & 0 deletions tests/zeroconf_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include "gtest/gtest.h"

#include "networkremote/zeroconf.h"

namespace {

static const char k64CharAscii[] =
"aaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaa";

static const char kShortMultiByteString[] =
"我会说一点汉语";

static const char kLongMultiByteString[] =
"我会说一点汉语"
"我会说一点汉语"
"我会说一点汉语"
"我会说一点汉语";

TEST(ZeroconfTest, TruncatesAscii) {
QByteArray truncated = Zeroconf::TruncateName(
QString::fromAscii(k64CharAscii));
EXPECT_EQ(63, truncated.size());
EXPECT_TRUE(truncated.endsWith('\0'));
}

TEST(ZeroconfTest, DoesNotTruncateShortMultiByteUTF8) {
EXPECT_EQ(
sizeof(kShortMultiByteString),
Zeroconf::TruncateName(QString::fromUtf8(kShortMultiByteString)).size());
}

TEST(ZeroconfTest, TruncatesLongMultiByteUTF8) {
QByteArray truncated = Zeroconf::TruncateName(
QString::fromAscii(kLongMultiByteString));
EXPECT_LE(63, truncated.size());
EXPECT_TRUE(truncated.endsWith('\0'));
}

} // namespace

0 comments on commit def697c

Please sign in to comment.