Fix atostr

This commit is contained in:
Stephen Seo 2019-09-18 18:39:35 +09:00
parent 355f3b2bd0
commit 5eb0feb22b
2 changed files with 31 additions and 8 deletions

View file

@ -11,6 +11,7 @@
#include <string>
#include <sstream>
#include <ios>
#include <iomanip>
#include <regex>
#include <sys/ioctl.h>
#include <net/if.h>
@ -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;
}
}

View file

@ -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) {