1 macro_rules! impl_write_unsigned_leb128 {
2 ($fn_name:ident, $int_ty:ident) => {
4 pub fn $fn_name(out: &mut Vec<u8>, mut value: $int_ty) {
10 out.push(((value & 0x7f) | 0x80) as u8);
18 impl_write_unsigned_leb128!(write_u16_leb128, u16);
19 impl_write_unsigned_leb128!(write_u32_leb128, u32);
20 impl_write_unsigned_leb128!(write_u64_leb128, u64);
21 impl_write_unsigned_leb128!(write_u128_leb128, u128);
22 impl_write_unsigned_leb128!(write_usize_leb128, usize);
24 macro_rules! impl_read_unsigned_leb128 {
25 ($fn_name:ident, $int_ty:ident) => {
27 pub fn $fn_name(slice: &[u8]) -> ($int_ty, usize) {
32 let byte = slice[position];
34 if (byte & 0x80) == 0 {
35 result |= (byte as $int_ty) << shift;
36 return (result, position);
38 result |= ((byte & 0x7F) as $int_ty) << shift;
46 impl_read_unsigned_leb128!(read_u16_leb128, u16);
47 impl_read_unsigned_leb128!(read_u32_leb128, u32);
48 impl_read_unsigned_leb128!(read_u64_leb128, u64);
49 impl_read_unsigned_leb128!(read_u128_leb128, u128);
50 impl_read_unsigned_leb128!(read_usize_leb128, usize);
53 /// encodes an integer using signed leb128 encoding and stores
54 /// the result using a callback function.
56 /// The callback `write` is called once for each position
57 /// that is to be written to with the byte to be encoded
59 pub fn write_signed_leb128_to<W>(mut value: i128, mut write: W)
64 let mut byte = (value as u8) & 0x7f;
67 !(((value == 0) && ((byte & 0x40) == 0)) || ((value == -1) && ((byte & 0x40) != 0)));
70 byte |= 0x80; // Mark this byte to show that more bytes will follow.
82 pub fn write_signed_leb128(out: &mut Vec<u8>, value: i128) {
83 write_signed_leb128_to(value, |v| out.push(v))
87 pub fn read_signed_leb128(data: &[u8], start_position: usize) -> (i128, usize) {
90 let mut position = start_position;
94 byte = data[position];
96 result |= i128::from(byte & 0x7F) << shift;
99 if (byte & 0x80) == 0 {
104 if (shift < 64) && ((byte & 0x40) != 0) {
106 result |= -(1 << shift);
109 (result, position - start_position)