musli_binary_common/int/
zigzag.rs

1//! Generic [zigzag encoding] for integers.
2//!
3//! [zigzag encoding]: https://en.wikipedia.org/wiki/Variable-length_quantity#Zigzag_encoding
4//!
5//! ```rust
6//! assert_eq!(musli_binary_common::int::zigzag::encode(-1i32), 1u32);
7//! assert_eq!(musli_binary_common::int::zigzag::encode(-2i32), 3u32);
8//! ```
9
10use crate::int::{Signed, Unsigned};
11
12/// Encode an integer into zig-zag encoding.
13#[inline]
14pub fn encode<T>(x: T) -> T::Unsigned
15where
16    T: Signed,
17{
18    (x >> (T::BITS - 1)).unsigned() ^ (x << 1).unsigned()
19}
20
21/// Decode an integer into zig-zag encoding.
22#[inline]
23pub fn decode<T>(x: T) -> T::Signed
24where
25    T: Unsigned,
26{
27    (x >> 1).signed() ^ -(x & T::ONE).signed()
28}