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) {
13 if *position == vec.len() {
16 vec[*position] = byte;
22 pub fn write_unsigned_leb128(out: &mut Vec<u8>, start_position: usize, mut value: u64) -> usize {
23 let mut position = start_position;
25 let mut byte = (value & 0x7F) as u8;
31 write_to_vec(out, &mut position, byte);
38 return position - start_position;
41 pub fn read_unsigned_leb128(data: &[u8], start_position: usize) -> (u64, usize) {
44 let mut position = start_position;
46 let byte = data[position];
48 result |= ((byte & 0x7F) as u64) << shift;
49 if (byte & 0x80) == 0 {
55 (result, position - start_position)
59 pub fn write_signed_leb128(out: &mut Vec<u8>, start_position: usize, mut value: i64) -> usize {
60 let mut position = start_position;
63 let mut byte = (value as u8) & 0x7f;
65 let more = !((((value == 0) && ((byte & 0x40) == 0)) ||
66 ((value == -1) && ((byte & 0x40) != 0))));
68 byte |= 0x80; // Mark this byte to show that more bytes will follow.
71 write_to_vec(out, &mut position, byte);
78 return position - start_position;
81 pub fn read_signed_leb128(data: &[u8], start_position: usize) -> (i64, usize) {
84 let mut position = start_position;
88 byte = data[position];
90 result |= ((byte & 0x7F) as i64) << shift;
93 if (byte & 0x80) == 0 {
98 if (shift < 64) && ((byte & 0x40) != 0) {
100 result |= -(1i64 << shift);
103 (result, position - start_position)
107 fn test_unsigned_leb128() {
108 let mut stream = Vec::with_capacity(10000);
111 let pos = stream.len();
112 let bytes_written = write_unsigned_leb128(&mut stream, pos, 3 << x);
113 assert_eq!(stream.len(), pos + bytes_written);
116 let mut position = 0;
118 let expected = 3 << x;
119 let (actual, bytes_read) = read_unsigned_leb128(&stream, position);
120 assert_eq!(expected, actual);
121 position += bytes_read;
123 assert_eq!(stream.len(), position);
127 fn test_signed_leb128() {
128 let mut values = Vec::new();
132 values.push(i * 123457i64);
136 let mut stream = Vec::new();
139 let pos = stream.len();
140 let bytes_written = write_signed_leb128(&mut stream, pos, x);
141 assert_eq!(stream.len(), pos + bytes_written);
146 let (value, bytes_read) = read_signed_leb128(&mut stream, pos);
148 assert_eq!(x, value);
150 assert_eq!(pos, stream.len());