1 // ZigZag endoging used for efficient transfer of signed integers
2 // https://developers.google.com/protocol-buffers/docs/encoding#types
3
4 use crate::rt::compute_raw_varint32_size;
5 use crate::rt::compute_raw_varint64_size;
6
decode_zig_zag_32(n: u32) -> i327 pub(crate) fn decode_zig_zag_32(n: u32) -> i32 {
8 ((n >> 1) as i32) ^ (-((n & 1) as i32))
9 }
10
decode_zig_zag_64(n: u64) -> i6411 pub(crate) fn decode_zig_zag_64(n: u64) -> i64 {
12 ((n >> 1) as i64) ^ (-((n & 1) as i64))
13 }
14
encode_zig_zag_32(n: i32) -> u3215 pub(crate) fn encode_zig_zag_32(n: i32) -> u32 {
16 ((n << 1) ^ (n >> 31)) as u32
17 }
18
encode_zig_zag_64(n: i64) -> u6419 pub(crate) fn encode_zig_zag_64(n: i64) -> u64 {
20 ((n << 1) ^ (n >> 63)) as u64
21 }
22
23 /// Helper trait implemented by integer types which could be encoded as zigzag varint.
24 pub(crate) trait ProtobufVarintZigzag {
25 /// Size of self when encoded as zigzag varint.
len_varint_zigzag(&self) -> u6426 fn len_varint_zigzag(&self) -> u64;
27 }
28
29 impl ProtobufVarintZigzag for i64 {
len_varint_zigzag(&self) -> u6430 fn len_varint_zigzag(&self) -> u64 {
31 compute_raw_varint64_size(encode_zig_zag_64(*self))
32 }
33 }
34
35 impl ProtobufVarintZigzag for i32 {
len_varint_zigzag(&self) -> u6436 fn len_varint_zigzag(&self) -> u64 {
37 compute_raw_varint32_size(encode_zig_zag_32(*self))
38 }
39 }
40
41 #[cfg(test)]
42 mod test {
43
44 use super::decode_zig_zag_32;
45 use super::decode_zig_zag_64;
46 use super::encode_zig_zag_32;
47 use super::encode_zig_zag_64;
48
49 #[test]
test_zig_zag()50 fn test_zig_zag() {
51 fn test_zig_zag_pair_64(decoded: i64, encoded: u64) {
52 assert_eq!(decoded, decode_zig_zag_64(encoded));
53 assert_eq!(encoded, encode_zig_zag_64(decoded));
54 }
55
56 fn test_zig_zag_pair(decoded: i32, encoded: u32) {
57 assert_eq!(decoded, decode_zig_zag_32(encoded));
58 assert_eq!(encoded, encode_zig_zag_32(decoded));
59 test_zig_zag_pair_64(decoded as i64, encoded as u64);
60 }
61
62 test_zig_zag_pair(0, 0);
63 test_zig_zag_pair(-1, 1);
64 test_zig_zag_pair(1, 2);
65 test_zig_zag_pair(-2, 3);
66 test_zig_zag_pair(2147483647, 4294967294);
67 test_zig_zag_pair(-2147483648, 4294967295);
68 test_zig_zag_pair_64(9223372036854775807, 18446744073709551614);
69 test_zig_zag_pair_64(-9223372036854775808, 18446744073709551615);
70 }
71 }
72