Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// The functions are named (CountBits)?(Byte|Uint64)s?. The plural forms are for slices. The CountBits.+ forms are Population Count only, where the bare-type forms are Hamming distance.
//
// import 'github.com/steakknife/hamming'
//
// // ...
//
// // hamming distance between values
// hamming.Byte(0xFF, 0x00) // 8
// hamming.Byte(0x00, 0x00) // 0
//
// // just count bits in a byte
// hamming.CountBitsByte(0xA5), // 4
//
packagehamming
// SSE4.x PopCnt is 10x slower
...
...
@@ -21,11 +46,29 @@ func Uint64(x, y uint64) int {
returnCountBitsUint64(x^y)
}
// hamming distance of two uint64 buffers, of which the size of the first argument is used for both (panics if b1 is smaller than b0, does not compare b1 beyond length of b0)
funcUint64s(b0,b1[]uint64)int{
d:=0
fori,x:=rangeb0{
d+=Uint64(x,b1[i])
}
returnd
}
// hamming distance of two bytes
funcByte(x,ybyte)int{
returnCountBitsByte(x^y)
}
// hamming distance of two byte buffers, of which the size of the first argument is used for both (panics if b1 is smaller than b0, does not compare b1 beyond length of b0)
funcBytes(b0,b1[]byte)int{
d:=0
fori,x:=rangeb0{
d+=Byte(x,b1[i])
}
returnd
}
funcCountBitsUint64(xuint64)int{
x-=(x>>1)&m1// put count of each 2 bits into those 2 bits
x=(x&m2)+((x>>2)&m2)// put count of each 4 bits into those 4 bits
...
...
@@ -33,6 +76,22 @@ func CountBitsUint64(x uint64) int {
returnint((x*h01)>>56)// returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ...