github.com/RomiChan/protobuf@v0.1.1-0.20230204044148-2ed269a2e54d/proto/decode_test.go (about) 1 package proto 2 3 import ( 4 "errors" 5 "io" 6 "testing" 7 ) 8 9 func TestUnarshalFromShortBuffer(t *testing.T) { 10 m := message{ 11 A: 1, 12 B: 2, 13 C: 3, 14 S: &submessage{ 15 X: "hello", 16 Y: "world", 17 }, 18 } 19 20 b, err := Marshal(&m) 21 if err != nil { 22 t.Fatalf("Marshal: %v", err) 23 } 24 25 for i := range b { 26 switch i { 27 case 0, 2, 4, 6: 28 continue // these land on field boundaries, making the input valid 29 } 30 t.Run("", func(t *testing.T) { 31 msg := &message{} 32 err := Unmarshal(b[:i], msg) 33 if !errors.Is(err, io.ErrUnexpectedEOF) { 34 t.Errorf("error mismatch, want io.ErrUnexpectedEOF but got %q", err) 35 } 36 }) 37 } 38 } 39 40 func BenchmarkDecodeTag(b *testing.B) { 41 c := appendTag(nil, 1, varint) 42 43 for i := 0; i < b.N; i++ { 44 decodeTag(c) 45 } 46 } 47 48 func BenchmarkDecodeMessage(b *testing.B) { 49 data, _ := Marshal(message{ 50 A: 1, 51 B: 100, 52 C: 10000, 53 S: &submessage{ 54 X: "", 55 Y: "Hello World!", 56 }, 57 }) 58 59 msg := message{} 60 b.SetBytes(int64(len(data))) 61 62 for i := 0; i < b.N; i++ { 63 if err := Unmarshal(data, &msg); err != nil { 64 b.Fatal(err) 65 } 66 msg = message{} 67 } 68 } 69 70 func BenchmarkDecodeMap(b *testing.B) { 71 type message struct { 72 M map[int32]int32 `protobuf:"bytes,1,opt"` 73 } 74 75 data, _ := Marshal(message{ 76 M: map[int32]int32{ 77 0: 0, 78 1: 1, 79 2: 2, 80 3: 3, 81 4: 4, 82 }, 83 }) 84 85 msg := message{} 86 b.SetBytes(int64(len(data))) 87 88 for i := 0; i < b.N; i++ { 89 if err := Unmarshal(data, &msg); err != nil { 90 b.Fatal(err) 91 } 92 msg = message{} 93 } 94 } 95 96 func BenchmarkDecodeSlice(b *testing.B) { 97 type message struct { 98 S []int32 `protobuf:"varint,1,opt"` 99 } 100 101 data, _ := Marshal(message{ 102 S: []int32{ 103 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 104 }, 105 }) 106 107 msg := message{} 108 b.SetBytes(int64(len(data))) 109 110 for i := 0; i < b.N; i++ { 111 if err := Unmarshal(data, &msg); err != nil { 112 b.Fatal(err) 113 } 114 msg = message{} 115 } 116 117 } 118 119 func TestIssue110(t *testing.T) { 120 type message struct { 121 A Option[uint32] `protobuf:"fixed32,1,opt"` 122 } 123 124 var a uint32 = 0x41c06db4 125 data, _ := Marshal(&message{ 126 A: Some(a), 127 }) 128 129 var m message 130 err := Unmarshal(data, &m) 131 if err != nil { 132 t.Fatal(err) 133 } 134 if m.A.Unwrap() != 0x41c06db4 { 135 t.Errorf("m.A mismatch, want 0x41c06db4 but got %v", m.A) 136 } 137 }