github.com/pidato/unsafe@v0.1.4/memory/util.go (about)

     1  package memory
     2  
     3  // divOrZero safely divides a by b or returns zero if either are zero
     4  func divOrZero(a, b int64) int64 {
     5  	if a == 0 || b == 0 {
     6  		return 0
     7  	}
     8  	return a / b
     9  }
    10  
    11  func toMicros(v int64) int64 {
    12  	return divOrZero(v, 1000)
    13  }
    14  
    15  func toMillis(v int64) int64 {
    16  	return divOrZero(v, 1000000)
    17  }
    18  
    19  const (
    20  	nanosSuffix   = "ns"
    21  	microsSuffix  = "µs"
    22  	millisSuffix  = "ms"
    23  	secondsSuffix = "secs"
    24  )
    25  
    26  func toTimeName(v int64) string {
    27  	switch {
    28  	case v < 1000:
    29  		return nanosSuffix
    30  	case v < 1000000:
    31  		return microsSuffix
    32  	case v < 1000000000:
    33  		return millisSuffix
    34  	default:
    35  		return secondsSuffix
    36  	}
    37  }
    38  
    39  const (
    40  	bitsize       = 32 << (^uint(0) >> 63)
    41  	maxint        = int(1<<(bitsize-1) - 1)
    42  	maxintHeadBit = 1 << (bitsize - 2)
    43  )
    44  
    45  // LogarithmicRange iterates from ceiled to power of two min to max,
    46  // calling cb on each iteration.
    47  func LogarithmicRange(min, max int, cb func(int)) {
    48  	if min == 0 {
    49  		min = 1
    50  	}
    51  	for n := ceilToPowerOfTwo(min); n <= max; n <<= 1 {
    52  		cb(n)
    53  	}
    54  }
    55  
    56  // IsPowerOfTwo reports whether given integer is a power of two.
    57  func IsPowerOfTwo(n int) bool {
    58  	return n&(n-1) == 0
    59  }
    60  
    61  // ceilToPowerOfTwo returns the least power of two integer value greater than
    62  // or equal to n.
    63  func ceilToPowerOfTwo(n int) int {
    64  	if n&maxintHeadBit != 0 && n > maxintHeadBit {
    65  		panic("argument is too large")
    66  	}
    67  	if n <= 2 {
    68  		return n
    69  	}
    70  	n--
    71  	n = fillBits(n)
    72  	n++
    73  	return n
    74  }
    75  
    76  // FloorToPowerOfTwo returns the greatest power of two integer value less than
    77  // or equal to n.
    78  func FloorToPowerOfTwo(n int) int {
    79  	if n <= 2 {
    80  		return n
    81  	}
    82  	n = fillBits(n)
    83  	n >>= 1
    84  	n++
    85  	return n
    86  }
    87  
    88  func fillBits(n int) int {
    89  	n |= n >> 1
    90  	n |= n >> 2
    91  	n |= n >> 4
    92  	n |= n >> 8
    93  	n |= n >> 16
    94  	n |= n >> 32
    95  	return n
    96  }