File: decode_test.go

package info (click to toggle)
golang-github-segmentio-encoding 0.5.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 14,468 kB
  • sloc: makefile: 286
file content (146 lines) | stat: -rw-r--r-- 2,212 bytes parent folder | download
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package proto

import (
	"errors"
	"io"
	"testing"
)

func TestUnarshalFromShortBuffer(t *testing.T) {
	m := message{
		A: 1,
		B: 2,
		C: 3,
		S: submessage{
			X: "hello",
			Y: "world",
		},
	}

	b, _ := Marshal(m)

	for i := range b {
		switch i {
		case 0, 2, 4, 6:
			continue // these land on field boundaries, making the input valid
		}
		t.Run("", func(t *testing.T) {
			msg := &message{}
			err := Unmarshal(b[:i], msg)
			if !errors.Is(err, io.ErrUnexpectedEOF) {
				t.Errorf("error mismatch, want io.ErrUnexpectedEOF but got %q", err)
			}
		})
	}
}

func TestUnmarshalFixture(t *testing.T) {
	type Message struct {
		A uint
		B uint32
		C uint64
		D string
	}

	b := loadProtobuf(t, "message.pb")
	m := Message{}

	if err := Unmarshal(b, &m); err != nil {
		t.Fatal(err)
	}

	if m.A != 10 {
		t.Error("m.A mismatch, want 10 but got", m.A)
	}

	if m.B != 20 {
		t.Error("m.B mismatch, want 20 but got", m.B)
	}

	if m.C != 30 {
		t.Error("m.C mismatch, want 30 but got", m.C)
	}

	if m.D != "Hello World!" {
		t.Errorf("m.D mismatch, want \"Hello World!\" but got %q", m.D)
	}
}

func BenchmarkDecodeTag(b *testing.B) {
	c := [8]byte{}
	n, _ := encodeTag(c[:], 1, varint)

	for range b.N {
		decodeTag(c[:n])
	}
}

func BenchmarkDecodeMessage(b *testing.B) {
	data, _ := Marshal(message{
		A: 1,
		B: 100,
		C: 10000,
		S: submessage{
			X: "",
			Y: "Hello World!",
		},
	})

	msg := message{}
	b.SetBytes(int64(len(data)))

	for range b.N {
		if err := Unmarshal(data, &msg); err != nil {
			b.Fatal(err)
		}
		msg = message{}
	}
}

func BenchmarkDecodeMap(b *testing.B) {
	type message struct {
		M map[int]int
	}

	data, _ := Marshal(message{
		M: map[int]int{
			0: 0,
			1: 1,
			2: 2,
			3: 3,
			4: 4,
		},
	})

	msg := message{}
	b.SetBytes(int64(len(data)))

	for range b.N {
		if err := Unmarshal(data, &msg); err != nil {
			b.Fatal(err)
		}
		msg = message{}
	}
}

func BenchmarkDecodeSlice(b *testing.B) {
	type message struct {
		S []int
	}

	data, _ := Marshal(message{
		S: []int{
			0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
		},
	})

	msg := message{}
	b.SetBytes(int64(len(data)))

	for range b.N {
		if err := Unmarshal(data, &msg); err != nil {
			b.Fatal(err)
		}
		msg = message{}
	}
}