varint_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2011 The Snappy-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 varint
  5. import (
  6. "testing"
  7. )
  8. var testCases = []struct {
  9. valid bool
  10. s string
  11. v uint64
  12. }{
  13. // Valid encodings.
  14. {true, "\x00", 0},
  15. {true, "\x01", 1},
  16. {true, "\x7f", 127},
  17. {true, "\x80\x01", 128},
  18. {true, "\xff\x02", 383},
  19. {true, "\x9e\xa7\x05", 86942}, // 86942 = 0x1e + 0x27<<7 + 0x05<<14
  20. {true, "\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01", 0xffffffffffffffff},
  21. {
  22. true,
  23. "\x8a\x89\x88\x87\x86\x85\x84\x83\x82\x01",
  24. 10 + 9<<7 + 8<<14 + 7<<21 + 6<<28 + 5<<35 + 4<<42 + 3<<49 + 2<<56 + 1<<63,
  25. },
  26. // Invalid encodings.
  27. {false, "", 0},
  28. {false, "\x80", 0},
  29. {false, "\xff", 0},
  30. {false, "\x9e\xa7", 0},
  31. }
  32. func TestDecode(t *testing.T) {
  33. for _, tc := range testCases {
  34. v, n := Decode([]byte(tc.s))
  35. if v != tc.v {
  36. t.Errorf("decode %q: want value %d got %d", tc.s, tc.v, v)
  37. continue
  38. }
  39. m := 0
  40. if tc.valid {
  41. m = len(tc.s)
  42. }
  43. if n != m {
  44. t.Errorf("decode %q: want length %d got %d", tc.s, m, n)
  45. continue
  46. }
  47. }
  48. }
  49. func TestEncode(t *testing.T) {
  50. for _, tc := range testCases {
  51. if !tc.valid {
  52. continue
  53. }
  54. var b [MaxLen]byte
  55. n := Encode(b[:], tc.v)
  56. if s := string(b[:n]); s != tc.s {
  57. t.Errorf("encode %d: want bytes %q got %q", tc.v, tc.s, s)
  58. continue
  59. }
  60. if n != Len(tc.v) {
  61. t.Errorf("encode %d: Encode length %d != Len length %d", tc.v, n, Len(tc.v))
  62. continue
  63. }
  64. }
  65. }