leb128fmt

Function encode_uint_slice

Source
pub fn encode_uint_slice<T, const BITS: u32>(
    value: T,
    output: &mut [u8],
    pos: &mut usize,
) -> Option<usize>
where T: Copy + PartialEq + BitAnd + Shr<u32> + ShrAssign<u32> + From<u8> + UInt, <T as Shr<u32>>::Output: PartialEq<T>, u8: TryFrom<<T as BitAnd<T>>::Output>,
Expand description

Encodes a given value into an output slice using the fixed set of bytes.

§Examples

let mut buffer = vec![254; 10];
let mut pos = 0;
let result = leb128fmt::encode_uint_slice::<_, 32>(0u32, &mut buffer, &mut pos);
assert_eq!(Some(1), result);
assert_eq!(1, pos);
assert_eq!(&[0x00], &buffer[..pos]);

assert_eq!(&[0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());

let result = leb128fmt::encode_uint_slice::<_, 32>(u32::MAX, &mut buffer, &mut pos);
assert_eq!(Some(5), result);
assert_eq!(6, pos);
assert_eq!(&[0xFF, 0xFF, 0xFF, 0xFF, 0x0F], &buffer[1..pos]);

assert_eq!(&[0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());

// Will try to encode even if the output slice is not as big as the maximum
// number of bytes required to output every value for the given BITS
let mut buffer = vec![254; 4];
let mut pos = 0;
let result = leb128fmt::encode_uint_slice::<_, 32>(1028u32, &mut buffer, &mut pos);
assert_eq!(Some(2), result);
assert_eq!(&[0x84, 0x08, 0xFE, 0xFE], buffer.as_slice());

// Will return `None` if the output buffer is not long enough but will have partially written
// the value
let mut buffer = vec![254; 4];
let mut pos = 0;
let result = leb128fmt::encode_uint_slice::<_, 32>(u32::MAX, &mut buffer, &mut pos);
assert_eq!(None, result);
assert_eq!(&[0xFF, 0xFF, 0xFF, 0xFF], buffer.as_slice());

// Will return `None` if the given value cannot be encoded with the given number of bits.
let mut buffer = vec![254; 10];
let mut pos = 0;
let result = leb128fmt::encode_uint_slice::<_, 32>(u64::MAX, &mut buffer, &mut pos);
assert_eq!(None, result);
assert_eq!(&[0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());