1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 pub fn write_to_vec(vec: &mut Vec<u8>, position: &mut usize, byte: u8)
14 if *position == vec.len() {
17 vec[*position] = byte;
23 pub fn write_unsigned_leb128(out: &mut Vec<u8>,
24 start_position: usize,
27 let mut position = start_position;
30 let mut byte = (value & 0x7F) as u8;
36 write_to_vec(out, &mut position, byte);
43 return position - start_position;
46 pub fn read_unsigned_leb128(data: &[u8],
47 start_position: usize)
51 let mut position = start_position;
53 let byte = data[position];
55 result |= ((byte & 0x7F) as u64) << shift;
56 if (byte & 0x80) == 0 {
62 (result, position - start_position)
66 pub fn write_signed_leb128(out: &mut Vec<u8>,
67 start_position: usize,
68 mut value: i64) -> usize {
69 let mut position = start_position;
72 let mut byte = (value as u8) & 0x7f;
74 let more = !((((value == 0 ) && ((byte & 0x40) == 0)) ||
75 ((value == -1) && ((byte & 0x40) != 0))));
77 byte |= 0x80; // Mark this byte to show that more bytes will follow.
80 write_to_vec(out, &mut position, byte);
87 return position - start_position;
90 pub fn read_signed_leb128(data: &[u8],
91 start_position: usize)
95 let mut position = start_position;
99 byte = data[position];
101 result |= ((byte & 0x7F) as i64) << shift;
104 if (byte & 0x80) == 0 {
109 if (shift < 64) && ((byte & 0x40) != 0) {
111 result |= -(1i64 << shift);
114 (result, position - start_position)
118 fn test_unsigned_leb128() {
119 let mut stream = Vec::with_capacity(10000);
122 let pos = stream.len();
123 let bytes_written = write_unsigned_leb128(&mut stream, pos, 3 << x);
124 assert_eq!(stream.len(), pos + bytes_written);
127 let mut position = 0;
129 let expected = 3 << x;
130 let (actual, bytes_read) = read_unsigned_leb128(&stream, position);
131 assert_eq!(expected, actual);
132 position += bytes_read;
134 assert_eq!(stream.len(), position);
138 fn test_signed_leb128() {
139 let mut values = Vec::new();
143 values.push(i * 123457i64);
147 let mut stream = Vec::new();
150 let pos = stream.len();
151 let bytes_written = write_signed_leb128(&mut stream, pos, x);
152 assert_eq!(stream.len(), pos + bytes_written);
157 let (value, bytes_read) = read_signed_leb128(&mut stream, pos);
159 assert_eq!(x, value);
161 assert_eq!(pos, stream.len());