pub struct VarintEncoding;
Expand description

Variable-size integer encoding (excepting [ui]8).

Encoding an unsigned integer v (of any type excepting u8) works as follows:

  1. If u < 251, encode it as a single byte with that value.
  2. If 251 <= u < 2**16, encode it as a literal byte 251, followed by a u16 with value u.
  3. If 2**16 <= u < 2**32, encode it as a literal byte 252, followed by a u32 with value u.
  4. If 2**32 <= u < 2**64, encode it as a literal byte 253, followed by a u64 with value u.
  5. If 2**64 <= u < 2**128, encode it as a literal byte 254, followed by a u128 with value u.

Then, for signed integers, we first convert to unsigned using the zigzag algorithm, and then encode them as we do for unsigned integers generally. The reason we use this algorithm is that it encodes those values which are close to zero in less bytes; the obvious algorithm, where we encode the cast values, gives a very large encoding for all negative values.

The zigzag algorithm is defined as follows:

fn zigzag(v: Signed) -> Unsigned {
    match v {
        0 => 0,
        v if v < 0 => |v| * 2 - 1
        v if v > 0 => v * 2
    }
}

And works such that:

assert_eq!(zigzag(0), 0);
assert_eq!(zigzag(-1), 1);
assert_eq!(zigzag(1), 2);
assert_eq!(zigzag(-2), 3);
assert_eq!(zigzag(2), 4);
assert_eq!(zigzag(i64::min_value()), u64::max_value());

Note that u256 and the like are unsupported by this format; if and when they are added to the language, they may be supported via the extension point given by the 255 byte.

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.