mirror of
https://github.com/soypat/lneto.git
synced 2026-08-24 08:29:08 +00:00
Further reduce heap allocs (#56)
* work on tracking more heap allocations down * write own heapless IP AppendFormatAddr functions * remove potential Error method allocations * more logging
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
package ipv4
|
||||
|
||||
import "strconv"
|
||||
|
||||
const (
|
||||
sizeHeader = 20
|
||||
)
|
||||
@@ -68,3 +70,15 @@ func b2u8(b bool) uint8 {
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// AppendFormatAddr appends the dotted-decimal text representation of an IPv4 address
|
||||
// to dst. Zero heap allocations.
|
||||
func AppendFormatAddr(dst []byte, addr [4]byte) []byte {
|
||||
for i, b := range addr {
|
||||
if i != 0 {
|
||||
dst = append(dst, '.')
|
||||
}
|
||||
dst = strconv.AppendUint(dst, uint64(b), 10)
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package ipv4
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAppendFormatAddr(t *testing.T) {
|
||||
tests := []struct {
|
||||
addr [4]byte
|
||||
want string
|
||||
}{
|
||||
{addr: [4]byte{0, 0, 0, 0}, want: "0.0.0.0"},
|
||||
{addr: [4]byte{127, 0, 0, 1}, want: "127.0.0.1"},
|
||||
{addr: [4]byte{192, 168, 1, 1}, want: "192.168.1.1"},
|
||||
{addr: [4]byte{255, 255, 255, 255}, want: "255.255.255.255"},
|
||||
{addr: [4]byte{10, 0, 0, 1}, want: "10.0.0.1"},
|
||||
{addr: [4]byte{1, 2, 3, 4}, want: "1.2.3.4"},
|
||||
{addr: [4]byte{100, 99, 9, 0}, want: "100.99.9.0"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
got := string(AppendFormatAddr(nil, tc.addr))
|
||||
if got != tc.want {
|
||||
t.Errorf("AppendFormatAddr(%v): got %q, want %q", tc.addr, got, tc.want)
|
||||
}
|
||||
// Cross-check with netip.
|
||||
want := netip.AddrFrom4(tc.addr).String()
|
||||
if got != want {
|
||||
t.Errorf("AppendFormatAddr(%v) disagrees with netip: got %q, want %q", tc.addr, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppendFormatAddr_noAllocs(t *testing.T) {
|
||||
var buf [24]byte
|
||||
addr := [4]byte{192, 168, 1, 1}
|
||||
allocs := testing.AllocsPerRun(100, func() {
|
||||
_ = AppendFormatAddr(buf[:0], addr)
|
||||
})
|
||||
if allocs != 0 {
|
||||
t.Errorf("expected 0 allocs, got %v", allocs)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user