From 5eb0feb22bbd7aaf57d159b7ce71656dd8a26234 Mon Sep 17 00:00:00 2001 From: Stephen Seo Date: Wed, 18 Sep 2019 18:39:35 +0900 Subject: [PATCH] Fix atostr --- cpp_impl/src/UDPConnection.cpp | 26 ++++++++++++++++++++------ cpp_impl/src/test/TestUDPC.cpp | 13 +++++++++++-- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/cpp_impl/src/UDPConnection.cpp b/cpp_impl/src/UDPConnection.cpp index ac76ae2..cb55bdf 100644 --- a/cpp_impl/src/UDPConnection.cpp +++ b/cpp_impl/src/UDPConnection.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -1190,19 +1191,32 @@ const char *UDPC_atostr(UDPC_HContext ctx, struct in6_addr addr) { } } - if(addr.s6_addr[i] == 0) { + if(addr.s6_addr[i] == 0 && (headIndex - index <= 1 || c->atostrBuf[index] == ':')) { continue; } else { std::stringstream sstream; - sstream << std::hex << (unsigned int) addr.s6_addr[i]; + sstream << std::setw(2) << std::setfill('0') + << std::hex << (unsigned int) addr.s6_addr[i]; std::string out(sstream.str()); - if(out.size() == 1) { - if(out[0] != '0') { - std::memcpy(c->atostrBuf + index, out.c_str(), 1); + unsigned int outOffset = 0; + if(headIndex - index <= 1 || c->atostrBuf[index - 1] == ':') { + if(out[0] == '0') { + if(out[1] == '0') { + outOffset = 2; + } else { + outOffset = 1; + } + } + } + if(outOffset == 2) { + continue; + } else if(outOffset == 1) { + if(out[outOffset] != '0') { + std::memcpy(c->atostrBuf + index, out.c_str() + outOffset, 1); ++index; } } else { - std::memcpy(c->atostrBuf + index, out.c_str(), 2); + std::memcpy(c->atostrBuf + index, out.c_str() + outOffset, 2); index += 2; } } diff --git a/cpp_impl/src/test/TestUDPC.cpp b/cpp_impl/src/test/TestUDPC.cpp index 34c7689..f3c43b9 100644 --- a/cpp_impl/src/test/TestUDPC.cpp +++ b/cpp_impl/src/test/TestUDPC.cpp @@ -27,12 +27,12 @@ TEST(UDPC, atostr) { conId.addr.s6_addr[0] = 1; conId.addr.s6_addr[1] = 2; resultBuf = UDPC_atostr((UDPC_HContext)&context, conId.addr); - EXPECT_STREQ(resultBuf, "12::56ff:1256:ff12:56ff"); + EXPECT_STREQ(resultBuf, "102::56ff:1256:ff12:56ff"); conId.addr.s6_addr[14] = 0; conId.addr.s6_addr[15] = 0; resultBuf = UDPC_atostr((UDPC_HContext)&context, conId.addr); - EXPECT_STREQ(resultBuf, "12::56ff:1256:ff12:0"); + EXPECT_STREQ(resultBuf, "102::56ff:1256:ff12:0"); for(unsigned int i = 0; i < 15; ++i) { conId.addr.s6_addr[i] = 0; @@ -46,6 +46,15 @@ TEST(UDPC, atostr) { resultBuf = UDPC_atostr((UDPC_HContext)&context, conId.addr); EXPECT_STREQ(resultBuf, "::"); + + conId.addr = { + 0xAE, 0x0, 0x12, 1, + 0x10, 0x45, 0x2, 0x13, + 0, 0, 0, 0, + 0, 0, 0, 0 + }; + resultBuf = UDPC_atostr((UDPC_HContext)&context, conId.addr); + EXPECT_STREQ(resultBuf, "ae00:1201:1045:213::"); } TEST(UDPC, atostr_concurrent) {