github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/net/internal/math.go (about)

     1  package internal
     2  
     3  const (
     4  	bitsize       = 32 << (^uint(0) >> 63)
     5  	maxintHeadBit = 1 << (bitsize - 2)
     6  )
     7  
     8  // IsPowerOfTwo reports whether given integer is a power of two.
     9  func IsPowerOfTwo(n int) bool {
    10  	return n&(n-1) == 0
    11  }
    12  
    13  // CeilToPowerOfTwo returns the least power of two integer value greater than
    14  // or equal to n.
    15  func CeilToPowerOfTwo(n int) int {
    16  	if n&maxintHeadBit != 0 && n > maxintHeadBit {
    17  		panic("argument is too large")
    18  	}
    19  	if n <= 2 {
    20  		return 2
    21  	}
    22  	n--
    23  	n = fillBits(n)
    24  	n++
    25  	return n
    26  }
    27  
    28  // FloorToPowerOfTwo returns the greatest power of two integer value less than
    29  // or equal to n.
    30  func FloorToPowerOfTwo(n int) int {
    31  	if n <= 2 {
    32  		return 2
    33  	}
    34  	n = fillBits(n)
    35  	n >>= 1
    36  	n++
    37  	return n
    38  }
    39  
    40  func fillBits(n int) int {
    41  	n |= n >> 1
    42  	n |= n >> 2
    43  	n |= n >> 4
    44  	n |= n >> 8
    45  	n |= n >> 16
    46  	n |= n >> 32
    47  	return n
    48  }