summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--base/string_util.cc29
-rw-r--r--base/string_util_unittest.cc4
2 files changed, 9 insertions, 24 deletions
diff --git a/base/string_util.cc b/base/string_util.cc
index 45a4442..5a06b64 100644
--- a/base/string_util.cc
+++ b/base/string_util.cc
@@ -1534,30 +1534,15 @@ bool ElideString(const std::wstring& input, int max_len, std::wstring* output) {
}
std::string HexEncode(const void* bytes, size_t size) {
- static const char kHexChars[] = {
- '0', '1', '2', '3', '4', '5', '6', '7',
- '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+ static const char kHexChars[] = "0123456789ABCDEF";
- if (size == 0)
- return std::string();
+ // Each input byte creates two output hex characters.
+ std::string ret(size * 2, '\0');
- std::string ret;
- // For each byte, we print two characters.
- ret.resize(size * 2);
-
- const unsigned char* pos = reinterpret_cast<const unsigned char*>(bytes);
- const unsigned char* end = pos + size;
- std::string::iterator write = ret.begin();
- while (pos < end) {
- unsigned char b = *pos;
- pos++;
-
- write[0] = kHexChars[(b >> 4) & 0xf];
- write++;
-
- write[0] = kHexChars[b & 0xf];
- write++;
+ for (size_t i = 0; i < size; ++i) {
+ char b = reinterpret_cast<const char*>(bytes)[i];
+ ret[(i * 2)] = kHexChars[(b >> 4) & 0xf];
+ ret[(i * 2) + 1] = kHexChars[b & 0xf];
}
-
return ret;
}
diff --git a/base/string_util_unittest.cc b/base/string_util_unittest.cc
index 0ca4438..a3ca7ee 100644
--- a/base/string_util_unittest.cc
+++ b/base/string_util_unittest.cc
@@ -1455,7 +1455,7 @@ TEST(StringUtilTest, ElideString) {
TEST(StringUtilTest, HexEncode) {
std::string hex(HexEncode(NULL, 0));
EXPECT_EQ(hex.length(), 0U);
- unsigned char bytes[] = {0x01, 0xff, 0x02, 0xfe, 0x03};
+ unsigned char bytes[] = {0x01, 0xff, 0x02, 0xfe, 0x03, 0x80, 0x81};
hex = HexEncode(bytes, sizeof(bytes));
- EXPECT_EQ(hex.compare("01FF02FE03"), 0);
+ EXPECT_EQ(hex.compare("01FF02FE038081"), 0);
}