From 4488189a752b9c51d1755e8f7546819e0043731c Mon Sep 17 00:00:00 2001 From: cathugger Date: Sat, 6 Apr 2019 21:34:47 +0300 Subject: [PATCH] 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. --- src/yggdrasil/wire.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/yggdrasil/wire.go b/src/yggdrasil/wire.go index 8891f1ab..1bb4d90f 100644 --- a/src/yggdrasil/wire.go +++ b/src/yggdrasil/wire.go @@ -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)) } ////////////////////////////////////////////////////////////////////////////////