use std::io;
pub trait Write7BitEncodedI32Ext {
fn write_7_bit_encoded_i32(&mut self, n: i32) -> io::Result<()>;
}
impl<T: io::Write> Write7BitEncodedI32Ext for T {
fn write_7_bit_encoded_i32(&mut self, n: i32) -> io::Result<()> {
let mut n = n as u32;
let mut byte: u8;
let mut buff = Vec::<u8>::with_capacity(4);
loop {
byte = (n & 127) as u8;
if n < 128 {
break;
}
byte |= 128;
n >>= 7;
buff.push(byte);
}
buff.push(byte);
self.write_all(&buff)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::write_byte_vec::WriteByteVec;
#[test]
fn writing_ints() {
let mut out = Vec::<u8>::with_capacity(40);
let mut writer = WriteByteVec::new(&mut out);
writer.write_7_bit_encoded_i32(-1).unwrap();
writer.write_7_bit_encoded_i32(-2147483648).unwrap();
writer.write_7_bit_encoded_i32(1).unwrap();
writer.write_7_bit_encoded_i32(2147483647).unwrap();
writer.write_7_bit_encoded_i32(0).unwrap();
writer.write_7_bit_encoded_i32(2).unwrap();
writer.write_7_bit_encoded_i32(5).unwrap();
writer.write_7_bit_encoded_i32(8000000).unwrap();
writer.write_7_bit_encoded_i32(160000000).unwrap();
writer.write_7_bit_encoded_i32(30000).unwrap();
writer.write_7_bit_encoded_i32(-2323232).unwrap();
writer.write_7_bit_encoded_i32(-23232).unwrap();
assert_eq!(
out,
[
0xff, 0xff, 0xff, 0xff, 0x0f, 0x80, 0x80, 0x80, 0x80, 0x08, 0x01, 0xff, 0xff, 0xff,
0xff, 0x07, 0x00, 0x02, 0x05, 0x80, 0xa4, 0xe8, 0x03, 0x80, 0xd0, 0xa5, 0x4c, 0xb0,
0xea, 0x01, 0xe0, 0x99, 0xf2, 0xfe, 0x0f, 0xc0, 0xca, 0xfe, 0xff, 0x0f,
]
);
}
}