wire: cleaner and faster wire_intToUint and wire_intFromUint

Bit operations are much faster on most processors than multiplication.
Also specify that it's zigzag to ease finding additional documentation for it.
This commit is contained in:
cathugger 2019-04-06 21:34:47 +03:00
parent 67c670ab4c
commit 4488189a75
No known key found for this signature in database
GPG Key ID: 9BADDA2DAF6F01A8

View File

@ -72,13 +72,16 @@ func wire_decode_uint64(bs []byte) (uint64, int) {
// Non-negative integers are mapped to even integers: 0 -> 0, 1 -> 2, etc. // Non-negative integers are mapped to even integers: 0 -> 0, 1 -> 2, etc.
// Negative integers are mapped to odd integers: -1 -> 1, -2 -> 3, etc. // Negative integers are mapped to odd integers: -1 -> 1, -2 -> 3, etc.
// This means the least significant bit is a sign bit. // This means the least significant bit is a sign bit.
// This is known as zigzag encoding.
func wire_intToUint(i int64) uint64 { func wire_intToUint(i int64) uint64 {
return ((uint64(-(i+1))<<1)|0x01)*(uint64(i)>>63) + (uint64(i)<<1)*(^uint64(i)>>63) // signed arithmetic shift
return uint64((i >> 63) ^ (i << 1))
} }
// Converts uint64 back to int64, genreally when being read from the wire. // Converts uint64 back to int64, genreally when being read from the wire.
func wire_intFromUint(u uint64) int64 { func wire_intFromUint(u uint64) int64 {
return int64(u&0x01)*(-int64(u>>1)-1) + int64(^u&0x01)*int64(u>>1) // non-arithmetic shift
return int64((u >> 1) ^ -(u & 1))
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////