1use std::io::Write;
2use std::io;
3use std::u16;
4use bitstream::LsbWriter;
5use byteorder::{LittleEndian, WriteBytesExt};
67#[cfg(test)]
8const BLOCK_SIZE: u16 = 32000;
910const STORED_FIRST_BYTE: u8 = 0b0000_0000;
11pub const STORED_FIRST_BYTE_FINAL: u8 = 0b0000_0001;
12pub const MAX_STORED_BLOCK_LENGTH: usize = (u16::MAX as usize) / 2;
1314pub fn write_stored_header(writer: &mut LsbWriter, final_block: bool) {
15let header = if final_block {
16 STORED_FIRST_BYTE_FINAL
17 } else {
18 STORED_FIRST_BYTE
19 };
20// Write the block header
21writer.write_bits(header.into(), 3);
22// Flush the writer to make sure we are aligned to the byte boundary.
23writer.flush_raw();
24}
2526// Compress one stored block (excluding the header)
27pub fn compress_block_stored<W: Write>(input: &[u8], writer: &mut W) -> io::Result<usize> {
28if input.len() > u16::max_value() as usize {
29return Err(io::Error::new(
30 io::ErrorKind::InvalidInput,
31"Stored block too long!",
32 ));
33 };
34// The header is written before this function.
35 // The next two bytes indicates the length
36writer.write_u16::<LittleEndian>(input.len() as u16)?;
37// the next two after the length is the ones complement of the length
38writer.write_u16::<LittleEndian>(!input.len() as u16)?;
39// After this the data is written directly with no compression
40writer.write(input)
41}
4243#[cfg(test)]
44pub fn compress_data_stored(input: &[u8]) -> Vec<u8> {
45let block_length = BLOCK_SIZE as usize;
4647let mut output = Vec::with_capacity(input.len() + 2);
48let mut i = input.chunks(block_length).peekable();
49while let Some(chunk) = i.next() {
50let last_chunk = i.peek().is_none();
51// First bit tells us if this is the final chunk
52 // the next two details compression type (none in this case)
53let first_byte = if last_chunk {
54 STORED_FIRST_BYTE_FINAL
55 } else {
56 STORED_FIRST_BYTE
57 };
58 output.write(&[first_byte]).unwrap();
5960 compress_block_stored(chunk, &mut output).unwrap();
61 }
62 output
63}
646566#[cfg(test)]
67mod test {
68use super::*;
69use test_utils::decompress_to_end;
7071#[test]
72fn no_compression_one_chunk() {
73let test_data = vec![1u8, 2, 3, 4, 5, 6, 7, 8];
74let compressed = compress_data_stored(&test_data);
75let result = decompress_to_end(&compressed);
76assert_eq!(test_data, result);
77 }
7879#[test]
80fn no_compression_multiple_chunks() {
81let test_data = vec![32u8; 40000];
82let compressed = compress_data_stored(&test_data);
83let result = decompress_to_end(&compressed);
84assert_eq!(test_data, result);
85 }
8687#[test]
88fn no_compression_string() {
89let test_data = String::from(
90"This is some text, this is some more text, this is even \
91 more text, lots of text here.",
92 ).into_bytes();
93let compressed = compress_data_stored(&test_data);
94let result = decompress_to_end(&compressed);
95assert_eq!(test_data, result);
96 }
97}