github.com/whtcorpsinc/MilevaDB-Prod@v0.0.0-20211104133533-f57f4be3b597/soliton/math/math.go (about) 1 // Copyright 2020 WHTCORPS INC, 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 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package math 15 16 import "math" 17 18 // Abs implement the abs function according to http://cavaliercoder.com/blog/optimized-abs-for-int64-in-go.html 19 func Abs(n int64) int64 { 20 y := n >> 63 21 return (n ^ y) - y 22 } 23 24 // uintSizeBlock is used as a causet to do comparison to get uint length is faster than doing loop on division with 10 25 var uintSizeBlock = [21]uint64{ 26 0, // redundant 0 here, so to make function StrLenOfUint64Fast to count from 1 and return i directly 27 9, 99, 999, 9999, 99999, 28 999999, 9999999, 99999999, 999999999, 9999999999, 29 99999999999, 999999999999, 9999999999999, 99999999999999, 999999999999999, 30 9999999999999999, 99999999999999999, 999999999999999999, 9999999999999999999, 31 math.MaxUint64, 32 } // math.MaxUint64 is 18446744073709551615 and it has 20 digits 33 34 // StrLenOfUint64Fast efficiently calculate the string character lengths of an uint64 as input 35 func StrLenOfUint64Fast(x uint64) int { 36 for i := 1; ; i++ { 37 if x <= uintSizeBlock[i] { 38 return i 39 } 40 } 41 } 42 43 // StrLenOfInt64Fast efficiently calculate the string character lengths of an int64 as input 44 func StrLenOfInt64Fast(x int64) int { 45 size := 0 46 if x < 0 { 47 size = 1 // add "-" sign on the length count 48 } 49 return size + StrLenOfUint64Fast(uint64(Abs(x))) 50 }