github.com/RomiChan/protobuf@v0.1.1-0.20230204044148-2ed269a2e54d/proto/encode_test.go (about) 1 package proto 2 3 import ( 4 "math" 5 "testing" 6 ) 7 8 type message struct { 9 A int32 `protobuf:"varint,1,opt"` 10 B int32 `protobuf:"varint,2,opt"` 11 C int32 `protobuf:"varint,3,opt"` 12 S *submessage `protobuf:"bytes,4,opt"` 13 } 14 15 type submessage struct { 16 X string `protobuf:"bytes,1,opt"` 17 Y string `protobuf:"bytes,2,opt"` 18 } 19 20 func BenchmarkEncodeVarintShort(b *testing.B) { 21 c := [10]byte{} 22 23 for i := 0; i < b.N; i++ { 24 appendVarint(c[:], 0) 25 } 26 } 27 28 func BenchmarkEncodeVarintLong(b *testing.B) { 29 c := [10]byte{} 30 31 for i := 0; i < b.N; i++ { 32 appendVarint(c[:], math.MaxUint64) 33 } 34 } 35 36 func BenchmarkEncodeTag(b *testing.B) { 37 c := [8]byte{} 38 39 for i := 0; i < b.N; i++ { 40 appendTag(c[:], 1, varint) 41 } 42 } 43 44 func BenchmarkEncodeMessage(b *testing.B) { 45 msg := &message{ 46 A: 1, 47 B: 100, 48 C: 10000, 49 S: &submessage{ 50 X: "", 51 Y: "Hello World!", 52 }, 53 } 54 55 size := Size(msg) 56 b.SetBytes(int64(size)) 57 58 for i := 0; i < b.N; i++ { 59 if _, err := Marshal(msg); err != nil { 60 b.Fatal(err) 61 } 62 } 63 } 64 65 func BenchmarkEncodeMap(b *testing.B) { 66 msg := struct { 67 M map[string]string `protobuf:"bytes,1,opt" protobuf_key:"bytes,1,opt" protobuf_val:"bytes,2,opt"` 68 }{ 69 M: map[string]string{ 70 "hello": "world", 71 }, 72 } 73 74 size := Size(&msg) 75 b.SetBytes(int64(size)) 76 77 for i := 0; i < b.N; i++ { 78 if _, err := Marshal(&msg); err != nil { 79 b.Fatal(err) 80 } 81 } 82 } 83 84 func BenchmarkEncodeSlice(b *testing.B) { 85 msg := struct { 86 S []int32 `protobuf:"varint,1,rep"` 87 }{ 88 S: []int32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 89 } 90 91 size := Size(&msg) 92 b.SetBytes(int64(size)) 93 94 for i := 0; i < b.N; i++ { 95 if _, err := Marshal(&msg); err != nil { 96 b.Fatal(err) 97 } 98 } 99 } 100 101 func TestEncodeDecodeVarint(t *testing.T) { 102 var b []byte 103 104 b = appendVarint(b, 42) 105 106 v, _, err := decodeVarint(b) 107 if err != nil { 108 t.Fatal(err) 109 } 110 if v != 42 { 111 t.Errorf("decoded value mismatch: want %d, got %d", 42, v) 112 } 113 } 114 115 func TestEncodeDecodeVarintZigZag(t *testing.T) { 116 var b []byte 117 118 b = appendVarintZigZag(b, -42) 119 v, _, err := decodeVarintZigZag(b) 120 if err != nil { 121 t.Fatal(err) 122 } 123 if v != -42 { 124 t.Errorf("decoded value mismatch: want %d, got %d", -42, v) 125 } 126 } 127 128 func TestEncodeDecodeTag(t *testing.T) { 129 var b []byte 130 131 b = appendTag(b, 1, varint) 132 num, typ, _, err := decodeTag(b) 133 if err != nil { 134 t.Fatal(err) 135 } 136 if num != 1 { 137 t.Errorf("decoded field number mismatch: want %d, got %d", 1, num) 138 } 139 if typ != varint { 140 t.Errorf("decoded wire type mismatch: want %d, got %d", varint, typ) 141 } 142 }