lzw-0.10.0/.gitignore000064400007650000765000000000221250646357200126320ustar0000000000000000target Cargo.lock lzw-0.10.0/Cargo.toml000064400007650000765000000014661266464113600126060ustar0000000000000000# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "lzw" version = "0.10.0" authors = ["nwin "] description = "LZW compression and decompression." readme = "README.md" license = "MIT/Apache-2.0" repository = "https://github.com/nwin/lzw.git" [features] default = ["raii_no_panic"] raii_no_panic = [] lzw-0.10.0/Cargo.toml.orig000064400007650000765000000004511266464113600135360ustar0000000000000000[package] name = "lzw" version = "0.10.0" license = "MIT/Apache-2.0" description = "LZW compression and decompression." authors = ["nwin "] readme = "README.md" repository = "https://github.com/nwin/lzw.git" [features] default = ["raii_no_panic"] raii_no_panic = []lzw-0.10.0/examples/lzw-compress.rs000064400007650000765000000013731253500402100154630ustar0000000000000000//! Compresses the input from stdin and writes the result to stdout. extern crate lzw; use std::io::{self, Write, BufRead}; fn main() { match (|| -> io::Result<()> { let mut encoder = try!( lzw::Encoder::new(lzw::LsbWriter::new(io::stdout()), 8) ); let stdin = io::stdin(); let mut stdin = stdin.lock(); loop { let len = { let buf = try!(stdin.fill_buf()); try!(encoder.encode_bytes(buf)); buf.len() }; if len == 0 { break } stdin.consume(len); } Ok(()) })() { Ok(()) => (), Err(err) => { let _ = write!(io::stderr(), "{}", err); } } }lzw-0.10.0/examples/lzw-decompress.rs000064400007650000765000000016371263546246300160220ustar0000000000000000//! Decompresses the input from stdin and writes the result to stdout. extern crate lzw; use std::io::{self, Write, BufWriter, BufRead}; fn main() { match (|| -> io::Result<()> { let mut decoder = lzw::Decoder::new(lzw::LsbReader::new(), 8) ; let stdout = io::stdout(); let mut stdout = BufWriter::new(stdout.lock()); let stdin = io::stdin(); let mut stdin = stdin.lock(); loop { let len = { let buf = try!(stdin.fill_buf()); if buf.len() == 0 { break } let (len, bytes) = try!(decoder.decode_bytes(buf)); try!(stdout.write_all(bytes)); len }; stdin.consume(len); } Ok(()) })() { Ok(()) => (), Err(err) => { let _ = write!(io::stderr(), "{}", err); } } }lzw-0.10.0/LICENSE-APACHE000064400007650000765000000251361266463774100126110ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.lzw-0.10.0/LICENSE-MIT000064400007650000765000000020601250646353400123000ustar0000000000000000The MIT License (MIT) Copyright (c) 2015 nwin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. lzw-0.10.0/README.md000064400007650000765000000000331250646353400121210ustar0000000000000000# lzw LZW en- and decoding lzw-0.10.0/src/bitstream.rs000064400007650000765000000126411263546341700140040ustar0000000000000000//! This module provides bit readers and writers use std::io::{self, Write}; /// Containes either the consumed bytes and reconstructed bits or /// only the consumed bytes if the supplied buffer was not bit enough pub enum Bits { /// Consumed bytes, reconstructed bits Some(usize, u16), /// Consumed bytes None(usize), } /// A bit reader. pub trait BitReader { /// Returns the next `n` bits. fn read_bits(&mut self, buf: &[u8], n: u8) -> Bits; } /// A bit writer. pub trait BitWriter: Write { /// Writes the next `n` bits. fn write_bits(&mut self, v: u16, n: u8) -> io::Result<()>; } macro_rules! define_bit_readers { {$( $name:ident, #[$doc:meta]; )*} => { $( // START Structure definitions #[$doc] #[derive(Debug)] pub struct $name { bits: u8, acc: u32, } impl $name { /// Creates a new bit reader pub fn new() -> $name { $name { bits: 0, acc: 0, } } } )* // END Structure definitions } } define_bit_readers!{ LsbReader, #[doc = "Reads bits from a byte stream, LSB first."]; MsbReader, #[doc = "Reads bits from a byte stream, MSB first."]; } impl BitReader for LsbReader { fn read_bits(&mut self, mut buf: &[u8], n: u8) -> Bits { if n > 16 { // This is a logic error the program should have prevented this // Ideally we would used bounded a integer value instead of u8 panic!("Cannot read more than 16 bits") } let mut consumed = 0; while self.bits < n { let byte = if buf.len() > 0 { let byte = buf[0]; buf = &buf[1..]; byte } else { return Bits::None(consumed) }; self.acc |= (byte as u32) << self.bits; self.bits += 8; consumed += 1; } let res = self.acc & ((1 << n) - 1); self.acc >>= n; self.bits -= n; Bits::Some(consumed, res as u16) } } impl BitReader for MsbReader { fn read_bits(&mut self, mut buf: &[u8], n: u8) -> Bits { if n > 16 { // This is a logic error the program should have prevented this // Ideally we would used bounded a integer value instead of u8 panic!("Cannot read more than 16 bits") } let mut consumed = 0; while self.bits < n { let byte = if buf.len() > 0 { let byte = buf[0]; buf = &buf[1..]; byte } else { return Bits::None(consumed) }; self.acc |= (byte as u32) << (24 - self.bits); self.bits += 8; consumed += 1; } let res = self.acc >> (32 - n); self.acc <<= n; self.bits -= n; Bits::Some(consumed, res as u16) } } macro_rules! define_bit_writers { {$( $name:ident, #[$doc:meta]; )*} => { $( // START Structure definitions #[$doc] #[allow(dead_code)] pub struct $name { w: W, bits: u8, acc: u32, } impl $name { /// Creates a new bit reader #[allow(dead_code)] pub fn new(writer: W) -> $name { $name { w: writer, bits: 0, acc: 0, } } } impl Write for $name { fn write(&mut self, buf: &[u8]) -> io::Result { if self.acc == 0 { self.w.write(buf) } else { for &byte in buf.iter() { try!(self.write_bits(byte as u16, 8)) } Ok(buf.len()) } } fn flush(&mut self) -> io::Result<()> { let missing = 8 - self.bits; if missing > 0 { try!(self.write_bits(0, missing)); } self.w.flush() } } )* // END Structure definitions } } define_bit_writers!{ LsbWriter, #[doc = "Writes bits to a byte stream, LSB first."]; MsbWriter, #[doc = "Writes bits to a byte stream, MSB first."]; } impl BitWriter for LsbWriter { fn write_bits(&mut self, v: u16, n: u8) -> io::Result<()> { self.acc |= (v as u32) << self.bits; self.bits += n; while self.bits >= 8 { try!(self.w.write_all(&[self.acc as u8])); self.acc >>= 8; self.bits -= 8 } Ok(()) } } impl BitWriter for MsbWriter { fn write_bits(&mut self, v: u16, n: u8) -> io::Result<()> { self.acc |= (v as u32) << (32 - n - self.bits); self.bits += n; while self.bits >= 8 { try!(self.w.write_all(&[(self.acc >> 24) as u8])); self.acc <<= 8; self.bits -= 8 } Ok(()) } } #[cfg(test)] mod test { use super::{BitReader, BitWriter, Bits}; #[test] fn reader_writer() { let data = [255, 20, 40, 120, 128]; let mut offset = 0; let mut expanded_data = Vec::new(); let mut reader = super::LsbReader::new(); while let Bits::Some(consumed, b) = reader.read_bits(&data[offset..], 10) { offset += consumed; expanded_data.push(b) } let mut compressed_data = Vec::new(); { let mut writer = super::LsbWriter::new(&mut compressed_data); for &datum in expanded_data.iter() { let _ = writer.write_bits(datum, 10); } } assert_eq!(&data[..], &compressed_data[..]) } } lzw-0.10.0/src/lib.rs000064400007650000765000000021371266464131600125550ustar0000000000000000//! # LZW decoder and encoder //! //! This crates provides a `LzwEncoder` and `LzwDecoder`. The code words are written from //! and to bit streams where it is possible to write either the most or least significant //! bit first. The maximum possible code size is 16 bits. Both types rely on RAII to //! produced correct results. //! //! The de- and encoder expect the LZW stream to start with a clear code and end with an //! end code which are defined as follows: //! //! * `CLEAR_CODE == 1 << min_code_size` //! * `END_CODE == CLEAR_CODE + 1` //! //! Examplary use of the encoder: //! //! use lzw::{LsbWriter, Encoder}; //! let size = 8; //! let data = b"TOBEORNOTTOBEORTOBEORNOT"; //! let mut compressed = vec![]; //! { //! let mut enc = Encoder::new(LsbWriter::new(&mut compressed), size).unwrap(); //! enc.encode_bytes(data).unwrap(); //! } mod lzw; mod bitstream; pub use lzw::{ Decoder, DecoderEarlyChange, Encoder, encode }; pub use bitstream::{ BitReader, BitWriter, LsbReader, LsbWriter, MsbReader, MsbWriter, Bits };lzw-0.10.0/src/lzw.rs000064400007650000765000000356071266464131600126330ustar0000000000000000//! This modules provides an implementation of the Lempel–Ziv–Welch Compression Algorithm // Note: This implementation borrows heavily from the work of Julius Pettersson // See http://www.cplusplus.com/articles/iL18T05o/ for his extensive explanations // and a C++ implementatation use std::io; use std::io::{Read, Write}; use bitstream::{Bits, BitReader, BitWriter}; const MAX_CODESIZE: u8 = 12; const MAX_ENTRIES: usize = 1 << MAX_CODESIZE as usize; /// Alias for a LZW code point type Code = u16; /// Decoding dictionary. /// /// It is not generic due to current limitations of Rust /// Inspired by http://www.cplusplus.com/articles/iL18T05o/ #[derive(Debug)] struct DecodingDict { min_size: u8, table: Vec<(Option, u8)>, buffer: Vec, } impl DecodingDict { /// Creates a new dict fn new(min_size: u8) -> DecodingDict { DecodingDict { min_size: min_size, table: Vec::with_capacity(512), buffer: Vec::with_capacity((1 << MAX_CODESIZE as usize) - 1) } } /// Resets the dictionary fn reset(&mut self) { self.table.clear(); for i in 0..(1u16 << self.min_size as usize) { self.table.push((None, i as u8)); } } /// Inserts a value into the dict #[inline(always)] fn push(&mut self, key: Option, value: u8) { self.table.push((key, value)) } /// Reconstructs the data for the corresponding code fn reconstruct(&mut self, code: Option) -> io::Result<&[u8]> { self.buffer.clear(); let mut code = code; let mut cha; // Check the first access more thoroughly since a bad code // could occur if the data is malformed if let Some(k) = code { match self.table.get(k as usize) { Some(&(code_, cha_)) => { code = code_; cha = cha_; } None => return Err(io::Error::new( io::ErrorKind::InvalidInput, &*format!("Invalid code {:X}, expected code <= {:X}", k, self.table.len()) )) } self.buffer.push(cha); } while let Some(k) = code { if self.buffer.len() >= MAX_ENTRIES { return Err(io::Error::new( io::ErrorKind::InvalidInput, "Invalid code sequence. Cycle in decoding table." )) } //(code, cha) = self.table[k as usize]; // Note: This could possibly be replaced with an unchecked array access if // - value is asserted to be < self.next_code() in push // - min_size is asserted to be < MAX_CODESIZE let entry = self.table[k as usize]; code = entry.0; cha = entry.1; self.buffer.push(cha); } self.buffer.reverse(); Ok(&self.buffer) } /// Returns the buffer constructed by the last reconstruction #[inline(always)] fn buffer(&self) -> &[u8] { &self.buffer } /// Number of entries in the dictionary #[inline(always)] fn next_code(&self) -> u16 { self.table.len() as u16 } } macro_rules! define_decoder_struct { {$( $name:ident, $offset:expr, #[$doc:meta]; )*} => { $( // START struct definition #[$doc] /// /// The maximum supported code size is 16 bits. The decoder assumes two /// special code word to be present in the stream: /// /// * `CLEAR_CODE == 1 << min_code_size` /// * `END_CODE == CLEAR_CODE + 1` /// ///Furthermore the decoder expects the stream to start with a `CLEAR_CODE`. This /// corresponds to the implementation needed for en- and decoding GIF and TIFF files. #[derive(Debug)] pub struct $name { r: R, prev: Option, table: DecodingDict, buf: [u8; 1], code_size: u8, min_code_size: u8, clear_code: Code, end_code: Code, } impl $name where R: BitReader { /// Creates a new LZW decoder. pub fn new(reader: R, min_code_size: u8) -> $name { $name { r: reader, prev: None, table: DecodingDict::new(min_code_size), buf: [0; 1], code_size: min_code_size + 1, min_code_size: min_code_size, clear_code: 1 << min_code_size, end_code: (1 << min_code_size) + 1, } } /// Tries to obtain and decode a code word from `bytes`. /// /// Returns the number of bytes that have been consumed from `bytes`. An empty /// slice does not indicate `EOF`. pub fn decode_bytes(&mut self, bytes: &[u8]) -> io::Result<(usize, &[u8])> { Ok(match self.r.read_bits(bytes, self.code_size) { Bits::Some(consumed, code) => { (consumed, if code == self.clear_code { self.table.reset(); self.table.push(None, 0); // clear code self.table.push(None, 0); // end code self.code_size = self.min_code_size + 1; self.prev = None; &[] } else if code == self.end_code { &[] } else { let next_code = self.table.next_code(); if code > next_code { return Err(io::Error::new( io::ErrorKind::InvalidInput, &*format!("Invalid code {:X}, expected code <= {:X}", code, next_code ) )) } let prev = self.prev; let result = if prev.is_none() { self.buf = [code as u8]; &self.buf[..] } else { let data = if code == next_code { let cha = try!(self.table.reconstruct(prev))[0]; self.table.push(prev, cha); try!(self.table.reconstruct(Some(code))) } else if code < next_code { let cha = try!(self.table.reconstruct(Some(code)))[0]; self.table.push(prev, cha); self.table.buffer() } else { // code > next_code is already tested a few lines earlier unreachable!() }; data }; if next_code == (1 << self.code_size as usize) - 1 - $offset && self.code_size < MAX_CODESIZE { self.code_size += 1; } self.prev = Some(code); result }) }, Bits::None(consumed) => { (consumed, &[]) } }) } } )* // END struct definition } } define_decoder_struct!{ Decoder, 0, #[doc = "Decoder for a LZW compressed stream (this algorithm is used for GIF files)."]; DecoderEarlyChange, 1, #[doc = "Decoder for a LZW compressed stream using an “early change” algorithm (used in TIFF files)."]; } struct Node { prefix: Option, c: u8, left: Option, right: Option, } impl Node { #[inline(always)] fn new(c: u8) -> Node { Node { prefix: None, c: c, left: None, right: None } } } struct EncodingDict { table: Vec, min_size: u8, } /// Encoding dictionary based on a binary tree impl EncodingDict { fn new(min_size: u8) -> EncodingDict { let mut this = EncodingDict { table: Vec::with_capacity(MAX_ENTRIES), min_size: min_size }; this.reset(); this } fn reset(&mut self) { self.table.clear(); for i in 0 .. (1u16 << self.min_size as usize) { self.push_node(Node::new(i as u8)); } } #[inline(always)] fn push_node(&mut self, node: Node) { self.table.push(node) } #[inline(always)] fn clear_code(&self) -> Code { 1u16 << self.min_size } #[inline(always)] fn end_code(&self) -> Code { self.clear_code() + 1 } // Searches for a new prefix fn search_and_insert(&mut self, i: Option, c: u8) -> Option { if let Some(i) = i.map(|v| v as usize) { let table_size = self.table.len() as Code; if let Some(mut j) = self.table[i].prefix { loop { let entry = &mut self.table[j as usize]; if c < entry.c { if let Some(k) = entry.left { j = k } else { entry.left = Some(table_size); break } } else if c > entry.c { if let Some(k) = entry.right { j = k } else { entry.right = Some(table_size); break } } else { return Some(j) } } } else { self.table[i].prefix = Some(table_size); } self.table.push(Node::new(c)); None } else { Some(self.search_initials(c as Code)) } } fn next_code(&self) -> usize { self.table.len() } fn search_initials(&self, i: Code) -> Code { self.table[i as usize].c as Code } } /// Convenience function that reads and compresses all bytes from `R`. pub fn encode(r: R, mut w: W, min_code_size: u8) -> io::Result<()> where R: Read, W: BitWriter { let mut dict = EncodingDict::new(min_code_size); dict.push_node(Node::new(0)); // clear code dict.push_node(Node::new(0)); // end code let mut code_size = min_code_size + 1; let mut i = None; // gif spec: first clear code try!(w.write_bits(dict.clear_code(), code_size)); let mut r = r.bytes(); while let Some(Ok(c)) = r.next() { let prev = i; i = dict.search_and_insert(prev, c); if i.is_none() { if let Some(code) = prev { try!(w.write_bits(code, code_size)); } i = Some(dict.search_initials(c as Code)) } // There is a hit: do not write out code but continue let next_code = dict.next_code(); if next_code > (1 << code_size as usize) && code_size < MAX_CODESIZE { code_size += 1; } if next_code > MAX_ENTRIES { dict.reset(); dict.push_node(Node::new(0)); // clear code dict.push_node(Node::new(0)); // end code try!(w.write_bits(dict.clear_code(), code_size)); code_size = min_code_size + 1; } } if let Some(code) = i { try!(w.write_bits(code, code_size)); } try!(w.write_bits(dict.end_code(), code_size)); try!(w.flush()); Ok(()) } /// LZW encoder using the algorithm of GIF files. pub struct Encoder { w: W, dict: EncodingDict, min_code_size: u8, code_size: u8, i: Option } impl Encoder { /// Creates a new LZW encoder. /// /// **Note**: If `min_code_size < 8` then `Self::encode_bytes` might panic when /// the supplied data containts values that exceed `1 << min_code_size`. pub fn new(mut w: W, min_code_size: u8) -> io::Result> { let mut dict = EncodingDict::new(min_code_size); dict.push_node(Node::new(0)); // clear code dict.push_node(Node::new(0)); // end code let code_size = min_code_size + 1; try!(w.write_bits(dict.clear_code(), code_size)); Ok(Encoder { w: w, dict: dict, min_code_size: min_code_size, code_size: code_size, i: None }) } /// Compresses `bytes` and writes the result into the writer. /// /// ## Panics /// /// This function might panic if any of the input bytes exceeds `1 << min_code_size`. /// This cannot happen if `min_code_size >= 8`. pub fn encode_bytes(&mut self, bytes: &[u8]) -> io::Result<()> { let w = &mut self.w; let dict = &mut self.dict; let code_size = &mut self.code_size; let i = &mut self.i; for &c in bytes { let prev = *i; *i = dict.search_and_insert(prev, c); if i.is_none() { if let Some(code) = prev { try!(w.write_bits(code, *code_size)); } *i = Some(dict.search_initials(c as Code)) } // There is a hit: do not write out code but continue let next_code = dict.next_code(); if next_code > (1 << *code_size as usize) && *code_size < MAX_CODESIZE { *code_size += 1; } if next_code > MAX_ENTRIES { dict.reset(); dict.push_node(Node::new(0)); // clear code dict.push_node(Node::new(0)); // end code try!(w.write_bits(dict.clear_code(), *code_size)); *code_size = self.min_code_size + 1; } } Ok(()) } } impl Drop for Encoder { #[cfg(feature = "raii_no_panic")] fn drop(&mut self) { let w = &mut self.w; let code_size = &mut self.code_size; if let Some(code) = self.i { let _ = w.write_bits(code, *code_size); } let _ = w.write_bits(self.dict.end_code(), *code_size); let _ = w.flush(); } #[cfg(not(feature = "raii_no_panic"))] fn drop(&mut self) { (|| { let w = &mut self.w; let code_size = &mut self.code_size; if let Some(code) = self.i { try!(w.write_bits(code, *code_size)); } try!(w.write_bits(self.dict.end_code(), *code_size)); w.flush() })().unwrap() } } #[cfg(test)] #[test] fn round_trip() { use {LsbWriter, LsbReader}; let size = 8; let data = b"TOBEORNOTTOBEORTOBEORNOT"; let mut compressed = vec![]; { let mut enc = Encoder::new(LsbWriter::new(&mut compressed), size).unwrap(); enc.encode_bytes(data).unwrap(); } println!("{:?}", compressed); let mut dec = Decoder::new(LsbReader::new(), size); let mut compressed = &compressed[..]; let mut data2 = vec![]; while compressed.len() > 0 { let (start, bytes) = dec.decode_bytes(&compressed).unwrap(); compressed = &compressed[start..]; data2.extend(bytes.iter().map(|&i| i)); } assert_eq!(data2, data) }