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.

79 lines
1.6 KiB

10 years ago
  1. package wire
  2. import (
  3. "bytes"
  4. "fmt"
  5. "testing"
  6. )
  7. func TestVarint(t *testing.T) {
  8. check := func(i int, s string) {
  9. buf := new(bytes.Buffer)
  10. n, err := new(int64), new(error)
  11. WriteVarint(i, buf, n, err)
  12. bufBytes := buf.Bytes() // Read before consuming below.
  13. i_ := ReadVarint(buf, n, err)
  14. if i != i_ {
  15. fmt.Println(bufBytes)
  16. t.Fatalf("Encoded %v and got %v", i, i_)
  17. }
  18. if s != "" {
  19. if bufHex := fmt.Sprintf("%X", bufBytes); bufHex != s {
  20. t.Fatalf("Encoded %v, expected %v", bufHex, s)
  21. }
  22. }
  23. }
  24. // 123457 is some prime.
  25. for i := -(2 << 33); i < (2 << 33); i += 123457 {
  26. check(i, "")
  27. }
  28. // Near zero
  29. check(-1, "F101")
  30. check(0, "00")
  31. check(1, "0101")
  32. // Positives
  33. check(1<<32-1, "04FFFFFFFF")
  34. check(1<<32+0, "050100000000")
  35. check(1<<32+1, "050100000001")
  36. check(1<<53-1, "071FFFFFFFFFFFFF")
  37. // Negatives
  38. check(-1<<32+1, "F4FFFFFFFF")
  39. check(-1<<32-0, "F50100000000")
  40. check(-1<<32-1, "F50100000001")
  41. check(-1<<53+1, "F71FFFFFFFFFFFFF")
  42. }
  43. func TestUvarint(t *testing.T) {
  44. check := func(i uint, s string) {
  45. buf := new(bytes.Buffer)
  46. n, err := new(int64), new(error)
  47. WriteUvarint(i, buf, n, err)
  48. bufBytes := buf.Bytes()
  49. i_ := ReadUvarint(buf, n, err)
  50. if i != i_ {
  51. fmt.Println(buf.Bytes())
  52. t.Fatalf("Encoded %v and got %v", i, i_)
  53. }
  54. if s != "" {
  55. if bufHex := fmt.Sprintf("%X", bufBytes); bufHex != s {
  56. t.Fatalf("Encoded %v, expected %v", bufHex, s)
  57. }
  58. }
  59. }
  60. // 123457 is some prime.
  61. for i := 0; i < (2 << 33); i += 123457 {
  62. check(uint(i), "")
  63. }
  64. check(1, "0101")
  65. check(1<<32-1, "04FFFFFFFF")
  66. check(1<<32+0, "050100000000")
  67. check(1<<32+1, "050100000001")
  68. check(1<<53-1, "071FFFFFFFFFFFFF")
  69. }