scale_int_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package resource
  14. import (
  15. "math"
  16. "math/big"
  17. "testing"
  18. )
  19. func TestScaledValueInternal(t *testing.T) {
  20. tests := []struct {
  21. unscaled *big.Int
  22. scale int
  23. newScale int
  24. want int64
  25. }{
  26. // remain scale
  27. {big.NewInt(1000), 0, 0, 1000},
  28. // scale down
  29. {big.NewInt(1000), 0, -3, 1},
  30. {big.NewInt(1000), 3, 0, 1},
  31. {big.NewInt(0), 3, 0, 0},
  32. // always round up
  33. {big.NewInt(999), 3, 0, 1},
  34. {big.NewInt(500), 3, 0, 1},
  35. {big.NewInt(499), 3, 0, 1},
  36. {big.NewInt(1), 3, 0, 1},
  37. // large scaled value does not lose precision
  38. {big.NewInt(0).Sub(maxInt64, bigOne), 1, 0, (math.MaxInt64-1)/10 + 1},
  39. // large intermidiate result.
  40. {big.NewInt(1).Exp(big.NewInt(10), big.NewInt(100), nil), 100, 0, 1},
  41. // scale up
  42. {big.NewInt(0), 0, 3, 0},
  43. {big.NewInt(1), 0, 3, 1000},
  44. {big.NewInt(1), -3, 0, 1000},
  45. {big.NewInt(1000), -3, 2, 100000000},
  46. {big.NewInt(0).Div(big.NewInt(math.MaxInt64), bigThousand), 0, 3,
  47. (math.MaxInt64 / 1000) * 1000},
  48. }
  49. for i, tt := range tests {
  50. old := (&big.Int{}).Set(tt.unscaled)
  51. got := scaledValue(tt.unscaled, tt.scale, tt.newScale)
  52. if got != tt.want {
  53. t.Errorf("#%d: got = %v, want %v", i, got, tt.want)
  54. }
  55. if tt.unscaled.Cmp(old) != 0 {
  56. t.Errorf("#%d: unscaled = %v, want %v", i, tt.unscaled, old)
  57. }
  58. }
  59. }
  60. func BenchmarkScaledValueSmall(b *testing.B) {
  61. s := big.NewInt(1000)
  62. for i := 0; i < b.N; i++ {
  63. scaledValue(s, 3, 0)
  64. }
  65. }
  66. func BenchmarkScaledValueLarge(b *testing.B) {
  67. s := big.NewInt(math.MaxInt64)
  68. s.Mul(s, big.NewInt(1000))
  69. for i := 0; i < b.N; i++ {
  70. scaledValue(s, 10, 0)
  71. }
  72. }