SockAddr string optimization

- Reduce buffer size to INET6_ADDRSTRLEN, and use a single buf rather
  than two identical ones in each branch.
- Don't pre-reserve because doing so is usually going to over-allocate,
  but also because it prevents SSO, especially for the IPv4 case which
  should fit in SSO for all IPv4 addresses.
This commit is contained in:
Jason Rhinelander 2021-08-30 16:52:43 -03:00
parent 37dde7da05
commit 3deb55193f
1 changed files with 3 additions and 10 deletions

View File

@ -299,24 +299,17 @@ namespace llarp
SockAddr::hostString() const
{
std::string str;
char buf[INET6_ADDRSTRLEN] = {0x0};
if (isIPv4())
{
// handle IPv4 mapped addrs
constexpr auto MaxIPv4PlusPortStringSize = 22;
str.reserve(MaxIPv4PlusPortStringSize);
char buf[128] = {0x0};
inet_ntop(AF_INET, &m_addr4.sin_addr.s_addr, buf, sizeof(buf));
str.append(buf);
str = buf;
}
else
{
constexpr auto MaxIPv6PlusPortStringSize = 128;
str.reserve(MaxIPv6PlusPortStringSize);
char buf[128] = {0x0};
inet_ntop(AF_INET6, &m_addr.sin6_addr.s6_addr, buf, sizeof(buf));
str.reserve(std::strlen(buf) + 2);
str.append("[");
str.append(buf);
str.append("]");