github.com/jackc/puddle/v2@v2.2.2-0.20240301145809-72b022bcfc59/log.go (about)

     1  package puddle
     2  
     3  import "unsafe"
     4  
     5  type ints interface {
     6  	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64
     7  }
     8  
     9  // log2Int returns log2 of an integer. This function panics if val < 0. For val
    10  // == 0, returns 0.
    11  func log2Int[T ints](val T) uint8 {
    12  	if val <= 0 {
    13  		panic("log2 of non-positive number does not exist")
    14  	}
    15  
    16  	return log2IntRange(val, 0, uint8(8*unsafe.Sizeof(val)))
    17  }
    18  
    19  func log2IntRange[T ints](val T, begin, end uint8) uint8 {
    20  	length := end - begin
    21  	if length == 1 {
    22  		return begin
    23  	}
    24  
    25  	delim := begin + length/2
    26  	mask := T(1) << delim
    27  	if mask > val {
    28  		return log2IntRange(val, begin, delim)
    29  	} else {
    30  		return log2IntRange(val, delim, end)
    31  	}
    32  }