File: packet_internal_test.go

package info (click to toggle)
golang-github-mdlayher-packet 1.1.2-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 128 kB
  • sloc: makefile: 2
file content (78 lines) | stat: -rw-r--r-- 1,345 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//go:build linux
// +build linux

package packet

import (
	"encoding/binary"
	"fmt"
	"math"
	"testing"

	"github.com/google/go-cmp/cmp"
	"github.com/josharian/native"
)

func Test_htons(t *testing.T) {
	tests := []struct {
		name     string
		i        int
		vLE, vBE uint16
		ok       bool
	}{
		{
			name: "negative",
			i:    -1,
		},
		{
			name: "too large",
			i:    math.MaxUint16 + 1,
		},
		{
			name: "IPv4",
			i:    0x0800,
			vLE:  0x0008,
			vBE:  0x0800,
			ok:   true,
		},
		{
			name: "IPv6",
			i:    0x86dd,
			vLE:  0xdd86,
			vBE:  0x86dd,
			ok:   true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			v, err := htons(tt.i)
			if tt.ok && err != nil {
				t.Fatalf("failed to perform htons: %v", err)
			}
			if !tt.ok && err == nil {
				t.Fatal("expected an error, but none occurred")
			}
			if err != nil {
				t.Logf("err: %v", err)
				return
			}

			// Depending on our GOARCH, the result may be big or little endian.
			var want uint16
			if native.Endian == binary.ByteOrder(binary.LittleEndian) {
				want = tt.vLE
			} else {
				want = tt.vBE
			}

			if diff := cmp.Diff(hex(want), hex(v)); diff != "" {
				t.Fatalf("unexpected output for %s GOARCH (-want +got):\n%s", native.Endian.String(), diff)
			}
		})
	}
}

func hex(v uint16) string {
	return fmt.Sprintf("%#04x", v)
}