github.com/ltltlt/go-source-code@v0.0.0-20190830023027-95be009773aa/runtime/internal/sys/intrinsics.go (about)

     1  // Copyright 2016 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // +build !386
     6  
     7  package sys
     8  
     9  // Using techniques from http://supertech.csail.mit.edu/papers/debruijn.pdf
    10  
    11  const deBruijn64 = 0x0218a392cd3d5dbf
    12  
    13  var deBruijnIdx64 = [64]byte{
    14  	0, 1, 2, 7, 3, 13, 8, 19,
    15  	4, 25, 14, 28, 9, 34, 20, 40,
    16  	5, 17, 26, 38, 15, 46, 29, 48,
    17  	10, 31, 35, 54, 21, 50, 41, 57,
    18  	63, 6, 12, 18, 24, 27, 33, 39,
    19  	16, 37, 45, 47, 30, 53, 49, 56,
    20  	62, 11, 23, 32, 36, 44, 52, 55,
    21  	61, 22, 43, 51, 60, 42, 59, 58,
    22  }
    23  
    24  const deBruijn32 = 0x04653adf
    25  
    26  var deBruijnIdx32 = [32]byte{
    27  	0, 1, 2, 6, 3, 11, 7, 16,
    28  	4, 14, 12, 21, 8, 23, 17, 26,
    29  	31, 5, 10, 15, 13, 20, 22, 25,
    30  	30, 9, 19, 24, 29, 18, 28, 27,
    31  }
    32  
    33  // Ctz64 counts trailing (low-order) zeroes,
    34  // and if all are zero, then 64.
    35  func Ctz64(x uint64) int {
    36  	x &= -x                      // isolate low-order bit
    37  	y := x * deBruijn64 >> 58    // extract part of deBruijn sequence
    38  	i := int(deBruijnIdx64[y])   // convert to bit index
    39  	z := int((x - 1) >> 57 & 64) // adjustment if zero
    40  	return i + z
    41  }
    42  
    43  // Ctz32 counts trailing (low-order) zeroes,
    44  // and if all are zero, then 32.
    45  func Ctz32(x uint32) int {
    46  	x &= -x                      // isolate low-order bit
    47  	y := x * deBruijn32 >> 27    // extract part of deBruijn sequence
    48  	i := int(deBruijnIdx32[y])   // convert to bit index
    49  	z := int((x - 1) >> 26 & 32) // adjustment if zero
    50  	return i + z
    51  }
    52  
    53  // Bswap64 returns its input with byte order reversed
    54  // 0x0102030405060708 -> 0x0807060504030201
    55  func Bswap64(x uint64) uint64 {
    56  	c8 := uint64(0x00ff00ff00ff00ff)
    57  	a := x >> 8 & c8
    58  	b := (x & c8) << 8
    59  	x = a | b
    60  	c16 := uint64(0x0000ffff0000ffff)
    61  	a = x >> 16 & c16
    62  	b = (x & c16) << 16
    63  	x = a | b
    64  	c32 := uint64(0x00000000ffffffff)
    65  	a = x >> 32 & c32
    66  	b = (x & c32) << 32
    67  	x = a | b
    68  	return x
    69  }
    70  
    71  // Bswap32 returns its input with byte order reversed
    72  // 0x01020304 -> 0x04030201
    73  func Bswap32(x uint32) uint32 {
    74  	c8 := uint32(0x00ff00ff)
    75  	a := x >> 8 & c8
    76  	b := (x & c8) << 8
    77  	x = a | b
    78  	c16 := uint32(0x0000ffff)
    79  	a = x >> 16 & c16
    80  	b = (x & c16) << 16
    81  	x = a | b
    82  	return x
    83  }