lib_jsl_information/source_coders/
arithmetic.rs1use lib_jsl_core::ErrorsJSL;
34
35const MAGIC: &[u8; 4] = b"ARI0";
36const CODE_VALUE_BITS: u32 = 32;
37const TOP_VALUE: u64 = (1u64 << CODE_VALUE_BITS) - 1;
38const FIRST_QTR: u64 = TOP_VALUE / 4 + 1;
39const HALF: u64 = 2 * FIRST_QTR;
40const THIRD_QTR: u64 = 3 * FIRST_QTR;
41const MAX_TOTAL: u64 = FIRST_QTR;
45
46#[derive(Clone, Debug)]
47struct Model {
48 frequencies: [u32; 256],
49 cumulative: [u64; 257],
50 total: u64,
51}
52
53pub fn arithmetic_compress(input: &[u8]) -> Vec<u8> {
55 try_arithmetic_compress(input).unwrap_or_default()
56}
57
58pub fn try_arithmetic_compress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
60 compress_with_limit(input, MAX_TOTAL)
61}
62
63fn compress_with_limit(input: &[u8], limit: u64) -> Result<Vec<u8>, ErrorsJSL> {
65 if input.len() > u64::MAX as usize {
68 return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder input is too large to store its original length."));
69 }
70
71 let model = fit_model(build_model(input)?, limit)?;
74 let symbol_count = model.frequencies.iter().filter(|&&count| count > 0).count();
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 model.frequencies.iter().enumerate() {
84 if frequency > 0 {
85 output.push(symbol as u8);
86 output.extend_from_slice(&frequency.to_le_bytes());
87 }
88 }
89
90 if input.is_empty() {
91 output.extend_from_slice(&0u64.to_le_bytes());
92 return Ok(output);
93 }
94
95 let mut writer = BitWriter::default();
96 let mut low = 0u64;
97 let mut high = TOP_VALUE;
98 let mut pending_bits = 0u64;
99
100 for &symbol in input {
101 let symbol_index = symbol as usize;
105 let range = (high - low + 1) as u128;
107 let cum_low = model.cumulative[symbol_index] as u128;
108 let cum_high = model.cumulative[symbol_index + 1] as u128;
109 let total = model.total as u128;
110
111 high = low + ((range * cum_high) / total - 1) as u64;
113 low += ((range * cum_low) / total) as u64;
114
115 loop {
118 if high < HALF {
119 output_bit_plus_pending(&mut writer, false, &mut pending_bits);
122 } else if low >= HALF {
123 output_bit_plus_pending(&mut writer, true, &mut pending_bits);
127 low -= HALF;
128 high -= HALF;
129 } else if low >= FIRST_QTR && high < THIRD_QTR {
130 pending_bits += 1;
134 low -= FIRST_QTR;
135 high -= FIRST_QTR;
136 } else {
137 break;
138 }
139
140 low = low.saturating_mul(2);
144 high = high.saturating_mul(2).saturating_add(1);
145 }
146 }
148
149 pending_bits += 1;
152 if low < FIRST_QTR {
153 output_bit_plus_pending(&mut writer, false, &mut pending_bits);
154 } else {
155 output_bit_plus_pending(&mut writer, true, &mut pending_bits);
156 }
157
158 let (payload_bytes, payload_bits) = writer.finish();
159 output.extend_from_slice(&payload_bits.to_le_bytes());
160 output.extend_from_slice(&payload_bytes);
161 Ok(output)
162}
163
164pub fn arithmetic_decompress(input: &[u8]) -> Vec<u8> {
166 try_arithmetic_decompress(input).unwrap_or_default()
167}
168
169pub fn try_arithmetic_decompress(input: &[u8]) -> Result<Vec<u8>, ErrorsJSL> {
171 if input.len() < MAGIC.len() || &input[..MAGIC.len()] != MAGIC {
174 return Err(ErrorsJSL::InvalidInputRange("Compressed payload is missing the arithmetic coder header."));
175 }
176
177 let mut cursor = MAGIC.len();
178 if cursor + 8 + 2 > input.len() {
179 return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder header is truncated before length or symbol count."));
180 }
181
182 let original_len = u64::from_le_bytes(
183 input[cursor..cursor + 8]
184 .try_into()
185 .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse arithmetic coder original length field."))?,
186 ) as usize;
187 cursor += 8;
188
189 let symbol_count = u16::from_le_bytes(
190 input[cursor..cursor + 2]
191 .try_into()
192 .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse arithmetic coder symbol count field."))?,
193 ) as usize;
194 cursor += 2;
195
196 let table_bytes = symbol_count
197 .checked_mul(5)
198 .ok_or(ErrorsJSL::InvalidInputRange("Arithmetic coder frequency table size overflowed."))?;
199 if cursor + table_bytes + 8 > input.len() {
200 return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder header extends beyond the compressed payload."));
201 }
202
203 let mut frequencies = [0u32; 256];
204 for _ in 0..symbol_count {
205 let symbol = input[cursor];
206 let frequency = u32::from_le_bytes(
207 input[cursor + 1..cursor + 5]
208 .try_into()
209 .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse arithmetic coder symbol frequency field."))?,
210 );
211 cursor += 5;
212
213 if frequency == 0 {
214 return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder frequency table cannot contain zero-frequency entries."));
215 }
216 if frequencies[symbol as usize] != 0 {
217 return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder frequency table contains duplicate symbol entries."));
218 }
219
220 frequencies[symbol as usize] = frequency;
221 }
222
223 let payload_bits = u64::from_le_bytes(
224 input[cursor..cursor + 8]
225 .try_into()
226 .map_err(|_| ErrorsJSL::RuntimeError("Failed to parse arithmetic coder payload bit length field."))?,
227 );
228 cursor += 8;
229
230 let payload = &input[cursor..];
231 let available_bits = (payload.len() as u64)
232 .checked_mul(8)
233 .ok_or(ErrorsJSL::InvalidInputRange("Arithmetic coder payload size overflowed while checking bit capacity."))?;
234 if payload_bits > available_bits {
235 return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder payload bit length exceeds the available payload bytes."));
236 }
237
238 if original_len == 0 {
239 return Ok(Vec::new());
240 }
241
242 let model = build_model_from_frequencies(frequencies)?;
243 let rescaled = model.total < original_len as u64 && model.total <= MAX_TOTAL;
246 if model.total as usize != original_len && !rescaled {
247 return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder frequency table does not match the stored original length."));
248 }
249
250 let mut reader = BitReader::new(payload, payload_bits);
251 let mut low = 0u64;
252 let mut high = TOP_VALUE;
253 let mut code = 0u64;
254
255 for _ in 0..CODE_VALUE_BITS {
259 code = (code << 1) | reader.read_bit_or_zero();
260 }
261
262 let mut output = Vec::with_capacity(original_len);
263
264 while output.len() < original_len {
265 let range = (high - low + 1) as u128;
266 let total = model.total as u128;
267
268 let scaled_value =
271 (((code - low + 1) as u128 * total - 1) / range) as u64;
272
273 let symbol = find_symbol(&model.cumulative, scaled_value)?;
274 output.push(symbol as u8);
275
276 let cum_low = model.cumulative[symbol] as u128;
279 let cum_high = model.cumulative[symbol + 1] as u128;
280
281 high = low + ((range * cum_high) / total - 1) as u64;
282 low += ((range * cum_low) / total) as u64;
283
284 loop {
285 if high < HALF {
286 } else if low >= HALF {
288 code -= HALF;
290 low -= HALF;
291 high -= HALF;
292 } else if low >= FIRST_QTR && high < THIRD_QTR {
293 code -= FIRST_QTR;
295 low -= FIRST_QTR;
296 high -= FIRST_QTR;
297 } else {
298 break;
299 }
300
301 low = low.saturating_mul(2);
304 high = high.saturating_mul(2).saturating_add(1);
305 code = code.saturating_mul(2).saturating_add(reader.read_bit_or_zero());
306 }
307 }
308
309 Ok(output)
310}
311
312fn build_model(input: &[u8]) -> Result<Model, ErrorsJSL> {
313 let mut frequencies = [0u32; 256];
316 for &byte in input {
317 frequencies[byte as usize] = frequencies[byte as usize]
318 .checked_add(1)
319 .ok_or(ErrorsJSL::InvalidInputRange("Arithmetic coder frequency overflowed while counting symbols."))?;
320 }
321 build_model_from_frequencies(frequencies)
322}
323
324fn fit_model(model: Model, limit: u64) -> Result<Model, ErrorsJSL> {
327 if model.total <= limit {
328 return Ok(model);
329 }
330 let present = model.frequencies.iter().filter(|&&f| f > 0).count() as u64;
331 if present > limit {
332 return Err(ErrorsJSL::InvalidInputRange("Arithmetic coder frequency limit is below the number of symbols."));
333 }
334 let budget = (limit - present) as u128;
336 let mut scaled = [0u32; 256];
337 for (s, &f) in model.frequencies.iter().enumerate() {
338 if f > 0 {
339 scaled[s] = (1 + f as u128 * budget / model.total as u128) as u32;
340 }
341 }
342 build_model_from_frequencies(scaled)
343}
344
345fn build_model_from_frequencies(frequencies: [u32; 256]) -> Result<Model, ErrorsJSL> {
346 let mut cumulative = [0u64; 257];
347 for (index, &frequency) in frequencies.iter().enumerate() {
348 cumulative[index + 1] = cumulative[index]
351 .checked_add(frequency as u64)
352 .ok_or(ErrorsJSL::InvalidInputRange("Arithmetic coder cumulative frequency overflowed."))?;
353 }
354
355 Ok(Model {
356 frequencies,
357 cumulative,
358 total: cumulative[256],
359 })
360}
361
362fn find_symbol(cumulative: &[u64; 257], scaled_value: u64) -> Result<usize, ErrorsJSL> {
363 let mut low = 0usize;
367 let mut high = 256usize;
368
369 while low < high {
370 let mid = (low + high) / 2;
371 if cumulative[mid + 1] <= scaled_value {
372 low = mid + 1;
373 } else if cumulative[mid] > scaled_value {
374 high = mid;
375 } else {
376 return Ok(mid);
377 }
378 }
379
380 Err(ErrorsJSL::InvalidInputRange("Arithmetic coder could not map the current code value to a symbol interval."))
381}
382
383fn output_bit_plus_pending(writer: &mut BitWriter, bit: bool, pending_bits: &mut u64) {
384 writer.write_bit(bit);
386 while *pending_bits > 0 {
387 writer.write_bit(!bit);
390 *pending_bits -= 1;
391 }
392}
393
394#[derive(Default)]
395struct BitWriter {
396 bytes: Vec<u8>,
397 current_byte: u8,
398 bits_in_current_byte: u8,
399 bits_written: u64,
400}
401
402impl BitWriter {
403 fn write_bit(&mut self, bit: bool) {
404 self.current_byte <<= 1;
405 if bit {
406 self.current_byte |= 1;
407 }
408 self.bits_in_current_byte += 1;
409 self.bits_written += 1;
410
411 if self.bits_in_current_byte == 8 {
412 self.bytes.push(self.current_byte);
413 self.current_byte = 0;
414 self.bits_in_current_byte = 0;
415 }
416 }
417
418 fn finish(mut self) -> (Vec<u8>, u64) {
419 if self.bits_in_current_byte > 0 {
420 self.current_byte <<= 8 - self.bits_in_current_byte;
421 self.bytes.push(self.current_byte);
422 }
423 (self.bytes, self.bits_written)
424 }
425}
426
427struct BitReader<'a> {
428 bytes: &'a [u8],
429 total_bits: u64,
430 bit_position: u64,
431}
432
433impl<'a> BitReader<'a> {
434 fn new(bytes: &'a [u8], total_bits: u64) -> Self {
435 Self {
436 bytes,
437 total_bits,
438 bit_position: 0,
439 }
440 }
441
442 fn read_bit_or_zero(&mut self) -> u64 {
443 if self.bit_position >= self.total_bits {
444 return 0;
445 }
446
447 let byte_index = (self.bit_position / 8) as usize;
448 let bit_index = 7 - (self.bit_position % 8) as u8;
449 self.bit_position += 1;
450 ((self.bytes[byte_index] >> bit_index) & 1) as u64
451 }
452}
453
454#[cfg(test)]
455mod tests {
456 use super::*;
457
458 #[test]
459 fn round_trip_empty_input() {
460 let payload = b"";
461 let compressed = try_arithmetic_compress(payload).unwrap();
462 let decompressed = try_arithmetic_decompress(&compressed).unwrap();
463
464 assert_eq!(decompressed, payload);
465 assert_eq!(&compressed[..MAGIC.len()], MAGIC);
466 }
467
468 #[test]
469 fn round_trip_repeated_text() {
470 let payload = b"BANANA_BANDANA_BANANA_BANDANA";
471 let compressed = try_arithmetic_compress(payload).unwrap();
472 let decompressed = try_arithmetic_decompress(&compressed).unwrap();
473
474 assert_eq!(decompressed, payload);
475 }
476
477 #[test]
478 fn round_trip_binary_data() {
479 let payload = [0u8, 1, 1, 2, 3, 5, 8, 13, 13, 13, 21, 34, 55];
480 let compressed = try_arithmetic_compress(&payload).unwrap();
481 let decompressed = try_arithmetic_decompress(&compressed).unwrap();
482
483 assert_eq!(decompressed, payload);
484 }
485
486 #[test]
487 fn round_trip_single_symbol_input() {
488 let payload = [9u8; 2048];
489 let compressed = try_arithmetic_compress(&payload).unwrap();
490 let decompressed = try_arithmetic_decompress(&compressed).unwrap();
491
492 assert_eq!(decompressed, payload);
493 }
494
495 #[test]
496 fn round_trip_kjv_text_asset() {
497 let payload = include_bytes!("../../test_assets/kjv.txt");
498 let compressed = try_arithmetic_compress(payload).unwrap();
499 let decompressed = try_arithmetic_decompress(&compressed).unwrap();
500
501 assert_eq!(decompressed, payload);
502 }
503
504 #[test]
505 fn a_model_too_large_for_the_coder_is_rescaled() {
506 let payload = include_bytes!("../../test_assets/kjv.txt");
508 let compressed = compress_with_limit(payload, 1000).unwrap();
509 let symbol_count = u16::from_le_bytes([compressed[12], compressed[13]]) as usize;
510 let total: u64 = (0..symbol_count).map(|k| u32::from_le_bytes(compressed[15 + 5 * k..19 + 5 * k].try_into().unwrap()) as u64).sum();
511 assert!(total <= 1000, "stored total {total}");
512 assert_eq!(try_arithmetic_decompress(&compressed).unwrap(), payload);
513 assert!(compressed.len() > try_arithmetic_compress(payload).unwrap().len());
515 }
516
517 #[test]
518 fn malformed_stream_returns_error() {
519 let malformed = vec![b'A', b'R', b'I', b'0', 0x01];
520 let result = try_arithmetic_decompress(&malformed);
521
522 assert!(result.is_err());
523 }
524
525 #[test]
526 fn wrapper_returns_empty_on_malformed_stream() {
527 let malformed = vec![0x01, 0x02, 0x03];
528 let decompressed = arithmetic_decompress(&malformed);
529
530 assert!(decompressed.is_empty());
531 }
532}