tailscale/net/packet/udp4.go
David Anderson 22bf48f37c net/packet: remove {get,put}{16,32} indirection to encoding/binary.
name              old time/op    new time/op    delta
Decode/tcp4-8       28.8ns ± 2%    13.1ns ± 4%  -54.44%  (p=0.008 n=5+5)
Decode/tcp6-8       20.6ns ± 1%    12.6ns ± 2%  -38.72%  (p=0.008 n=5+5)
Decode/udp4-8       28.2ns ± 1%    12.1ns ± 4%  -57.01%  (p=0.008 n=5+5)
Decode/udp6-8       20.0ns ± 6%    12.1ns ± 2%  -39.38%  (p=0.008 n=5+5)
Decode/icmp4-8      21.7ns ± 2%    11.5ns ± 1%  -47.01%  (p=0.008 n=5+5)
Decode/icmp6-8      14.1ns ± 2%    11.8ns ± 4%  -16.60%  (p=0.008 n=5+5)
Decode/unknown-8    9.43ns ± 2%    9.30ns ± 3%     ~     (p=0.222 n=5+5)

Signed-off-by: David Anderson <danderson@tailscale.com>
2020-11-10 20:23:54 -08:00

56 lines
1.3 KiB
Go

// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package packet
import "encoding/binary"
// UDPHeader represents an UDP packet header.
type UDP4Header struct {
IP4Header
SrcPort uint16
DstPort uint16
}
const (
udpHeaderLength = 8
// udpTotalHeaderLength is the length of all headers in a UDP packet.
udpTotalHeaderLength = ip4HeaderLength + udpHeaderLength
)
func (UDP4Header) Len() int {
return udpTotalHeaderLength
}
func (h UDP4Header) Marshal(buf []byte) error {
if len(buf) < udpTotalHeaderLength {
return errSmallBuffer
}
if len(buf) > maxPacketLength {
return errLargePacket
}
// The caller does not need to set this.
h.IPProto = UDP
length := len(buf) - h.IP4Header.Len()
binary.BigEndian.PutUint16(buf[20:22], h.SrcPort)
binary.BigEndian.PutUint16(buf[22:24], h.DstPort)
binary.BigEndian.PutUint16(buf[24:26], uint16(length))
binary.BigEndian.PutUint16(buf[26:28], 0) // blank checksum
h.IP4Header.MarshalPseudo(buf)
// UDP checksum with IP pseudo header.
binary.BigEndian.PutUint16(buf[26:28], ipChecksum(buf[8:]))
h.IP4Header.Marshal(buf)
return nil
}
func (h *UDP4Header) ToResponse() {
h.SrcPort, h.DstPort = h.DstPort, h.SrcPort
h.IP4Header.ToResponse()
}