1//! LZ4 Block Format
2//!
3//! As defined in <https://github.com/lz4/lz4/blob/dev/doc/lz4_Block_format.md>
4//!
5//! Currently for no_std support only the block format is supported.
6//!
7//! # Example: block format roundtrip
8//! ```
9//! use lz4_flex::block::{compress_prepend_size, decompress_size_prepended};
10//! let input: &[u8] = b"Hello people, what's up?";
11//! let compressed = compress_prepend_size(input);
12//! let uncompressed = decompress_size_prepended(&compressed).unwrap();
13//! assert_eq!(input, uncompressed);
14//! ```
15//!
1617#[cfg_attr(feature = "safe-encode", forbid(unsafe_code))]
18pub(crate) mod compress;
19pub(crate) mod hashtable;
2021#[cfg(feature = "safe-decode")]
22#[cfg_attr(feature = "safe-decode", forbid(unsafe_code))]
23pub(crate) mod decompress_safe;
24#[cfg(feature = "safe-decode")]
25pub(crate) use decompress_safe as decompress;
2627#[cfg(not(feature = "safe-decode"))]
28pub(crate) mod decompress;
2930pub use compress::*;
31pub use decompress::*;
3233use core::fmt;
3435pub(crate) const WINDOW_SIZE: usize = 64 * 1024;
3637/// https://github.com/lz4/lz4/blob/dev/doc/lz4_Block_format.md#end-of-block-restrictions
38/// The last match must start at least 12 bytes before the end of block. The last match is part of
39/// the penultimate sequence. It is followed by the last sequence, which contains only literals.
40///
41/// Note that, as a consequence, an independent block < 13 bytes cannot be compressed, because the
42/// match must copy "something", so it needs at least one prior byte.
43///
44/// When a block can reference data from another block, it can start immediately with a match and no
45/// literal, so a block of 12 bytes can be compressed.
46const MFLIMIT: usize = 12;
4748/// The last 5 bytes of input are always literals. Therefore, the last sequence contains at least 5
49/// bytes.
50const LAST_LITERALS: usize = 5;
5152/// Due the way the compression loop is arrange we may read up to (register_size - 2) bytes from the
53/// current position. So we must end the matches 6 bytes before the end, 1 more than required by the
54/// spec.
55const END_OFFSET: usize = LAST_LITERALS + 1;
5657/// https://github.com/lz4/lz4/blob/dev/doc/lz4_Block_format.md#end-of-block-restrictions
58/// Minimum length of a block
59///
60/// MFLIMIT + 1 for the token.
61const LZ4_MIN_LENGTH: usize = MFLIMIT + 1;
6263const MAXD_LOG: usize = 16;
64const MAX_DISTANCE: usize = (1 << MAXD_LOG) - 1;
6566#[allow(dead_code)]
67const MATCH_LENGTH_MASK: u32 = (1_u32 << 4) - 1; // 0b1111 / 15
6869/// The minimum length of a duplicate
70const MINMATCH: usize = 4;
7172#[allow(dead_code)]
73const FASTLOOP_SAFE_DISTANCE: usize = 64;
7475/// Switch for the hashtable size byU16
76#[allow(dead_code)]
77static LZ4_64KLIMIT: usize = (64 * 1024) + (MFLIMIT - 1);
7879/// An error representing invalid compressed data.
80#[derive(Debug)]
81#[non_exhaustive]
82pub enum DecompressError {
83/// The provided output is too small
84OutputTooSmall {
85/// Minimum expected output size
86expected: usize,
87/// Actual size of output
88actual: usize,
89 },
90/// Literal is out of bounds of the input
91LiteralOutOfBounds,
92/// Expected another byte, but none found.
93ExpectedAnotherByte,
94/// Deduplication offset out of bounds (not in buffer).
95OffsetOutOfBounds,
96}
9798#[derive(Debug)]
99#[non_exhaustive]
100/// Errors that can happen during compression.
101pub enum CompressError {
102/// The provided output is too small.
103OutputTooSmall,
104}
105106impl fmt::Display for DecompressError {
107fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108match self {
109 DecompressError::OutputTooSmall { expected, actual } => {
110write!(
111 f,
112"provided output is too small for the decompressed data, actual {actual}, expected \
113 {expected}"
114)
115 }
116 DecompressError::LiteralOutOfBounds => {
117 f.write_str("literal is out of bounds of the input")
118 }
119 DecompressError::ExpectedAnotherByte => {
120 f.write_str("expected another byte, found none")
121 }
122 DecompressError::OffsetOutOfBounds => {
123 f.write_str("the offset to copy is not contained in the decompressed buffer")
124 }
125 }
126 }
127}
128129impl fmt::Display for CompressError {
130fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
131match self {
132 CompressError::OutputTooSmall => f.write_str(
133"output is too small for the compressed data, use get_maximum_output_size to \
134 reserve enough space",
135 ),
136 }
137 }
138}
139140#[cfg(feature = "std")]
141impl std::error::Error for DecompressError {}
142143#[cfg(feature = "std")]
144impl std::error::Error for CompressError {}
145146/// This can be used in conjunction with `decompress_size_prepended`.
147/// It will read the first 4 bytes as little-endian encoded length, and return
148/// the rest of the bytes after the length encoding.
149#[inline]
150pub fn uncompressed_size(input: &[u8]) -> Result<(usize, &[u8]), DecompressError> {
151let size = input.get(..4).ok_or(DecompressError::ExpectedAnotherByte)?;
152let size: &[u8; 4] = size.try_into().unwrap();
153let uncompressed_size = u32::from_le_bytes(*size) as usize;
154let rest = &input[4..];
155Ok((uncompressed_size, rest))
156}