lib_jsl_information/source_coders/
shannon_fano.rs1use lib_jsl_core::ErrorsJSL;
30
31const MAGIC: &[u8; 4] = b"SFAN";
32
33#[derive(Clone, Copy, Debug)]
34struct SymbolFrequency {
35 symbol: u8,
36 frequency: u32,
37}
38
39#[derive(Clone, Debug)]
40enum DecodeNode {
41 Leaf { symbol: u8 },
42 Internal {
43 left: Option<Box<DecodeNode>>,
44 right: Option<Box<DecodeNode>>,
45 },
46}
47
48impl DecodeNode {
49 fn new_internal() -> Self {
50 Self::Internal {
51 left: None,
52 right: None,
53 }
54 }
55}
56
57pub fn shannon_fano_compress(input: &[u8]) -> Vec<u8> {
59 try_shannon_fano_compress(input).unwrap_or_default()
60}
61
62pub fn try_shannon_fano_compress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
64 if input.len() > u64::MAX as usize {
67 return Err(ErrorsJSL::InvalidInputRange("Shannon-Fano input is too large to encode its original length."));
68 }
69
70 let frequencies = build_frequency_table(input);
71 let symbol_count = frequencies.iter().filter(|&&count| count > 0).count();
72 if symbol_count > u16::MAX as usize {
73 return Err(ErrorsJSL::InvalidInputRange("Shannon-Fano frequency table has too many distinct symbols."));
74 }
75
76 let mut output = Vec::new();
77 output.extend_from_slice(MAGIC);
78 output.extend_from_slice(&(input.len() as u64).to_le_bytes());
79 output.extend_from_slice(&(symbol_count as u16).to_le_bytes());
80
81 for (symbol, &frequency) in frequencies.iter().enumerate() {
82 if frequency > 0 {
83 output.push(symbol as u8);
84 output.extend_from_slice(&frequency.to_le_bytes());
85 }
86 }
87
88 if input.is_empty() {
89 return Ok(output);
90 }
91
92 let mut symbols = sorted_symbols(&frequencies);
93 let mut codes = vec![Vec::new(); 256];
94
95 assign_codes(&mut symbols, &mut codes);
98 if symbols.len() == 1 {
99 return Ok(output);
101 }
102
103 let mut current_byte = 0u8;
104 let mut bit_count = 0u8;
105
106 for &byte in input {
107 for &bit in &codes[byte as usize] {
110 current_byte <<= 1;
111 if bit {
112 current_byte |= 1;
113 }
114 bit_count += 1;
115
116 if bit_count == 8 {
117 output.push(current_byte);
118 current_byte = 0;
119 bit_count = 0;
120 }
121 }
122 }
123
124 if bit_count > 0 {
125 current_byte <<= 8 - bit_count;
126 output.push(current_byte);
127 }
128
129 Ok(output)
130}
131
132pub fn shannon_fano_decompress(input: &[u8]) -> Vec<u8> {
134 try_shannon_fano_decompress(input).unwrap_or_default()
135}
136
137pub fn try_shannon_fano_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
139 if input.len() < MAGIC.len() || &input[..MAGIC.len()] != MAGIC {
142 return Err(ErrorsJSL::InvalidInputRange("Compressed payload is missing the Shannon-Fano header."));
143 }
144
145 let mut cursor = MAGIC.len();
146 if cursor + 8 + 2 > input.len() {
147 return Err(ErrorsJSL::InvalidInputRange("Shannon-Fano header is truncated before length or symbol count."));
148 }
149
150 let original_len = u64::from_le_bytes(
151 input[cursor..cursor + 8]
152 .try_into()
153 .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse Shannon-Fano original length field."))?,
154 ) as usize;
155 cursor += 8;
156
157 let symbol_count = u16::from_le_bytes(
158 input[cursor..cursor + 2]
159 .try_into()
160 .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse Shannon-Fano symbol count field."))?,
161 ) as usize;
162 cursor += 2;
163
164 let table_bytes = symbol_count
165 .checked_mul(5)
166 .ok_or(ErrorsJSL::InvalidInputRange("Shannon-Fano frequency table size overflowed."))?;
167 if cursor + table_bytes > input.len() {
168 return Err(ErrorsJSL::InvalidInputRange("Shannon-Fano frequency table extends beyond the compressed payload."));
169 }
170
171 let mut frequencies = [0u32; 256];
172 for _ in 0..symbol_count {
173 let symbol = input[cursor];
174 let frequency = u32::from_le_bytes(
175 input[cursor + 1..cursor + 5]
176 .try_into()
177 .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse Shannon-Fano symbol frequency field."))?,
178 );
179 cursor += 5;
180
181 if frequency == 0 {
182 return Err(ErrorsJSL::InvalidInputRange("Shannon-Fano frequency table cannot contain zero-frequency entries."));
183 }
184 if frequencies[symbol as usize] != 0 {
185 return Err(ErrorsJSL::InvalidInputRange("Shannon-Fano frequency table contains duplicate symbol entries."));
186 }
187
188 frequencies[symbol as usize] = frequency;
189 }
190
191 if original_len == 0 {
192 return Ok(Vec::new());
193 }
194
195 let total_frequency: usize = frequencies.iter().map(|&count| count as usize).sum();
196 if total_frequency != original_len {
197 return Err(ErrorsJSL::InvalidInputRange("Shannon-Fano frequency table does not match the stored original length."));
198 }
199
200 let mut symbols = sorted_symbols(&frequencies);
201 if symbols.len() == 1 {
202 return Ok(vec![symbols[0].symbol; original_len]);
205 }
206 let mut codes = vec![Vec::new(); 256];
207 assign_codes(&mut symbols, &mut codes);
208
209 let decode_root = build_decode_tree(&codes, &frequencies)?;
212
213 if let DecodeNode::Leaf { symbol } = decode_root {
214 return Ok(vec![symbol; original_len]);
215 }
216
217 let bitstream = &input[cursor..];
218 let mut output = Vec::with_capacity(original_len);
219 let mut current = &decode_root;
220
221 for &packed_byte in bitstream {
222 for shift in (0..8).rev() {
223 let bit_is_set = ((packed_byte >> shift) & 1) == 1;
225
226 current = match current {
227 DecodeNode::Leaf { symbol } => {
228 output.push(*symbol);
229 if output.len() == original_len {
230 return Ok(output);
231 }
232 descend_from_root(&decode_root, bit_is_set)?
233 }
234 DecodeNode::Internal { left, right } => {
235 if bit_is_set {
236 right.as_deref().ok_or(ErrorsJSL::InvalidInputRange(
237 "Shannon-Fano bitstream referenced a missing right branch.",
238 ))?
239 } else {
240 left.as_deref().ok_or(ErrorsJSL::InvalidInputRange(
241 "Shannon-Fano bitstream referenced a missing left branch.",
242 ))?
243 }
244 }
245 };
246
247 if let DecodeNode::Leaf { symbol } = current {
248 output.push(*symbol);
252 if output.len() == original_len {
253 return Ok(output);
254 }
255 current = &decode_root;
256 }
257 }
258 }
259
260 Err(ErrorsJSL::InvalidInputRange(
261 "Shannon-Fano bitstream ended before the declared number of output bytes was reconstructed.",
262 ))
263}
264
265fn descend_from_root(root: &DecodeNode, bit_is_set: bool) -> Result<&DecodeNode, ErrorsJSL> {
266 match root {
267 DecodeNode::Internal { left, right } => {
268 if bit_is_set {
269 right
270 .as_deref()
271 .ok_or(ErrorsJSL::InvalidInputRange("Shannon-Fano root is missing its right branch."))
272 } else {
273 left
274 .as_deref()
275 .ok_or(ErrorsJSL::InvalidInputRange("Shannon-Fano root is missing its left branch."))
276 }
277 }
278 DecodeNode::Leaf { .. } => Err(ErrorsJSL::RuntimeError(
279 "Tried to descend from a leaf-only Shannon-Fano tree.",
280 )),
281 }
282}
283
284fn build_frequency_table(input: &[u8]) -> [u32; 256] {
285 let mut frequencies = [0u32; 256];
288 for &byte in input {
289 frequencies[byte as usize] = frequencies[byte as usize].saturating_add(1);
290 }
291 frequencies
292}
293
294fn sorted_symbols(frequencies: &[u32; 256]) -> Vec<SymbolFrequency> {
295 let mut symbols = Vec::new();
296 for (symbol, &frequency) in frequencies.iter().enumerate() {
297 if frequency > 0 {
298 symbols.push(SymbolFrequency {
299 symbol: symbol as u8,
300 frequency,
301 });
302 }
303 }
304
305 symbols.sort_by(|left, right| {
308 right
309 .frequency
310 .cmp(&left.frequency)
311 .then_with(|| left.symbol.cmp(&right.symbol))
312 });
313 symbols
314}
315
316fn assign_codes(symbols: &mut [SymbolFrequency], codes: &mut [Vec<bool>]) {
317 if symbols.is_empty() {
318 return;
319 }
320 assign_codes_recursive(symbols, codes);
323}
324
325fn assign_codes_recursive(symbols: &mut [SymbolFrequency], codes: &mut [Vec<bool>]) {
326 if symbols.len() == 1 {
327 if codes[symbols[0].symbol as usize].is_empty() {
330 codes[symbols[0].symbol as usize].push(false);
331 }
332 return;
333 }
334
335 let split_index = choose_split_index(symbols);
337
338 for entry in &symbols[..split_index] {
340 codes[entry.symbol as usize].push(false);
341 }
342 for entry in &symbols[split_index..] {
344 codes[entry.symbol as usize].push(true);
345 }
346
347 let (left, right) = symbols.split_at_mut(split_index);
348 assign_codes_recursive(left, codes);
349 assign_codes_recursive(right, codes);
350 }
352
353fn choose_split_index(symbols: &[SymbolFrequency]) -> usize {
354 let total: u64 = symbols.iter().map(|entry| entry.frequency as u64).sum();
355 let mut left_sum = 0u64;
356 let mut best_index = 1usize;
357 let mut best_difference = total;
358
359 for index in 1..symbols.len() {
362 left_sum += symbols[index - 1].frequency as u64;
363 let right_sum = total - left_sum;
364 let difference = left_sum.abs_diff(right_sum);
365
366 if difference < best_difference {
367 best_difference = difference;
368 best_index = index;
369 }
370 }
371
372 best_index
373}
374
375fn build_decode_tree(codes: &[Vec<bool>], frequencies: &[u32; 256]) -> Result<DecodeNode, ErrorsJSL> {
376 let mut root = DecodeNode::new_internal();
377
378 for (symbol, code) in codes.iter().enumerate() {
379 if frequencies[symbol] == 0 {
380 continue;
381 }
382
383 if code.is_empty() {
384 return Err(ErrorsJSL::InvalidInputRange(
385 "Shannon-Fano code table unexpectedly contained an empty code for a present symbol.",
386 ));
387 }
388
389 insert_code(&mut root, code, symbol as u8)?;
390 }
391
392 Ok(root)
393}
394
395fn insert_code(root: &mut DecodeNode, code: &[bool], symbol: u8) -> Result<(), ErrorsJSL> {
396 insert_code_recursive(root, code, 0, symbol)
397}
398
399fn insert_code_recursive(
400 node: &mut DecodeNode,
401 code: &[bool],
402 depth: usize,
403 symbol: u8,
404) -> Result<(), ErrorsJSL> {
405 match node {
406 DecodeNode::Leaf { .. } => Err(ErrorsJSL::InvalidInputRange(
407 "Shannon-Fano code table attempted to descend through an existing leaf.",
408 )),
409 DecodeNode::Internal { left, right } => {
410 let bit = code
414 .get(depth)
415 .ok_or(ErrorsJSL::RuntimeError("Shannon-Fano insertion depth exceeded the code length."))?;
416 let slot = if *bit { right } else { left };
417
418 if depth + 1 == code.len() {
419 if slot.is_some() {
420 return Err(ErrorsJSL::InvalidInputRange(
421 "Shannon-Fano code table attempted to assign the same code path twice.",
422 ));
423 }
424 *slot = Some(Box::new(DecodeNode::Leaf { symbol }));
425 Ok(())
426 } else {
427 if slot.is_none() {
428 *slot = Some(Box::new(DecodeNode::new_internal()));
429 }
430 insert_code_recursive(
431 slot.as_deref_mut().ok_or(ErrorsJSL::RuntimeError(
432 "Shannon-Fano decode tree branch disappeared during insertion.",
433 ))?,
434 code,
435 depth + 1,
436 symbol,
437 )
438 }
439 }
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446
447 #[test]
448 fn round_trip_empty_input() {
449 let payload = b"";
450 let compressed = try_shannon_fano_compress(payload).unwrap();
451 let decompressed = try_shannon_fano_decompress(&compressed).unwrap();
452
453 assert_eq!(decompressed, payload);
454 assert_eq!(&compressed[..MAGIC.len()], MAGIC);
455 }
456
457 #[test]
458 fn round_trip_repeated_text() {
459 let payload = b"this is a shannon fano coding example";
460 let compressed = try_shannon_fano_compress(payload).unwrap();
461 let decompressed = try_shannon_fano_decompress(&compressed).unwrap();
462
463 assert_eq!(decompressed, payload);
464 }
465
466 #[test]
467 fn round_trip_binary_data() {
468 let payload = [0u8, 0, 1, 1, 1, 2, 3, 5, 8, 8, 13, 21, 34, 55];
469 let compressed = try_shannon_fano_compress(&payload).unwrap();
470 let decompressed = try_shannon_fano_decompress(&compressed).unwrap();
471
472 assert_eq!(decompressed, payload);
473 }
474
475 #[test]
476 fn round_trip_single_symbol_input() {
477 let payload = [7u8; 2048];
478 let compressed = try_shannon_fano_compress(&payload).unwrap();
479 let decompressed = try_shannon_fano_decompress(&compressed).unwrap();
480
481 assert_eq!(decompressed, payload);
482 assert_eq!(compressed.len(), 4 + 8 + 2 + 5, "header only, no payload bits");
483 }
484
485 #[test]
486 fn round_trip_kjv_text_asset() {
487 let payload = include_bytes!("../../test_assets/kjv.txt");
488 let compressed = try_shannon_fano_compress(payload).unwrap();
489 let decompressed = try_shannon_fano_decompress(&compressed).unwrap();
490
491 assert_eq!(decompressed, payload);
492 }
493
494 #[test]
495 fn malformed_stream_returns_error() {
496 let malformed = vec![b'S', b'F', b'A', b'N', 0x01];
497 let result = try_shannon_fano_decompress(&malformed);
498
499 assert!(result.is_err());
500 }
501
502 #[test]
503 fn wrapper_returns_empty_on_malformed_stream() {
504 let malformed = vec![0x01, 0x02, 0x03];
505 let decompressed = shannon_fano_decompress(&malformed);
506
507 assert!(decompressed.is_empty());
508 }
509}