lib_jsl_information/source_coders/lz77.rs
1//! Manual LZ77 compression and decompression helpers.
2//!
3//! This module implements the sliding-window variant of the Lempel-Ziv family.
4//! The encoder looks backward into the already-seen portion of the input and
5//! replaces repeated substrings with `(offset, length)` style references.
6//!
7//! # Format Overview
8//!
9//! The compressed stream begins with the ASCII header `LZ77`. The remainder of
10//! the payload is a sequence of variable-length tokens:
11//!
12//! - literal run token:
13//! - high bit clear in the control byte
14//! - lower 7 bits encode `literal_count - 1`
15//! - the control byte is followed by `literal_count` raw bytes
16//! - back-reference token:
17//! - high bit set in the control byte
18//! - lower 7 bits encode `match_len - MIN_MATCH`
19//! - followed by a 16-bit little-endian offset
20//!
21//! A back-reference means "copy `match_len` bytes from `offset` bytes before
22//! the current output position". This is the classic sliding-window LZ77 idea:
23//! when we see a repeated substring, we emit a pointer into previously decoded
24//! output rather than repeating the bytes literally.
25//!
26//! # API Design
27//!
28//! The user-facing functions consume `&[u8]` and return `Vec<u8>`. To keep the
29//! implementation honest, the fallible decoder logic is exposed as
30//! [`try_lz77_decompress`]. The infallible [`lz77_decompress`] wrapper returns
31//! an empty vector when the payload is malformed.
32//!
33//! See the book entry [Dictionary coding](https://jwkunz.github.io/lib_jsl/book/information/dictionary-coding.html#lz77-a-sliding-window).
34
35use std::collections::HashMap;
36
37use lib_jsl_core::ErrorsJSL;
38
39const MAGIC: &[u8; 4] = b"LZ77";
40const MIN_MATCH: usize = 3;
41const MAX_MATCH: usize = MIN_MATCH + 0x7F;
42const MAX_LITERAL_RUN: usize = 0x80;
43const MAX_WINDOW: usize = u16::MAX as usize;
44const MAX_CANDIDATES_PER_PREFIX: usize = 256;
45
46/// Compress a byte slice with a manual LZ77 sliding-window encoder.
47///
48/// The encoder scans the already-seen prefix of `input` and looks for the
49/// longest repeated substring that starts at the current position. When it
50/// finds a match of at least three bytes, it emits a back-reference token;
51/// otherwise it emits literal bytes.
52///
53/// The returned vector contains a small `LZ77` header followed by the custom
54/// token stream described in the module-level documentation.
55pub fn lz77_compress(input: &[u8]) -> Vec<u8> {
56 // Start with enough room for the original data plus a tiny amount of
57 // framing overhead. This is only a hint to reduce reallocations; the final
58 // compressed stream may still grow or shrink relative to the input.
59 let mut output = Vec::with_capacity(input.len().saturating_add(MAGIC.len() + 1));
60
61 // Write the magic header first so the decoder can quickly recognize that
62 // this byte stream belongs to our custom format.
63 output.extend_from_slice(MAGIC);
64
65 // `literals` temporarily collects bytes that we choose not to encode as a
66 // back-reference. We buffer them so several adjacent literal bytes can be
67 // emitted as one token instead of many one-byte tokens.
68 let mut literals = Vec::new();
69
70 // A small prefix index dramatically reduces the amount of searching we do
71 // on large inputs. For each three-byte prefix, we remember recent starting
72 // positions that began with that same prefix, then only compare against
73 // those candidates when searching for a match.
74 let mut prefix_index: HashMap<[u8; MIN_MATCH], Vec<usize>> = HashMap::new();
75
76 // `position` is the encoder's read head into the original input.
77 let mut position = 0usize;
78
79 // Keep walking forward until every input byte has been represented by
80 // either a literal run or a back-reference.
81 // ANCHOR: lz77
82 while position < input.len() {
83 // Ask the history window for the best repeat we can encode starting at
84 // this exact byte position.
85 let (best_offset, best_len) = find_longest_match(input, position, &prefix_index);
86
87 if best_len >= MIN_MATCH {
88 // Before writing a match token, flush any pending literal bytes.
89 // This keeps the compressed stream in the same logical order as the
90 // original input: first the raw bytes, then the repeated region.
91 flush_literals(&mut output, &mut literals);
92
93 // Emit a token that says "go backwards by `best_offset` bytes in
94 // the already-decoded output and copy `best_len` bytes from there".
95 emit_match(&mut output, best_offset, best_len);
96
97 // Even though we encoded this whole span as one token, each byte
98 // position inside the span becomes part of the searchable history
99 // for future matches. We therefore register every newly covered
100 // starting point that has at least three bytes available.
101 register_prefixes(input, position, best_len, &mut prefix_index);
102
103 // Because the match covers `best_len` bytes from the input, we can
104 // skip over that whole region in one step.
105 position += best_len;
106 } else {
107 // No useful repetition was found, so this byte must be carried
108 // through literally.
109 literals.push(input[position]);
110
111 // This starting point is now part of the history window for later
112 // positions, so index its three-byte prefix if one exists.
113 register_prefixes(input, position, 1, &mut prefix_index);
114 position += 1;
115
116 // Literal runs are capped at 128 bytes because the run length is
117 // stored in the lower seven bits of the control byte.
118 if literals.len() == MAX_LITERAL_RUN {
119 flush_literals(&mut output, &mut literals);
120 }
121 }
122 }
123 // ANCHOR_END: lz77
124
125 // If the input ended while we were still collecting literal bytes, emit
126 // that final run now.
127 flush_literals(&mut output, &mut literals);
128 output
129}
130
131/// Decompress a byte slice previously produced by [`lz77_compress`].
132///
133/// This wrapper keeps the requested simple signature. If the compressed stream
134/// is malformed, it returns an empty vector. Code that needs explicit error
135/// reporting should call [`try_lz77_decompress`] instead.
136pub fn lz77_decompress(input: &[u8]) -> Vec<u8> {
137 try_lz77_decompress(input).unwrap_or_default()
138}
139
140/// Fallible variant of [`lz77_decompress`].
141pub fn try_lz77_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
142 // The decoder expects the stream to begin with the exact four-byte magic
143 // header. If it is absent, the rest of the bytes are ambiguous, so we stop
144 // immediately.
145 if input.len() < MAGIC.len() || &input[..MAGIC.len()] != MAGIC {
146 return Err(ErrorsJSL::InvalidInputRange("Compressed payload is missing the LZ77 header."));
147 }
148
149 // `output` is the progressively reconstructed original message. In LZ77,
150 // back-references always point into this already-produced prefix.
151 let mut output = Vec::new();
152
153 // `cursor` is the decoder's read head into the compressed stream. We start
154 // just after the magic header because those bytes have already been
155 // consumed by validation.
156 let mut cursor = MAGIC.len();
157
158 // Decode one token at a time until we reach the end of the compressed
159 // payload.
160 while cursor < input.len() {
161 // Every token begins with a one-byte control field that determines the
162 // token kind and how much additional data we should read.
163 let control = input[cursor];
164 cursor += 1;
165
166 if control & 0x80 == 0 {
167 // Literal token: the lower seven bits store `count - 1`, so adding
168 // one recovers the real number of raw bytes that follow.
169 let literal_count = (control as usize) + 1;
170
171 if cursor + literal_count > input.len() {
172 return Err(ErrorsJSL::InvalidInputRange("Literal token extends beyond the compressed payload."));
173 }
174
175 // Copy the literal bytes directly from the compressed stream to the
176 // reconstructed output, then move the cursor past them.
177 output.extend_from_slice(&input[cursor..cursor + literal_count]);
178 cursor += literal_count;
179 } else {
180 // Match token: after the control byte we require a two-byte offset.
181 if cursor + 2 > input.len() {
182 return Err(ErrorsJSL::InvalidInputRange("Back-reference token is missing its offset bytes."));
183 }
184
185 // The lower seven bits store `length - MIN_MATCH`, so adding
186 // `MIN_MATCH` reconstructs the actual number of bytes to copy.
187 let match_len = ((control & 0x7F) as usize) + MIN_MATCH;
188
189 // The offset tells us how far back from the current end of the
190 // output we should begin copying.
191 let offset = u16::from_le_bytes([input[cursor], input[cursor + 1]]) as usize;
192 cursor += 2;
193
194 if offset == 0 || offset > output.len() {
195 return Err(ErrorsJSL::InvalidInputRange("Back-reference offset points outside the decoded prefix."));
196 }
197
198 // Convert the backward-looking offset into a concrete starting index
199 // inside the bytes we have already reconstructed.
200 let start = output.len() - offset;
201
202 // We copy one byte at a time so overlapping matches work exactly
203 // like classic LZ77 decoding. This is important for patterns such
204 // as `AAAAAA`, where newly written bytes become the source for
205 // later bytes in the same token.
206 for index in 0..match_len {
207 // Read from the historical window, then append to the end of the
208 // output. On later iterations, `output` may already contain the
209 // bytes written by earlier iterations of this same loop, which
210 // is precisely how overlap expansion works.
211 let byte = output[start + index];
212 output.push(byte);
213 }
214 }
215 }
216
217 Ok(output)
218}
219
220/// Search for the best back-reference that starts at `position`.
221///
222/// The implementation is intentionally straightforward rather than heavily
223/// optimized: we only compare against recent history positions that share the
224/// same three-byte prefix, then measure how many bytes match for each of those
225/// candidates. That keeps the logic readable while avoiding a full scan over
226/// multi-megabyte inputs.
227fn find_longest_match(
228 input: &[u8],
229 position: usize,
230 prefix_index: &HashMap<[u8; MIN_MATCH], Vec<usize>>,
231) -> (usize, usize) {
232 // At the very first byte there is no history to point backward into, so a
233 // match is impossible.
234 if position == 0 || position + MIN_MATCH > input.len() {
235 return (0, 0);
236 }
237
238 // Use the next three input bytes as a cheap fingerprint. If no previous
239 // position shared this prefix, then there is no valid match of length three
240 // or greater and we can immediately fall back to a literal byte.
241 let prefix = [input[position], input[position + 1], input[position + 2]];
242 let Some(candidates) = prefix_index.get(&prefix) else {
243 return (0, 0);
244 };
245
246 let mut best_offset = 0usize;
247 let mut best_len = 0usize;
248
249 // Consider only the most recent matching prefixes. Recent candidates are
250 // usually the most valuable in LZ77, and capping this search keeps the
251 // reference implementation practical on large text assets.
252 for &candidate in candidates.iter().rev().take(MAX_CANDIDATES_PER_PREFIX) {
253 if candidate >= position {
254 continue;
255 }
256
257 let offset = position - candidate;
258 if offset > MAX_WINDOW {
259 continue;
260 }
261
262 let mut match_len = 0usize;
263
264 // Keep extending the candidate match while:
265 // 1. we are still inside the original input,
266 // 2. the candidate byte agrees with the byte at `position + match_len`,
267 // 3. the match is still encodable in one token.
268 //
269 // The modulo term is the key overlap trick on the encoder side. If the
270 // candidate region is shorter than the full repeated pattern, we allow
271 // the comparison to wrap across the candidate span the same way the
272 // decoder would observe bytes appearing during an overlapping copy.
273 while position + match_len < input.len()
274 && input[candidate + (match_len % offset)] == input[position + match_len]
275 && match_len < MAX_MATCH
276 {
277 match_len += 1;
278 }
279
280 // Keep whichever candidate gives the longest repeat. LZ-family codecs
281 // usually prefer longer matches because they replace more input bytes
282 // with a single compact token.
283 if match_len > best_len {
284 best_len = match_len;
285 best_offset = offset;
286
287 // Once we hit the maximum encodable match length we cannot improve
288 // further, so ending the search here saves work.
289 if best_len == MAX_MATCH {
290 break;
291 }
292 }
293 }
294
295 (best_offset, best_len)
296}
297
298/// Register newly available three-byte prefixes in the encoder's search index.
299fn register_prefixes(
300 input: &[u8],
301 start: usize,
302 span_len: usize,
303 prefix_index: &mut HashMap<[u8; MIN_MATCH], Vec<usize>>,
304) {
305 let end = start.saturating_add(span_len).min(input.len());
306
307 for position in start..end {
308 if position + MIN_MATCH > input.len() {
309 break;
310 }
311
312 let prefix = [input[position], input[position + 1], input[position + 2]];
313 let entries = prefix_index.entry(prefix).or_default();
314 entries.push(position);
315
316 // Keep only a bounded number of recent candidates per prefix. That is
317 // enough to find strong local matches while preventing very common
318 // prefixes from accumulating massive search lists.
319 if entries.len() > MAX_CANDIDATES_PER_PREFIX {
320 let overflow = entries.len() - MAX_CANDIDATES_PER_PREFIX;
321 entries.drain(0..overflow);
322 }
323 }
324}
325
326/// Emit a back-reference token into the compressed stream.
327fn emit_match(output: &mut Vec<u8>, offset: usize, length: usize) {
328 // Set the high bit to mark this as a match token, and pack the match
329 // length into the remaining seven bits after subtracting `MIN_MATCH`.
330 let control = 0x80 | ((length - MIN_MATCH) as u8);
331 output.push(control);
332
333 // Store the backward distance as a little-endian `u16`, which matches the
334 // maximum window size enforced by the encoder.
335 output.extend_from_slice(&(offset as u16).to_le_bytes());
336}
337
338/// Emit any queued literal bytes as one or more literal-run tokens.
339fn flush_literals(output: &mut Vec<u8>, literals: &mut Vec<u8>) {
340 // `cursor` walks through the temporary literal buffer as we split it into
341 // one or more encoded runs.
342 let mut cursor = 0usize;
343
344 while cursor < literals.len() {
345 // Each literal token can encode at most 128 bytes because only seven
346 // control bits are available for the run length.
347 let run_len = (literals.len() - cursor).min(MAX_LITERAL_RUN);
348
349 // Literal tokens keep the high bit clear, so the control byte is just
350 // `run_len - 1`.
351 output.push((run_len - 1) as u8);
352 output.extend_from_slice(&literals[cursor..cursor + run_len]);
353 cursor += run_len;
354 }
355
356 // Reset the staging buffer so the caller can begin collecting a fresh run.
357 literals.clear();
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363
364 #[test]
365 fn round_trip_empty_input() {
366 let payload = b"";
367 let compressed = lz77_compress(payload);
368 let decompressed = lz77_decompress(&compressed);
369
370 assert_eq!(decompressed, payload);
371 assert_eq!(&compressed[..MAGIC.len()], MAGIC);
372 }
373
374 #[test]
375 fn round_trip_repeated_text() {
376 let payload = b"TOBEORNOTTOBEORTOBEORNOT";
377 let compressed = lz77_compress(payload);
378 let decompressed = lz77_decompress(&compressed);
379
380 assert_eq!(decompressed, payload);
381 assert!(compressed.len() < payload.len() + MAGIC.len());
382 }
383
384 #[test]
385 fn round_trip_binary_data_with_overlap() {
386 let payload = [7u8, 7, 7, 7, 7, 7, 9, 9, 9, 1, 2, 1, 2, 1, 2, 1, 2];
387 let compressed = lz77_compress(&payload);
388 let decompressed = lz77_decompress(&compressed);
389
390 assert_eq!(decompressed, payload);
391 }
392
393 #[test]
394 fn round_trip_kjv_text_asset() {
395 // Embed the asset directly into the test binary so the regression test
396 // is independent of the current working directory.
397 let payload = include_bytes!("../../test_assets/kjv.txt");
398 let compressed = lz77_compress(payload);
399 let decompressed = lz77_decompress(&compressed);
400
401 assert_eq!(decompressed, payload);
402 }
403
404 #[test]
405 fn malformed_stream_returns_error_in_try_api() {
406 let malformed = vec![b'L', b'Z', b'7', b'7', 0x80, 0x00, 0x00];
407 let result = try_lz77_decompress(&malformed);
408
409 assert!(result.is_err());
410 }
411
412 #[test]
413 fn malformed_stream_returns_empty_in_wrapper_api() {
414 let malformed = vec![0x80, 0x00, 0x00];
415 let decompressed = lz77_decompress(&malformed);
416
417 assert!(decompressed.is_empty());
418 }
419}