2 pub fn write_to_vec(vec: &mut Vec<u8>, byte: u8) {
6 #[cfg(target_pointer_width = "32")]
7 const USIZE_LEB128_SIZE: usize = 5;
8 #[cfg(target_pointer_width = "64")]
9 const USIZE_LEB128_SIZE: usize = 10;
11 macro_rules! leb128_size {
16 (usize) => (USIZE_LEB128_SIZE);
19 macro_rules! impl_write_unsigned_leb128 {
20 ($fn_name:ident, $int_ty:ident) => (
22 pub fn $fn_name(out: &mut Vec<u8>, mut value: $int_ty) {
23 for _ in 0 .. leb128_size!($int_ty) {
24 let mut byte = (value & 0x7F) as u8;
30 write_to_vec(out, byte);
40 impl_write_unsigned_leb128!(write_u16_leb128, u16);
41 impl_write_unsigned_leb128!(write_u32_leb128, u32);
42 impl_write_unsigned_leb128!(write_u64_leb128, u64);
43 impl_write_unsigned_leb128!(write_u128_leb128, u128);
44 impl_write_unsigned_leb128!(write_usize_leb128, usize);
47 macro_rules! impl_read_unsigned_leb128 {
48 ($fn_name:ident, $int_ty:ident) => (
50 pub fn $fn_name(slice: &[u8]) -> ($int_ty, usize) {
51 let mut result: $int_ty = 0;
55 for _ in 0 .. leb128_size!($int_ty) {
57 *slice.get_unchecked(position)
60 result |= ((byte & 0x7F) as $int_ty) << shift;
61 if (byte & 0x80) == 0 {
67 // Do a single bounds check at the end instead of for every byte.
68 assert!(position <= slice.len());
75 impl_read_unsigned_leb128!(read_u16_leb128, u16);
76 impl_read_unsigned_leb128!(read_u32_leb128, u32);
77 impl_read_unsigned_leb128!(read_u64_leb128, u64);
78 impl_read_unsigned_leb128!(read_u128_leb128, u128);
79 impl_read_unsigned_leb128!(read_usize_leb128, usize);
84 /// encodes an integer using signed leb128 encoding and stores
85 /// the result using a callback function.
87 /// The callback `write` is called once for each position
88 /// that is to be written to with the byte to be encoded
90 pub fn write_signed_leb128_to<W>(mut value: i128, mut write: W)
94 let mut byte = (value as u8) & 0x7f;
96 let more = !(((value == 0) && ((byte & 0x40) == 0)) ||
97 ((value == -1) && ((byte & 0x40) != 0)));
100 byte |= 0x80; // Mark this byte to show that more bytes will follow.
112 pub fn write_signed_leb128(out: &mut Vec<u8>, value: i128) {
113 write_signed_leb128_to(value, |v| write_to_vec(out, v))
117 pub fn read_signed_leb128(data: &[u8], start_position: usize) -> (i128, usize) {
120 let mut position = start_position;
124 byte = data[position];
126 result |= i128::from(byte & 0x7F) << shift;
129 if (byte & 0x80) == 0 {
134 if (shift < 64) && ((byte & 0x40) != 0) {
136 result |= -(1 << shift);
139 (result, position - start_position)