musli/int/
zigzag.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//! Generic [zigzag encoding] for integers.
//!
//! [zigzag encoding]: https://en.wikipedia.org/wiki/Variable-length_quantity#Zigzag_encoding

use super::{Signed, Unsigned};

/// Encode an integer into zig-zag encoding.
#[inline]
pub fn encode<T>(x: T) -> T::Unsigned
where
    T: Signed,
{
    (x >> (T::BITS - 1)).unsigned() ^ (x << 1).unsigned()
}

/// Decode an integer into zig-zag encoding.
#[inline]
pub fn decode<T>(x: T) -> T::Signed
where
    T: Unsigned,
{
    (x >> 1).signed() ^ -(x & T::ONE).signed()
}