bytes_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package jsonparser
  2. import (
  3. "strconv"
  4. "testing"
  5. "unsafe"
  6. )
  7. type ParseIntTest struct {
  8. in string
  9. out int64
  10. isErr bool
  11. }
  12. var parseIntTests = []ParseIntTest{
  13. {
  14. in: "0",
  15. out: 0,
  16. },
  17. {
  18. in: "1",
  19. out: 1,
  20. },
  21. {
  22. in: "-1",
  23. out: -1,
  24. },
  25. {
  26. in: "12345",
  27. out: 12345,
  28. },
  29. {
  30. in: "-12345",
  31. out: -12345,
  32. },
  33. {
  34. in: "9223372036854775807",
  35. out: 9223372036854775807,
  36. },
  37. {
  38. in: "-9223372036854775808",
  39. out: -9223372036854775808,
  40. },
  41. {
  42. in: "18446744073709551616", // = 2^64; integer overflow is not detected
  43. out: 0,
  44. },
  45. {
  46. in: "",
  47. isErr: true,
  48. },
  49. {
  50. in: "abc",
  51. isErr: true,
  52. },
  53. {
  54. in: "12345x",
  55. isErr: true,
  56. },
  57. {
  58. in: "123e5",
  59. isErr: true,
  60. },
  61. {
  62. in: "9223372036854775807x",
  63. isErr: true,
  64. },
  65. }
  66. func TestBytesParseInt(t *testing.T) {
  67. for _, test := range parseIntTests {
  68. out, ok := parseInt([]byte(test.in))
  69. if ok != !test.isErr {
  70. t.Errorf("Test '%s' error return did not match expectation (obtained %t, expected %t)", test.in, !ok, test.isErr)
  71. } else if ok && out != test.out {
  72. t.Errorf("Test '%s' did not return the expected value (obtained %d, expected %d)", test.in, out, test.out)
  73. }
  74. }
  75. }
  76. func BenchmarkParseInt(b *testing.B) {
  77. bytes := []byte("123")
  78. for i := 0; i < b.N; i++ {
  79. parseInt(bytes)
  80. }
  81. }
  82. // Alternative implementation using unsafe and delegating to strconv.ParseInt
  83. func BenchmarkParseIntUnsafeSlower(b *testing.B) {
  84. bytes := []byte("123")
  85. for i := 0; i < b.N; i++ {
  86. strconv.ParseInt(*(*string)(unsafe.Pointer(&bytes)), 10, 64)
  87. }
  88. }