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