github.com/kamalshkeir/kencoding@v0.0.2-0.20230409043843-44b609a0475a/proto/encode_test.go (about) 1 package proto 2 3 import ( 4 "errors" 5 "io" 6 "math" 7 "testing" 8 ) 9 10 func TestMarshalToShortBuffer(t *testing.T) { 11 m := message{ 12 A: 1, 13 B: 2, 14 C: 3, 15 S: submessage{ 16 X: "hello", 17 Y: "world", 18 }, 19 } 20 21 b, _ := Marshal(m) 22 short := make([]byte, len(b)) 23 24 for i := range b { 25 t.Run("", func(t *testing.T) { 26 n, err := MarshalTo(short[:i], m) 27 if n != i { 28 t.Errorf("byte count mismatch, want %d but got %d", i, n) 29 } 30 if !errors.Is(err, io.ErrShortBuffer) { 31 t.Errorf("error mismatch, want io.ErrShortBuffer but got %q", err) 32 } 33 }) 34 } 35 } 36 37 func BenchmarkEncodeVarintShort(b *testing.B) { 38 c := [10]byte{} 39 40 for i := 0; i < b.N; i++ { 41 encodeVarint(c[:], 0) 42 } 43 } 44 45 func BenchmarkEncodeVarintLong(b *testing.B) { 46 c := [10]byte{} 47 48 for i := 0; i < b.N; i++ { 49 encodeVarint(c[:], math.MaxUint64) 50 } 51 } 52 53 func BenchmarkEncodeTag(b *testing.B) { 54 c := [8]byte{} 55 56 for i := 0; i < b.N; i++ { 57 encodeTag(c[:], 1, varint) 58 } 59 } 60 61 func BenchmarkEncodeMessage(b *testing.B) { 62 buf := [128]byte{} 63 msg := &message{ 64 A: 1, 65 B: 100, 66 C: 10000, 67 S: submessage{ 68 X: "", 69 Y: "Hello World!", 70 }, 71 } 72 73 size := Size(msg) 74 data := buf[:size] 75 b.SetBytes(int64(size)) 76 77 for i := 0; i < b.N; i++ { 78 if _, err := MarshalTo(data, msg); err != nil { 79 b.Fatal(err) 80 } 81 } 82 } 83 84 func BenchmarkEncodeMap(b *testing.B) { 85 buf := [128]byte{} 86 msg := struct { 87 M map[string]string 88 }{ 89 M: map[string]string{ 90 "hello": "world", 91 }, 92 } 93 94 size := Size(msg) 95 data := buf[:size] 96 b.SetBytes(int64(size)) 97 98 for i := 0; i < b.N; i++ { 99 if _, err := MarshalTo(data, msg); err != nil { 100 b.Fatal(err) 101 } 102 } 103 } 104 105 func BenchmarkEncodeSlice(b *testing.B) { 106 buf := [128]byte{} 107 msg := struct { 108 S []int 109 }{ 110 S: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 111 } 112 113 size := Size(msg) 114 data := buf[:size] 115 b.SetBytes(int64(size)) 116 117 for i := 0; i < b.N; i++ { 118 if _, err := MarshalTo(data, &msg); err != nil { 119 b.Fatal(err) 120 } 121 } 122 }