Cleanup / temp buffers for various things
This commit is contained in:
@@ -33,15 +33,18 @@ type Ping struct {
|
||||
Dst netip.AddrPort
|
||||
}
|
||||
|
||||
// Marshal encodes p into a fixed-size 51-byte array.
|
||||
func (p Ping) Marshal() [Size]byte {
|
||||
var buf [Size]byte
|
||||
// Marshal encodes p into buf (which must be at least Size bytes) and returns
|
||||
// buf[:Size]. Taking the buffer lets callers reuse one across sends; every
|
||||
// field is written unconditionally so a reused buffer needs no pre-zeroing.
|
||||
func (p Ping) Marshal(buf []byte) []byte {
|
||||
buf[0] = version
|
||||
binary.BigEndian.PutUint64(buf[1:9], uint64(p.PingTS))
|
||||
if p.SrcV4.IsValid() {
|
||||
a4 := p.SrcV4.Addr().As4()
|
||||
copy(buf[9:13], a4[:])
|
||||
binary.BigEndian.PutUint16(buf[13:15], p.SrcV4.Port())
|
||||
} else {
|
||||
clear(buf[9:15])
|
||||
}
|
||||
a16 := p.SrcV6.Addr().As16()
|
||||
copy(buf[15:31], a16[:])
|
||||
@@ -49,7 +52,7 @@ func (p Ping) Marshal() [Size]byte {
|
||||
a16 = p.Dst.Addr().As16()
|
||||
copy(buf[33:49], a16[:])
|
||||
binary.BigEndian.PutUint16(buf[49:51], p.Dst.Port())
|
||||
return buf
|
||||
return buf[:Size]
|
||||
}
|
||||
|
||||
// Unmarshal decodes a Ping from a fixed-size 51-byte array.
|
||||
|
||||
@@ -59,7 +59,8 @@ func TestRoundTrip(t *testing.T) {
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
buf := tc.ping.Marshal()
|
||||
var buf [control.Size]byte
|
||||
tc.ping.Marshal(buf[:])
|
||||
got, err := control.Unmarshal(buf)
|
||||
if err != nil {
|
||||
t.Fatalf("Unmarshal: %v", err)
|
||||
@@ -80,7 +81,8 @@ func TestUnmarshalBadVersion(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestZeroEncoding(t *testing.T) {
|
||||
buf := (control.Ping{}).Marshal()
|
||||
var buf [control.Size]byte
|
||||
(control.Ping{}).Marshal(buf[:])
|
||||
for i, b := range buf {
|
||||
if i == 0 {
|
||||
continue // version byte
|
||||
|
||||
Reference in New Issue
Block a user