Skip to main content

lib_jsl_information/source_coders/
lz78.rs

1//! Manual LZ78 compression and decompression helpers.
2//!
3//! LZ78 differs from LZ77 in one important way: instead of pointing into a
4//! sliding history window, the encoder explicitly builds a dictionary of phrases
5//! and emits dictionary indices. Each new token is "an existing phrase" plus
6//! "one extra byte".
7//!
8//! # Format Overview
9//!
10//! The compressed stream begins with the ASCII header `LZ78`. The remainder is
11//! a sequence of dictionary tokens:
12//!
13//! - 16-bit little-endian prefix index
14//! - 1-byte suffix-present flag
15//! - optional 1-byte suffix literal when the flag is `1`
16//!
17//! Dictionary index `0` means "the empty phrase". A token therefore says:
18//!
19//! - take dictionary entry `prefix_index`
20//! - append the optional suffix byte
21//! - emit that phrase to the output
22//! - insert the new phrase into the dictionary
23//!
24//! The optional-suffix form is used so the final phrase can be emitted even if
25//! the input ends exactly on a phrase already present in the dictionary.
26//!
27//! See the book entry [Dictionary coding](https://jwkunz.github.io/lib_jsl/book/information/dictionary-coding.html#lz78-an-explicit-dictionary).
28
29use std::collections::HashMap;
30
31use lib_jsl_core::ErrorsJSL;
32
33const MAGIC: &[u8; 4] = b"LZ78";
34const HAS_SUFFIX: u8 = 1;
35const NO_SUFFIX: u8 = 0;
36const MAX_INDEX: usize = u16::MAX as usize;
37
38/// Compress a byte slice with a manual LZ78 encoder.
39pub fn lz78_compress(input: &[u8]) -> Vec<u8> {
40    // The output starts with enough room for the original data plus a little
41    // framing overhead. The exact final size depends on how often the input
42    // can be expressed as "known phrase + one new byte".
43    let mut output = Vec::with_capacity(input.len().saturating_add(MAGIC.len() + 4));
44    output.extend_from_slice(MAGIC);
45
46    // The dictionary maps complete phrases to their assigned indices. Index
47    // zero is reserved for the empty phrase and therefore does not appear here.
48    let mut dictionary: HashMap<Vec<u8>, u16> = HashMap::new();
49    let mut next_index: usize = 1;
50
51    // `current_phrase` is the longest phrase we have matched so far while
52    // walking the input. We extend it greedily until the next extension would
53    // no longer exist in the dictionary.
54    let mut current_phrase = Vec::new();
55
56    for &byte in input {
57        // Pretend that the next input byte extends the phrase we are currently
58        // building. LZ78 always asks "have I seen this longer phrase before?"
59        // before deciding whether to emit a token.
60        let mut extended_phrase = current_phrase.clone();
61        extended_phrase.push(byte);
62
63        if dictionary.contains_key(&extended_phrase) {
64            // If the longer phrase already exists, keep growing it. This is the
65            // LZ78 "longest dictionary phrase" step.
66            current_phrase = extended_phrase;
67        } else {
68            // We found the first byte that takes us outside the existing
69            // dictionary, so emit:
70            // - the index of the longest known prefix
71            // - the new suffix byte that extends it
72            //
73            // Example:
74            // if the dictionary already knows `ABA` and the next byte is `Q`,
75            // the emitted token is `(index_of_ABA, 'Q')`.
76            let prefix_index = phrase_index(&dictionary, &current_phrase);
77            emit_token(&mut output, prefix_index, Some(byte));
78
79            // Then teach the dictionary about this newly discovered phrase,
80            // unless we have reached the maximum index size representable by the
81            // on-wire format.
82            if next_index <= MAX_INDEX {
83                dictionary.insert(extended_phrase, next_index as u16);
84                next_index += 1;
85            }
86
87            // Start searching for the next phrase from scratch.
88            current_phrase.clear();
89        }
90    }
91
92    // If we end the input while holding an already-known phrase, emit it using
93    // the "no suffix" form.
94    if !current_phrase.is_empty() {
95        let prefix_index = phrase_index(&dictionary, &current_phrase);
96        emit_token(&mut output, prefix_index, None);
97    }
98
99    output
100}
101
102/// Decompress a byte slice previously produced by [`lz78_compress`].
103pub fn lz78_decompress(input: &[u8]) -> Vec<u8> {
104    try_lz78_decompress(input).unwrap_or_default()
105}
106
107/// Fallible variant of [`lz78_decompress`].
108pub fn try_lz78_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
109    // The decoder begins by validating the four-byte magic value so it knows
110    // the rest of the payload should be interpreted as LZ78 tokens.
111    if input.len() < MAGIC.len() || &input[..MAGIC.len()] != MAGIC {
112        return Err(ErrorsJSL::InvalidInputRange("Compressed payload is missing the LZ78 header."));
113    }
114
115    let mut output = Vec::new();
116
117    // Dictionary index zero is the empty phrase; every other entry is appended
118    // as tokens are decoded.
119    let mut dictionary: Vec<Vec<u8>> = vec![Vec::new()];
120    let mut cursor = MAGIC.len();
121
122    while cursor < input.len() {
123        // Every token must at least carry a two-byte prefix index and a
124        // one-byte suffix flag.
125        if cursor + 3 > input.len() {
126            return Err(ErrorsJSL::InvalidInputRange("LZ78 token is missing prefix index or suffix flag bytes."));
127        }
128
129        // Recover the "existing dictionary phrase" part of the token.
130        let prefix_index = u16::from_le_bytes([input[cursor], input[cursor + 1]]) as usize;
131        cursor += 2;
132
133        // Then recover whether this token carries a trailing literal byte.
134        let suffix_flag = input[cursor];
135        cursor += 1;
136
137        if prefix_index >= dictionary.len() {
138            return Err(ErrorsJSL::InvalidInputRange("LZ78 prefix index points outside the reconstructed dictionary."));
139        }
140
141        // Rebuild the phrase by copying the referenced dictionary phrase first.
142        let mut phrase = dictionary[prefix_index].clone();
143
144        match suffix_flag {
145            HAS_SUFFIX => {
146                if cursor >= input.len() {
147                    return Err(ErrorsJSL::InvalidInputRange("LZ78 token declares a suffix byte but none is present."));
148                }
149
150                // Then append the one new literal byte that made this phrase a
151                // fresh dictionary entry during compression.
152                phrase.push(input[cursor]);
153                cursor += 1;
154            }
155            NO_SUFFIX => {
156                // This is the end-of-stream form used when the encoder ended on
157                // an already-known phrase. No additional byte is appended.
158            }
159            _ => {
160                return Err(ErrorsJSL::InvalidInputRange("LZ78 suffix flag must be either 0 or 1."));
161            }
162        }
163
164        // The token's decoded phrase is part of the original data stream, so
165        // append it directly to the output in the order we recovered it.
166        output.extend_from_slice(&phrase);
167
168        // Every non-empty decoded phrase becomes the next dictionary entry, just
169        // as it did during compression.
170        if !phrase.is_empty() && dictionary.len() <= MAX_INDEX {
171            dictionary.push(phrase);
172        }
173    }
174
175    Ok(output)
176}
177
178/// Look up the dictionary index for a phrase, returning zero for the empty
179/// phrase.
180fn phrase_index(dictionary: &HashMap<Vec<u8>, u16>, phrase: &[u8]) -> u16 {
181    // LZ78 reserves index zero for "no prefix", which corresponds to the empty
182    // phrase at the start of a token.
183    if phrase.is_empty() {
184        0
185    } else {
186        dictionary.get(phrase).copied().unwrap_or(0)
187    }
188}
189
190/// Emit one LZ78 token into the custom byte stream.
191fn emit_token(output: &mut Vec<u8>, prefix_index: u16, suffix: Option<u8>) {
192    // The on-wire token layout is:
193    // 1. prefix index
194    // 2. suffix-present flag
195    // 3. optional suffix byte
196    output.extend_from_slice(&prefix_index.to_le_bytes());
197
198    match suffix {
199        Some(byte) => {
200            output.push(HAS_SUFFIX);
201            output.push(byte);
202        }
203        None => {
204            output.push(NO_SUFFIX);
205        }
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn round_trip_empty_input() {
215        let payload = b"";
216        let compressed = lz78_compress(payload);
217        let decompressed = lz78_decompress(&compressed);
218
219        assert_eq!(decompressed, payload);
220        assert_eq!(&compressed[..MAGIC.len()], MAGIC);
221    }
222
223    #[test]
224    fn round_trip_repeated_text() {
225        let payload = b"TOBEORNOTTOBEORTOBEORNOTO";
226        let compressed = lz78_compress(payload);
227        let decompressed = lz78_decompress(&compressed);
228
229        assert_eq!(decompressed, payload);
230    }
231
232    #[test]
233    fn round_trip_binary_data() {
234        let payload = [0u8, 1, 0, 1, 0, 1, 2, 2, 2, 3, 4, 3, 4];
235        let compressed = lz78_compress(&payload);
236        let decompressed = lz78_decompress(&compressed);
237
238        assert_eq!(decompressed, payload);
239    }
240
241    #[test]
242    fn round_trip_kjv_text_asset() {
243        // Embed the asset directly into the test binary so this large-file
244        // regression test keeps working no matter where `cargo test` is run.
245        let payload = include_bytes!("../../test_assets/kjv.txt");
246        let compressed = lz78_compress(payload);
247        let decompressed = lz78_decompress(&compressed);
248
249        assert_eq!(decompressed, payload);
250    }
251
252    #[test]
253    fn malformed_stream_returns_error_in_try_api() {
254        let malformed = vec![b'L', b'Z', b'7', b'8', 0x01, 0x00, 0x00];
255        let result = try_lz78_decompress(&malformed);
256
257        assert!(result.is_err());
258    }
259
260    #[test]
261    fn malformed_stream_returns_empty_in_wrapper_api() {
262        let malformed = vec![0x00, 0x00, 0x01];
263        let decompressed = lz78_decompress(&malformed);
264
265        assert!(decompressed.is_empty());
266    }
267}