summaryrefslogtreecommitdiff
path: root/vendor/golang.org/x/text/internal/catmsg/varint_test.go
blob: 04d881d41d74bcdcf8782992ee32f6670d9beab7 (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// Copyright 2017 The Go 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 catmsg

import (
	"fmt"
	"testing"
)

func TestEncodeUint(t *testing.T) {
	testCases := []struct {
		x   uint64
		enc string
	}{
		{0, "\x00"},
		{1, "\x01"},
		{2, "\x02"},
		{0x7f, "\x7f"},
		{0x80, "\x80\x01"},
		{1 << 14, "\x80\x80\x01"},
		{0xffffffff, "\xff\xff\xff\xff\x0f"},
		{0xffffffffffffffff, "\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01"},
	}
	for _, tc := range testCases {
		buf := [maxVarintBytes]byte{}
		got := string(buf[:encodeUint(buf[:], tc.x)])
		if got != tc.enc {
			t.Errorf("EncodeUint(%#x) = %q; want %q", tc.x, got, tc.enc)
		}
	}
}

func TestDecodeUint(t *testing.T) {
	testCases := []struct {
		x    uint64
		size int
		enc  string
		err  error
	}{{
		x:    0,
		size: 0,
		enc:  "",
		err:  errIllegalVarint,
	}, {
		x:    0,
		size: 1,
		enc:  "\x80",
		err:  errIllegalVarint,
	}, {
		x:    0,
		size: 3,
		enc:  "\x80\x80\x80",
		err:  errIllegalVarint,
	}, {
		x:    0,
		size: 1,
		enc:  "\x00",
	}, {
		x:    1,
		size: 1,
		enc:  "\x01",
	}, {
		x:    2,
		size: 1,
		enc:  "\x02",
	}, {
		x:    0x7f,
		size: 1,
		enc:  "\x7f",
	}, {
		x:    0x80,
		size: 2,
		enc:  "\x80\x01",
	}, {
		x:    1 << 14,
		size: 3,
		enc:  "\x80\x80\x01",
	}, {
		x:    0xffffffff,
		size: 5,
		enc:  "\xff\xff\xff\xff\x0f",
	}, {
		x:    0xffffffffffffffff,
		size: 10,
		enc:  "\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01",
	}, {
		x:    0xffffffffffffffff,
		size: 10,
		enc:  "\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00",
	}, {
		x:    0,
		size: 10,
		enc:  "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01",
		err:  errVarintTooLarge,
	}}
	forms := []struct {
		name   string
		decode func(s string) (x uint64, size int, err error)
	}{
		{"decode", func(s string) (x uint64, size int, err error) {
			return decodeUint([]byte(s))
		}},
		{"decodeString", decodeUintString},
	}
	for _, f := range forms {
		for _, tc := range testCases {
			t.Run(fmt.Sprintf("%s:%q", f.name, tc.enc), func(t *testing.T) {
				x, size, err := f.decode(tc.enc)
				if err != tc.err {
					t.Errorf("err = %q; want %q", err, tc.err)
				}
				if size != tc.size {
					t.Errorf("size = %d; want %d", size, tc.size)
				}
				if x != tc.x {
					t.Errorf("decode = %#x; want %#x", x, tc.x)
				}
			})
		}
	}
}