leb128fmt

Function encode_fixed_sint_slice

Source
pub fn encode_fixed_sint_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<i8> + SInt, <T as Shr<u32>>::Output: PartialEq<T>, u8: TryFrom<<T as BitAnd>::Output>,
Expand description

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

§Examples

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

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

let result = leb128fmt::encode_fixed_sint_slice::<_, 32>(i32::MAX, &mut buffer, &mut pos);
assert_eq!(Some(5), result);
assert_eq!(10, pos);
assert_eq!(&[0xFF, 0xFF, 0xFF, 0xFF, 0x07], &buffer[5..pos]);

assert_eq!(&[0x80, 0x80, 0x80, 0x80, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x07], buffer.as_slice());

// Will return `None` if the output buffer is not long enough.
let mut buffer = vec![254; 4];
let mut pos = 0;
let result = leb128fmt::encode_fixed_sint_slice::<_, 32>(i32::MAX, &mut buffer, &mut pos);
assert_eq!(None, result);
assert_eq!(&[0xFE, 0xFE, 0xFE, 0xFE], 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_fixed_sint_slice::<_, 32>(i64::MAX, &mut buffer, &mut pos);
assert_eq!(None, result);
assert_eq!(&[0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE], buffer.as_slice());