Skip to main content

lib_jsl_information/source_coders/
lzw.rs

1//! Manual LZW compression and decompression helpers.
2//!
3//! LZW starts from the LZ78 idea of building a dictionary of phrases, but it
4//! removes the explicit "suffix byte" from the token stream. Instead, both the
5//! encoder and decoder grow the same dictionary deterministically as they read
6//! codes.
7//!
8//! # Format Overview
9//!
10//! The compressed stream begins with the ASCII header `LZW0`. The remainder is
11//! a sequence of 16-bit little-endian dictionary codes.
12//!
13//! The initial dictionary contains all 256 one-byte values. Whenever the
14//! encoder emits a code for phrase `W` and then sees the next phrase `WK`, the
15//! new combined phrase is inserted into the dictionary. The decoder mirrors
16//! that same update rule.
17//!
18//! See the book entry [Dictionary coding](https://jwkunz.github.io/lib_jsl/book/information/dictionary-coding.html#lzw-no-explicit-byte).
19
20use std::collections::HashMap;
21
22use lib_jsl_core::ErrorsJSL;
23
24const MAGIC: &[u8; 4] = b"LZW0";
25const MAX_CODE: usize = u16::MAX as usize;
26
27/// Compress a byte slice with a manual LZW encoder.
28pub fn lzw_compress(input: &[u8]) -> Vec<u8> {
29    // We reserve enough room for the header plus a rough stream of 16-bit
30    // codes. LZW can compress or expand depending on the input, so this is
31    // only a starting guess.
32    let mut output = Vec::with_capacity(input.len().saturating_add(MAGIC.len() + 2));
33    output.extend_from_slice(MAGIC);
34
35    // Seed the dictionary with every one-byte phrase so compression can start
36    // immediately from raw input bytes.
37    let mut dictionary: HashMap<Vec<u8>, u16> =
38        (0u16..=255).map(|code| (vec![code as u8], code)).collect();
39    let mut next_code: usize = 256;
40
41    let mut current_phrase = Vec::new();
42
43    // ANCHOR: lzw
44    for &byte in input {
45        // Hypothesize that the next input byte extends the phrase we are
46        // currently building. If that longer phrase already exists, we keep
47        // growing; otherwise we emit the known prefix and learn the longer one.
48        let mut extended_phrase = current_phrase.clone();
49        extended_phrase.push(byte);
50
51        if dictionary.contains_key(&extended_phrase) {
52            // Keep extending while the dictionary already knows the longer
53            // phrase.
54            current_phrase = extended_phrase;
55        } else {
56            // The longer phrase is new, so emit the code for the longest phrase
57            // we *did* know.
58            //
59            // Example:
60            // if `TOBE` is in the dictionary but `TOBEN` is not, we emit the
61            // code for `TOBE`, then insert `TOBEN`.
62            if !current_phrase.is_empty() {
63                let code = dictionary[&current_phrase];
64                output.extend_from_slice(&code.to_le_bytes());
65            }
66
67            // Then add the newly discovered phrase to the dictionary if the
68            // 16-bit code space still has room.
69            if next_code <= MAX_CODE {
70                dictionary.insert(extended_phrase, next_code as u16);
71                next_code += 1;
72            }
73
74            // The current unmatched suffix is now just the single byte that
75            // caused the miss.
76            current_phrase.clear();
77            current_phrase.push(byte);
78        }
79    }
80    // ANCHOR_END: lzw
81
82    // Emit the final phrase after the scan finishes.
83    if !current_phrase.is_empty() {
84        let code = dictionary[&current_phrase];
85        output.extend_from_slice(&code.to_le_bytes());
86    }
87
88    output
89}
90
91/// Decompress a byte slice previously produced by [`lzw_compress`].
92pub fn lzw_decompress(input: &[u8]) -> Vec<u8> {
93    try_lzw_decompress(input).unwrap_or_default()
94}
95
96/// Fallible variant of [`lzw_decompress`].
97pub fn try_lzw_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
98    // The magic header distinguishes this payload from the other source coders
99    // in the crate, which all have their own byte layouts.
100    if input.len() < MAGIC.len() || &input[..MAGIC.len()] != MAGIC {
101        return Err(ErrorsJSL::InvalidInputRange("Compressed payload is missing the LZW header."));
102    }
103
104    if !(input.len() - MAGIC.len()).is_multiple_of(2) {
105        return Err(ErrorsJSL::InvalidInputRange("LZW code stream must contain an even number of bytes after the header."));
106    }
107
108    // Seed the decoder dictionary with the same 256 one-byte phrases used by
109    // the encoder.
110    let mut dictionary: Vec<Vec<u8>> = (0u16..=255).map(|code| vec![code as u8]).collect();
111    let mut next_code: usize = 256;
112    let mut output = Vec::new();
113    let mut cursor = MAGIC.len();
114    let mut previous_phrase: Option<Vec<u8>> = None;
115
116    while cursor < input.len() {
117        // Read the next 16-bit phrase code from the compressed stream.
118        let code = u16::from_le_bytes([input[cursor], input[cursor + 1]]);
119        cursor += 2;
120
121        let phrase = if let Some(existing) = dictionary.get(code as usize) {
122            // The common case: the code already names a phrase we know.
123            existing.clone()
124        } else if (code as usize) == next_code {
125            // This is the classic LZW "KwKwK" edge case. The encoder has just
126            // created the next dictionary entry, and the decoder can reconstruct
127            // it as `previous_phrase + first(previous_phrase)`.
128            let previous = previous_phrase.as_ref().ok_or(ErrorsJSL::InvalidInputRange(
129                "LZW encountered a forward reference before any previous phrase existed.",
130            ))?;
131            let first = *previous.first().ok_or(ErrorsJSL::InvalidInputRange(
132                "LZW previous phrase unexpectedly had no leading byte.",
133            ))?;
134
135            let mut inferred = previous.clone();
136            inferred.push(first);
137            inferred
138        } else {
139            return Err(ErrorsJSL::InvalidInputRange("LZW code points outside the reconstructed dictionary."));
140        };
141
142        // Once the phrase is known, emit it directly to reconstruct the source.
143        output.extend_from_slice(&phrase);
144
145        if let Some(previous) = &previous_phrase {
146            // Mirror the encoder's update rule by creating
147            // `previous_phrase + first_byte_of_current_phrase`.
148            let mut new_phrase = previous.clone();
149            let first = *phrase.first().ok_or(ErrorsJSL::InvalidInputRange(
150                "LZW current phrase unexpectedly had no leading byte.",
151            ))?;
152            new_phrase.push(first);
153
154            if next_code <= MAX_CODE {
155                dictionary.push(new_phrase);
156                next_code += 1;
157            }
158        }
159
160        previous_phrase = Some(phrase);
161    }
162
163    Ok(output)
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn round_trip_empty_input() {
172        let payload = b"";
173        let compressed = lzw_compress(payload);
174        let decompressed = lzw_decompress(&compressed);
175
176        assert_eq!(decompressed, payload);
177        assert_eq!(&compressed[..MAGIC.len()], MAGIC);
178    }
179
180    #[test]
181    fn round_trip_repeated_text() {
182        let payload = b"TOBEORNOTTOBEORTOBEORNOT";
183        let compressed = lzw_compress(payload);
184        let decompressed = lzw_decompress(&compressed);
185
186        assert_eq!(decompressed, payload);
187    }
188
189    #[test]
190    fn round_trip_binary_data() {
191        let payload = [1u8, 2, 1, 2, 1, 2, 1, 2, 3, 3, 3, 4, 5, 4, 5];
192        let compressed = lzw_compress(&payload);
193        let decompressed = lzw_decompress(&compressed);
194
195        assert_eq!(decompressed, payload);
196    }
197
198    #[test]
199    fn round_trip_kjv_text_asset() {
200        // Embed the asset directly into the test binary so this large-file
201        // regression test keeps working no matter where `cargo test` is run.
202        let payload = include_bytes!("../../test_assets/kjv.txt");
203        let compressed = lzw_compress(payload);
204        let decompressed = lzw_decompress(&compressed);
205
206        assert_eq!(decompressed, payload);
207    }
208
209    #[test]
210    fn malformed_stream_returns_error_in_try_api() {
211        let malformed = vec![b'L', b'Z', b'W', b'0', 0x34];
212        let result = try_lzw_decompress(&malformed);
213
214        assert!(result.is_err());
215    }
216
217    #[test]
218    fn malformed_stream_returns_empty_in_wrapper_api() {
219        let malformed = vec![0x34];
220        let decompressed = lzw_decompress(&malformed);
221
222        assert!(decompressed.is_empty());
223    }
224}