5
0
mirror of https://github.com/cwinfo/yggdrasil-go.git synced 2024-11-10 05:10:26 +00:00

Merge pull request #407 from cathugger/develop

wire: cleaner and faster wire_intToUint and wire_intFromUint
This commit is contained in:
Arceliar 2019-04-11 00:28:27 -05:00 committed by GitHub
commit 53fba06382
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

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))
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////