github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/bit/scan.go (about)

     1  package bit
     2  
     3  const NotFound = 0xFF
     4  
     5  // ScanRight scans from the highest to the lowest bit
     6  // if x == 0 it will return NotFound
     7  func ScanRight(x uint64) uint {
     8  	if x == 0 {
     9  		return NotFound
    10  	}
    11  	n := uint(0)
    12  
    13  	for x > scanTableMask {
    14  		x >>= scanTableBits
    15  		n += scanTableBits
    16  	}
    17  	return uint(scanRightTable[x]) + n
    18  }
    19  
    20  func slowScanRight(x uint64) uint {
    21  	for k := 63; k >= 0; k -= 1 {
    22  		if x&(1<<byte(k)) != 0 {
    23  			return uint(k)
    24  		}
    25  	}
    26  	return NotFound
    27  }
    28  
    29  // ScanLeft scans from the lowest to the highest bit
    30  // if x == 0 it will return NotFound
    31  func ScanLeft(x uint64) uint {
    32  	if x == 0 {
    33  		return NotFound
    34  	}
    35  
    36  	n := uint(0)
    37  	for x&scanTableMask == 0 {
    38  		n += scanTableBits
    39  		x >>= scanTableBits
    40  	}
    41  	return uint(scanLeftTable[x&scanTableMask]) + n
    42  }
    43  
    44  func slowScanLeft(x uint64) uint {
    45  	for k := byte(0); k < 64; k += 1 {
    46  		if x&(1<<k) != 0 {
    47  			return uint(k)
    48  		}
    49  	}
    50  	return NotFound
    51  }