Skip to main content

lib_jsl_information/source_coders/
source_coder.rs

1//! Shared trait wrappers for the source-coding implementations in this crate.
2//!
3//! The individual modules such as [`crate::lz77`], [`crate::lz78`], and
4//! [`crate::lzw`] intentionally expose plain function-based APIs because that
5//! keeps each algorithm easy to read in isolation. This module adds a thin
6//! trait layer on top so generic code can work with any of those codecs
7//! through one unified interface.
8//!
9//! # Design
10//!
11//! The trait uses associated functions rather than instance methods because the
12//! current codecs are stateless. Each implementation is represented by a
13//! zero-sized wrapper type that simply forwards to the existing module-level
14//! functions.
15//!
16//! See the book entry [Entropy coding](https://jwkunz.github.io/lib_jsl/book/information/entropy-coding.html#implementation).
17
18use lib_jsl_core::ErrorsJSL;
19
20use super::{arithmetic, huffman, lz77, lz78, lzw, shannon_fano};
21
22/// Common interface for byte-oriented source coders in this crate.
23///
24/// A source coder consumes raw bytes and either:
25///
26/// - produces a compressed byte stream with [`try_compress`](SourceCoder::try_compress), or
27/// - reconstructs the original bytes with [`try_decompress`](SourceCoder::try_decompress)
28///
29/// The methods are fallible so callers can handle malformed compressed data or
30/// future codec-specific compression failures through the same `Result` type.
31pub trait SourceCoder {
32    /// Compress a raw byte slice into a codec-specific byte stream.
33    ///
34    /// The trait keeps the signature intentionally small so generic code can
35    /// swap one source coder for another without having to learn codec-specific
36    /// setup APIs first.
37    fn try_compress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL>;
38
39    /// Decompress a codec-specific byte stream back into its original bytes.
40    fn try_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL>;
41}
42
43/// Zero-sized wrapper for the sliding-window LZ77 implementation.
44pub struct Lz77SourceCoder;
45
46impl SourceCoder for Lz77SourceCoder {
47    fn try_compress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
48        // The current LZ77 encoder cannot fail, so the trait wrapper simply
49        // lifts the existing byte vector into `Ok(...)`.
50        Ok(lz77::lz77_compress(input))
51    }
52
53    fn try_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
54        lz77::try_lz77_decompress(input)
55    }
56}
57
58/// Zero-sized wrapper for the explicit-dictionary LZ78 implementation.
59pub struct Lz78SourceCoder;
60
61impl SourceCoder for Lz78SourceCoder {
62    fn try_compress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
63        // The wrapper's only job is to adapt the plain function-based module
64        // API into the shared trait shape.
65        Ok(lz78::lz78_compress(input))
66    }
67
68    fn try_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
69        lz78::try_lz78_decompress(input)
70    }
71}
72
73/// Zero-sized wrapper for the Welch-style LZW implementation.
74pub struct LzwSourceCoder;
75
76impl SourceCoder for LzwSourceCoder {
77    fn try_compress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
78        Ok(lzw::lzw_compress(input))
79    }
80
81    fn try_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
82        lzw::try_lzw_decompress(input)
83    }
84}
85
86/// Zero-sized wrapper for the Huffman implementation.
87pub struct HuffmanSourceCoder;
88
89impl SourceCoder for HuffmanSourceCoder {
90    fn try_compress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
91        huffman::try_huffman_compress(input)
92    }
93
94    fn try_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
95        huffman::try_huffman_decompress(input)
96    }
97}
98
99/// Zero-sized wrapper for the arithmetic coding implementation.
100pub struct ArithmeticSourceCoder;
101
102impl SourceCoder for ArithmeticSourceCoder {
103    fn try_compress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
104        arithmetic::try_arithmetic_compress(input)
105    }
106
107    fn try_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
108        arithmetic::try_arithmetic_decompress(input)
109    }
110}
111
112/// Zero-sized wrapper for the Shannon-Fano implementation.
113pub struct ShannonFanoSourceCoder;
114
115impl SourceCoder for ShannonFanoSourceCoder {
116    fn try_compress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
117        shannon_fano::try_shannon_fano_compress(input)
118    }
119
120    fn try_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
121        shannon_fano::try_shannon_fano_decompress(input)
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    fn assert_round_trip<T: SourceCoder>(payload: &[u8]) {
130        // This helper exercises the exact trait surface that generic callers
131        // would use: compress first, then decompress that returned byte stream.
132        let compressed = T::try_compress(payload).expect("compression should succeed");
133        let decompressed = T::try_decompress(&compressed).expect("decompression should succeed");
134        assert_eq!(decompressed, payload);
135    }
136
137    #[test]
138    fn lz77_trait_wrapper_round_trip() {
139        assert_round_trip::<Lz77SourceCoder>(b"TOBEORNOTTOBEORTOBEORNOT");
140    }
141
142    #[test]
143    fn lz78_trait_wrapper_round_trip() {
144        assert_round_trip::<Lz78SourceCoder>(b"ABAABABAABBBBBBBBB");
145    }
146
147    #[test]
148    fn lzw_trait_wrapper_round_trip() {
149        assert_round_trip::<LzwSourceCoder>(b"TOBEORNOTTOBEORTOBEORNOT");
150    }
151
152    #[test]
153    fn huffman_trait_wrapper_round_trip() {
154        assert_round_trip::<HuffmanSourceCoder>(b"this is an example of a huffman tree");
155    }
156
157    #[test]
158    fn arithmetic_trait_wrapper_round_trip() {
159        assert_round_trip::<ArithmeticSourceCoder>(b"arithmetic coding narrows an interval symbol by symbol");
160    }
161
162    #[test]
163    fn shannon_fano_trait_wrapper_round_trip() {
164        assert_round_trip::<ShannonFanoSourceCoder>(b"shannon fano recursively splits symbols by probability");
165    }
166
167    #[test]
168    fn trait_wrappers_support_large_asset_round_trip() {
169        let payload = include_bytes!("../../test_assets/kjv.txt");
170
171        assert_round_trip::<ArithmeticSourceCoder>(payload);
172        assert_round_trip::<HuffmanSourceCoder>(payload);
173        assert_round_trip::<Lz77SourceCoder>(payload);
174        assert_round_trip::<Lz78SourceCoder>(payload);
175        assert_round_trip::<LzwSourceCoder>(payload);
176        assert_round_trip::<ShannonFanoSourceCoder>(payload);
177    }
178}