github.com/xmplusdev/xmcore@v1.8.11-0.20240412132628-5518b55526af/common/serial/serial_test.go (about) 1 package serial_test 2 3 import ( 4 "bytes" 5 "testing" 6 7 "github.com/google/go-cmp/cmp" 8 "github.com/xmplusdev/xmcore/common" 9 "github.com/xmplusdev/xmcore/common/buf" 10 "github.com/xmplusdev/xmcore/common/serial" 11 ) 12 13 func TestUint16Serial(t *testing.T) { 14 b := buf.New() 15 defer b.Release() 16 17 n, err := serial.WriteUint16(b, 10) 18 common.Must(err) 19 if n != 2 { 20 t.Error("expect 2 bytes writtng, but actually ", n) 21 } 22 if diff := cmp.Diff(b.Bytes(), []byte{0, 10}); diff != "" { 23 t.Error(diff) 24 } 25 } 26 27 func TestUint64Serial(t *testing.T) { 28 b := buf.New() 29 defer b.Release() 30 31 n, err := serial.WriteUint64(b, 10) 32 common.Must(err) 33 if n != 8 { 34 t.Error("expect 8 bytes writtng, but actually ", n) 35 } 36 if diff := cmp.Diff(b.Bytes(), []byte{0, 0, 0, 0, 0, 0, 0, 10}); diff != "" { 37 t.Error(diff) 38 } 39 } 40 41 func TestReadUint16(t *testing.T) { 42 testCases := []struct { 43 Input []byte 44 Output uint16 45 }{ 46 { 47 Input: []byte{0, 1}, 48 Output: 1, 49 }, 50 } 51 52 for _, testCase := range testCases { 53 v, err := serial.ReadUint16(bytes.NewReader(testCase.Input)) 54 common.Must(err) 55 if v != testCase.Output { 56 t.Error("for input ", testCase.Input, " expect output ", testCase.Output, " but got ", v) 57 } 58 } 59 } 60 61 func BenchmarkReadUint16(b *testing.B) { 62 reader := buf.New() 63 defer reader.Release() 64 65 common.Must2(reader.Write([]byte{0, 1})) 66 b.ResetTimer() 67 68 for i := 0; i < b.N; i++ { 69 _, err := serial.ReadUint16(reader) 70 common.Must(err) 71 reader.Clear() 72 reader.Extend(2) 73 } 74 } 75 76 func BenchmarkWriteUint64(b *testing.B) { 77 writer := buf.New() 78 defer writer.Release() 79 80 b.ResetTimer() 81 82 for i := 0; i < b.N; i++ { 83 _, err := serial.WriteUint64(writer, 8) 84 common.Must(err) 85 writer.Clear() 86 } 87 }