...

Source file src/github.com/golang/geo/s2/bits_go18.go

Documentation: github.com/golang/geo/s2

     1  // Copyright 2018 Google Inc. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  //go:build !go1.9
    16  // +build !go1.9
    17  
    18  package s2
    19  
    20  // This file is for the bit manipulation code pre-Go 1.9.
    21  
    22  // findMSBSetNonZero64 returns the index (between 0 and 63) of the most
    23  // significant set bit. Passing zero to this function returns zero.
    24  func findMSBSetNonZero64(x uint64) int {
    25  	val := []uint64{0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000, 0xFFFFFFFF00000000}
    26  	shift := []uint64{1, 2, 4, 8, 16, 32}
    27  	var msbPos uint64
    28  	for i := 5; i >= 0; i-- {
    29  		if x&val[i] != 0 {
    30  			x >>= shift[i]
    31  			msbPos |= shift[i]
    32  		}
    33  	}
    34  	return int(msbPos)
    35  }
    36  
    37  const deBruijn64 = 0x03f79d71b4ca8b09
    38  const digitMask = uint64(1<<64 - 1)
    39  
    40  var deBruijn64Lookup = []byte{
    41  	0, 1, 56, 2, 57, 49, 28, 3, 61, 58, 42, 50, 38, 29, 17, 4,
    42  	62, 47, 59, 36, 45, 43, 51, 22, 53, 39, 33, 30, 24, 18, 12, 5,
    43  	63, 55, 48, 27, 60, 41, 37, 16, 46, 35, 44, 21, 52, 32, 23, 11,
    44  	54, 26, 40, 15, 34, 20, 31, 10, 25, 14, 19, 9, 13, 8, 7, 6,
    45  }
    46  
    47  // findLSBSetNonZero64 returns the index (between 0 and 63) of the least
    48  // significant set bit. Passing zero to this function returns zero.
    49  //
    50  // This code comes from trailingZeroBits in https://golang.org/src/math/big/nat.go
    51  // which references (Knuth, volume 4, section 7.3.1).
    52  func findLSBSetNonZero64(x uint64) int {
    53  	return int(deBruijn64Lookup[((x&-x)*(deBruijn64&digitMask))>>58])
    54  }
    55  

View as plain text