serial_test.go 1.6 KB

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