You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

124 lines
2.3 KiB

  1. // Copyright 2017 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package catmsg
  5. import (
  6. "fmt"
  7. "testing"
  8. )
  9. func TestEncodeUint(t *testing.T) {
  10. testCases := []struct {
  11. x uint64
  12. enc string
  13. }{
  14. {0, "\x00"},
  15. {1, "\x01"},
  16. {2, "\x02"},
  17. {0x7f, "\x7f"},
  18. {0x80, "\x80\x01"},
  19. {1 << 14, "\x80\x80\x01"},
  20. {0xffffffff, "\xff\xff\xff\xff\x0f"},
  21. {0xffffffffffffffff, "\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01"},
  22. }
  23. for _, tc := range testCases {
  24. buf := [maxVarintBytes]byte{}
  25. got := string(buf[:encodeUint(buf[:], tc.x)])
  26. if got != tc.enc {
  27. t.Errorf("EncodeUint(%#x) = %q; want %q", tc.x, got, tc.enc)
  28. }
  29. }
  30. }
  31. func TestDecodeUint(t *testing.T) {
  32. testCases := []struct {
  33. x uint64
  34. size int
  35. enc string
  36. err error
  37. }{{
  38. x: 0,
  39. size: 0,
  40. enc: "",
  41. err: errIllegalVarint,
  42. }, {
  43. x: 0,
  44. size: 1,
  45. enc: "\x80",
  46. err: errIllegalVarint,
  47. }, {
  48. x: 0,
  49. size: 3,
  50. enc: "\x80\x80\x80",
  51. err: errIllegalVarint,
  52. }, {
  53. x: 0,
  54. size: 1,
  55. enc: "\x00",
  56. }, {
  57. x: 1,
  58. size: 1,
  59. enc: "\x01",
  60. }, {
  61. x: 2,
  62. size: 1,
  63. enc: "\x02",
  64. }, {
  65. x: 0x7f,
  66. size: 1,
  67. enc: "\x7f",
  68. }, {
  69. x: 0x80,
  70. size: 2,
  71. enc: "\x80\x01",
  72. }, {
  73. x: 1 << 14,
  74. size: 3,
  75. enc: "\x80\x80\x01",
  76. }, {
  77. x: 0xffffffff,
  78. size: 5,
  79. enc: "\xff\xff\xff\xff\x0f",
  80. }, {
  81. x: 0xffffffffffffffff,
  82. size: 10,
  83. enc: "\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01",
  84. }, {
  85. x: 0xffffffffffffffff,
  86. size: 10,
  87. enc: "\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00",
  88. }, {
  89. x: 0,
  90. size: 10,
  91. enc: "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01",
  92. err: errVarintTooLarge,
  93. }}
  94. forms := []struct {
  95. name string
  96. decode func(s string) (x uint64, size int, err error)
  97. }{
  98. {"decode", func(s string) (x uint64, size int, err error) {
  99. return decodeUint([]byte(s))
  100. }},
  101. {"decodeString", decodeUintString},
  102. }
  103. for _, f := range forms {
  104. for _, tc := range testCases {
  105. t.Run(fmt.Sprintf("%s:%q", f.name, tc.enc), func(t *testing.T) {
  106. x, size, err := f.decode(tc.enc)
  107. if err != tc.err {
  108. t.Errorf("err = %q; want %q", err, tc.err)
  109. }
  110. if size != tc.size {
  111. t.Errorf("size = %d; want %d", size, tc.size)
  112. }
  113. if x != tc.x {
  114. t.Errorf("decode = %#x; want %#x", x, tc.x)
  115. }
  116. })
  117. }
  118. }
  119. }