/rust/registry/src/index.crates.io-6f17d22bba15001f/protobuf-3.2.0/src/zigzag.rs
Line | Count | Source (jump to first uncovered line) |
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 | | |
7 | 0 | pub(crate) fn decode_zig_zag_32(n: u32) -> i32 { |
8 | 0 | ((n >> 1) as i32) ^ (-((n & 1) as i32)) |
9 | 0 | } |
10 | | |
11 | 0 | pub(crate) fn decode_zig_zag_64(n: u64) -> i64 { |
12 | 0 | ((n >> 1) as i64) ^ (-((n & 1) as i64)) |
13 | 0 | } |
14 | | |
15 | 0 | pub(crate) fn encode_zig_zag_32(n: i32) -> u32 { |
16 | 0 | ((n << 1) ^ (n >> 31)) as u32 |
17 | 0 | } |
18 | | |
19 | 0 | pub(crate) fn encode_zig_zag_64(n: i64) -> u64 { |
20 | 0 | ((n << 1) ^ (n >> 63)) as u64 |
21 | 0 | } |
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. |
26 | | fn len_varint_zigzag(&self) -> u64; |
27 | | } |
28 | | |
29 | | impl ProtobufVarintZigzag for i64 { |
30 | 0 | fn len_varint_zigzag(&self) -> u64 { |
31 | 0 | compute_raw_varint64_size(encode_zig_zag_64(*self)) |
32 | 0 | } |
33 | | } |
34 | | |
35 | | impl ProtobufVarintZigzag for i32 { |
36 | 0 | fn len_varint_zigzag(&self) -> u64 { |
37 | 0 | compute_raw_varint32_size(encode_zig_zag_32(*self)) |
38 | 0 | } |
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] |
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 | | } |