int_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package strconv // import "github.com/tdewolff/parse/strconv"
  2. import (
  3. "math"
  4. "math/rand"
  5. "testing"
  6. "github.com/tdewolff/test"
  7. )
  8. func TestParseInt(t *testing.T) {
  9. intTests := []struct {
  10. i string
  11. expected int64
  12. }{
  13. {"5", 5},
  14. {"99", 99},
  15. {"999", 999},
  16. {"-5", -5},
  17. {"+5", 5},
  18. {"9223372036854775807", 9223372036854775807},
  19. {"9223372036854775808", 0},
  20. {"-9223372036854775807", -9223372036854775807},
  21. {"-9223372036854775808", -9223372036854775808},
  22. {"-9223372036854775809", 0},
  23. {"18446744073709551620", 0},
  24. {"a", 0},
  25. }
  26. for _, tt := range intTests {
  27. i, _ := ParseInt([]byte(tt.i))
  28. test.That(t, i == tt.expected, "return", tt.expected, "for", tt.i)
  29. }
  30. }
  31. func TestLenInt(t *testing.T) {
  32. lenIntTests := []struct {
  33. number int64
  34. expected int
  35. }{
  36. {0, 1},
  37. {1, 1},
  38. {10, 2},
  39. {99, 2},
  40. {9223372036854775807, 19},
  41. {-9223372036854775808, 19},
  42. // coverage
  43. {100, 3},
  44. {1000, 4},
  45. {10000, 5},
  46. {100000, 6},
  47. {1000000, 7},
  48. {10000000, 8},
  49. {100000000, 9},
  50. {1000000000, 10},
  51. {10000000000, 11},
  52. {100000000000, 12},
  53. {1000000000000, 13},
  54. {10000000000000, 14},
  55. {100000000000000, 15},
  56. {1000000000000000, 16},
  57. {10000000000000000, 17},
  58. {100000000000000000, 18},
  59. {1000000000000000000, 19},
  60. }
  61. for _, tt := range lenIntTests {
  62. test.That(t, LenInt(tt.number) == tt.expected, "return", tt.expected, "for", tt.number)
  63. }
  64. }
  65. ////////////////////////////////////////////////////////////////
  66. var num []int64
  67. func TestMain(t *testing.T) {
  68. for j := 0; j < 1000; j++ {
  69. num = append(num, rand.Int63n(1000))
  70. }
  71. }
  72. func BenchmarkLenIntLog(b *testing.B) {
  73. n := 0
  74. for i := 0; i < b.N; i++ {
  75. for j := 0; j < 1000; j++ {
  76. n += int(math.Log10(math.Abs(float64(num[j])))) + 1
  77. }
  78. }
  79. }
  80. func BenchmarkLenIntSwitch(b *testing.B) {
  81. n := 0
  82. for i := 0; i < b.N; i++ {
  83. for j := 0; j < 1000; j++ {
  84. n += LenInt(num[j])
  85. }
  86. }
  87. }