cs_string_rw/
write_7_bit_encoded_i32.rs1use std::io;
2
3pub trait Write7BitEncodedI32Ext {
4 fn write_7_bit_encoded_i32(&mut self, n: i32) -> io::Result<()>;
5}
6
7impl<T: io::Write> Write7BitEncodedI32Ext for T {
8 fn write_7_bit_encoded_i32(&mut self, n: i32) -> io::Result<()> {
9 let mut n = n as u32;
10 let mut byte: u8;
11 let mut buff = Vec::<u8>::with_capacity(4);
12 loop {
13 byte = (n & 127) as u8;
14 if n < 128 {
15 break;
16 }
17
18 byte |= 128;
19 n >>= 7;
20 buff.push(byte);
21 }
22
23 buff.push(byte);
24 self.write_all(&buff)
25 }
26}
27
28#[cfg(test)]
29mod tests {
30 use super::*;
31 use crate::write_byte_vec::WriteByteVec;
32 #[test]
33 fn writing_ints() {
34 let mut out = Vec::<u8>::with_capacity(40);
35 let mut writer = WriteByteVec::new(&mut out);
36 writer.write_7_bit_encoded_i32(-1).unwrap();
37 writer.write_7_bit_encoded_i32(-2147483648).unwrap();
38 writer.write_7_bit_encoded_i32(1).unwrap();
39 writer.write_7_bit_encoded_i32(2147483647).unwrap();
40 writer.write_7_bit_encoded_i32(0).unwrap();
41 writer.write_7_bit_encoded_i32(2).unwrap();
42 writer.write_7_bit_encoded_i32(5).unwrap();
43 writer.write_7_bit_encoded_i32(8000000).unwrap();
44 writer.write_7_bit_encoded_i32(160000000).unwrap();
45 writer.write_7_bit_encoded_i32(30000).unwrap();
46 writer.write_7_bit_encoded_i32(-2323232).unwrap();
47 writer.write_7_bit_encoded_i32(-23232).unwrap();
48 assert_eq!(
49 out,
50 [
51 0xff, 0xff, 0xff, 0xff, 0x0f, 0x80, 0x80, 0x80, 0x80, 0x08, 0x01, 0xff, 0xff, 0xff,
52 0xff, 0x07, 0x00, 0x02, 0x05, 0x80, 0xa4, 0xe8, 0x03, 0x80, 0xd0, 0xa5, 0x4c, 0xb0,
53 0xea, 0x01, 0xe0, 0x99, 0xf2, 0xfe, 0x0f, 0xc0, 0xca, 0xfe, 0xff, 0x0f,
54 ]
55 );
56 }
57}