mirror of
https://github.com/cwinfo/yggdrasil-go.git
synced 2024-12-23 12:15:39 +00:00
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:
parent
67c670ab4c
commit
4488189a75
@ -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.
|
||||
// Negative integers are mapped to odd integers: -1 -> 1, -2 -> 3, etc.
|
||||
// This means the least significant bit is a sign bit.
|
||||
// This is known as zigzag encoding.
|
||||
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.
|
||||
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))
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
Loading…
Reference in New Issue
Block a user