github.com/seeker-insurance/kit@v0.0.13/umath/umath.go (about) 1 //Package umath contains helper functions for math on unsigned integers 2 package umath 3 4 import ( 5 "github.com/seeker-insurance/kit/imath" 6 ) 7 8 const ( 9 is64bit = uint64(^uint(0)) == ^uint64(0) 10 ) 11 12 //Min returns the smallest integer argument. 13 func Min(n uint, a ...uint) uint { 14 min := n 15 for _, m := range a { 16 if m < min { 17 min = m 18 } 19 } 20 return min 21 } 22 23 //Sum returns the sum of it's arguments. Sum() is 0 24 func Sum(a ...uint) uint { 25 var sum uint 26 for _, u := range a { 27 sum += u 28 } 29 return sum 30 } 31 32 func Range(start, stop uint, step int) []uint { 33 if (start > stop && step > 0) || 34 (start < stop && step < 0) || step == 0 { 35 return nil 36 } 37 a := make([]uint, 0, imath.Abs(int(start-stop)/imath.Abs(step))) 38 if step < 0 { 39 for n := int(start); n > int(stop); n += step { 40 a = append(a, uint(n)) 41 } 42 return a 43 } 44 45 for n := int(start); n < int(stop); n += step { 46 a = append(a, uint(n)) 47 } 48 49 return a 50 } 51 52 //Product returns the product of it's arguments. Product() is 1. 53 func Product(a ...uint) uint { 54 product := uint(1) 55 for _, u := range a { 56 product *= u 57 } 58 return product 59 } 60 61 //Max returns the largest integer argument. 62 func Max(n uint, a ...uint) uint { 63 max := n 64 for _, m := range a { 65 if m > max { 66 max = m 67 } 68 } 69 return max 70 } 71 72 //Clamp takes an uint n, returns low if n < low, high if n > high, and n otherwise. 73 func Clamp(n, low, high uint) uint { 74 if n < low { 75 return low 76 } else if n > high { 77 return high 78 } 79 return n 80 } 81 82 //Pow is an efficent implementation of exponentiation by squaring. 83 func Pow(base, exp uint) uint { 84 result := uint(1) 85 for ; exp > 0; exp >>= 1 { 86 if exp&1 > 0 { 87 result *= base 88 } 89 base *= base 90 } 91 return result 92 }