github.com/vescale/zgraph@v0.0.0-20230410094002-959c02d50f95/internal/mathutil/math_test.go (about) 1 // Copyright 2019 PingCAP, Inc. 2 // 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 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package mathutil 16 17 import ( 18 "math/rand" 19 "strconv" 20 "testing" 21 22 "github.com/stretchr/testify/require" 23 ) 24 25 func TestStrLenOfUint64Fast(t *testing.T) { 26 t.Run("RandomInput", func(t *testing.T) { 27 for i := 0; i < 1000000; i++ { 28 num := rand.Uint64() 29 expected := len(strconv.FormatUint(num, 10)) 30 actual := StrLenOfUint64Fast(num) 31 require.Equal(t, expected, actual) 32 } 33 }) 34 35 t.Run("ManualInput", func(t *testing.T) { 36 nums := [22]uint64{0, 37 1, 12, 123, 1234, 12345, 38 123456, 1234567, 12345678, 123456789, 1234567890, 39 1234567891, 12345678912, 123456789123, 1234567891234, 12345678912345, 40 123456789123456, 1234567891234567, 12345678912345678, 123456789123456789, 41 123456789123457890, 42 ^uint64(0), 43 } 44 for _, num := range nums { 45 expected := len(strconv.FormatUint(num, 10)) 46 actual := StrLenOfUint64Fast(num) 47 require.Equal(t, expected, actual) 48 } 49 }) 50 } 51 52 func TestMaxMin(t *testing.T) { 53 require.Equal(t, 1, Min(1, 2)) 54 require.Equal(t, 1, Min(2, 1)) 55 require.Equal(t, 1, Min(4, 2, 1, 3)) 56 require.Equal(t, 1, Min(1, 1)) 57 58 require.Equal(t, 2, Max(1, 2)) 59 require.Equal(t, 2, Max(2, 1)) 60 require.Equal(t, 4, Max(4, 2, 1, 3)) 61 require.Equal(t, 1, Max(1, 1)) 62 63 require.Equal(t, int64(1), Min(int64(1), int64(2))) 64 require.Equal(t, int64(2), Max(int64(2), int64(1))) 65 require.Equal(t, int64(1), Min(int64(4), int64(2), int64(1), int64(3))) 66 require.Equal(t, int64(1), Max(int64(1), int64(1))) 67 require.Equal(t, 1.0, Min(4.0, 2.0, 1.0, 3.0)) 68 require.Equal(t, 4.0, Max(4.0, 2.0, 1.0, 3.0)) 69 70 require.Equal(t, "ab", Min("ab", "xy")) 71 require.Equal(t, "xy", Max("ab", "xy")) 72 require.Equal(t, "ab", Max("ab", "ab")) 73 } 74 75 func TestClamp(t *testing.T) { 76 require.Equal(t, 3, Clamp(100, 1, 3)) 77 require.Equal(t, 2.0, Clamp(float64(2), 1.0, 3.0)) 78 require.Equal(t, float32(1.0), Clamp(float32(0), 1.0, 3.0)) 79 require.Equal(t, 1, Clamp(0, 1, 1)) 80 require.Equal(t, 1, Clamp(100, 1, 1)) 81 require.Equal(t, "ab", Clamp("aa", "ab", "xy")) 82 require.Equal(t, "xy", Clamp("yy", "ab", "xy")) 83 require.Equal(t, "ab", Clamp("ab", "ab", "ab")) 84 }