bc_components/
compressed.rs

1use std::{borrow::Cow, fmt::Formatter};
2
3use bc_crypto::hash::crc32;
4use bc_ur::prelude::*;
5use miniz_oxide::{deflate::compress_to_vec, inflate::decompress_to_vec};
6
7use crate::{DigestProvider, Error, Result, digest::Digest, tags};
8
9/// A compressed binary object with integrity verification.
10///
11/// `Compressed` provides a way to efficiently store and transmit binary data
12/// using the DEFLATE compression algorithm. It includes built-in integrity
13/// verification through a CRC32 checksum and optional cryptographic digest.
14///
15/// The compression is implemented using the raw DEFLATE format as described in
16/// [IETF RFC 1951](https://www.ietf.org/rfc/rfc1951.txt) with the following
17/// configuration equivalent to:
18///
19/// `deflateInit2(zstream, 5, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY)`
20///
21/// Features:
22/// - Automatic compression with configurable compression level
23/// - Integrity verification via CRC32 checksum
24/// - Optional cryptographic digest for content identification
25/// - Smart behavior for small data (stores decompressed if compression would
26///   increase size)
27/// - CBOR serialization/deserialization support
28#[derive(Clone, Eq, PartialEq)]
29pub struct Compressed {
30    /// CRC32 checksum of the decompressed data for integrity verification
31    checksum: u32,
32    /// Size of the original decompressed data in bytes
33    decompressed_size: usize,
34    /// The compressed data (or original data if compression is ineffective)
35    compressed_data: Vec<u8>,
36    /// Optional cryptographic digest of the content
37    digest: Option<Digest>,
38}
39
40impl Compressed {
41    /// Creates a new `Compressed` object with the specified parameters.
42    ///
43    /// This is a low-level constructor that allows direct creation of a
44    /// `Compressed` object without performing compression. It's primarily
45    /// intended for deserialization or when working with pre-compressed
46    /// data.
47    ///
48    /// # Parameters
49    ///
50    /// * `checksum` - CRC32 checksum of the decompressed data
51    /// * `decompressed_size` - Size of the original decompressed data in bytes
52    /// * `compressed_data` - The compressed data bytes
53    /// * `digest` - Optional cryptographic digest of the content
54    ///
55    /// # Returns
56    ///
57    /// A `Result` containing the new `Compressed` object if successful,
58    /// or an error if the parameters are invalid.
59    ///
60    /// # Errors
61    ///
62    /// Returns an error if the compressed data is larger than the decompressed
63    /// size, which would indicate a logical inconsistency.
64    ///
65    /// # Example
66    ///
67    /// ```
68    /// use bc_components::Compressed;
69    /// use bc_crypto::hash::crc32;
70    ///
71    /// let data = b"hello world";
72    /// let checksum = crc32(data);
73    /// let decompressed_size = data.len();
74    ///
75    /// // In a real scenario, this would be actually compressed data
76    /// let compressed_data = data.to_vec();
77    ///
78    /// let compressed =
79    ///     Compressed::new(checksum, decompressed_size, compressed_data, None)
80    ///         .unwrap();
81    /// ```
82    pub fn new(
83        checksum: u32,
84        decompressed_size: usize,
85        compressed_data: Vec<u8>,
86        digest: Option<Digest>,
87    ) -> Result<Self> {
88        if compressed_data.len() > decompressed_size {
89            return Err(Error::compression(
90                "compressed data is larger than decompressed size",
91            ));
92        }
93        Ok(Self {
94            checksum,
95            decompressed_size,
96            compressed_data,
97            digest,
98        })
99    }
100
101    /// Creates a new `Compressed` object by compressing the provided data.
102    ///
103    /// This is the primary method for creating compressed data. It
104    /// automatically handles compression using the DEFLATE algorithm with a
105    /// compression level of 6.
106    ///
107    /// If the compressed data would be larger than the original data (which can
108    /// happen with small or already compressed inputs), the original data
109    /// is stored instead.
110    ///
111    /// # Parameters
112    ///
113    /// * `decompressed_data` - The original data to compress
114    /// * `digest` - Optional cryptographic digest of the content
115    ///
116    /// # Returns
117    ///
118    /// A new `Compressed` object containing the compressed (or original) data.
119    ///
120    /// # Example
121    ///
122    /// ```
123    /// use bc_components::Compressed;
124    ///
125    /// // Compress a string
126    /// let data = "This is a longer string that should compress well with repeated patterns. \
127    ///            This is a longer string that should compress well with repeated patterns.";
128    /// let compressed = Compressed::from_decompressed_data(data.as_bytes(), None);
129    ///
130    /// // The compressed size should be smaller than the original
131    /// assert!(compressed.compressed_size() < data.len());
132    ///
133    /// // We can recover the original data
134    /// let decompressed = compressed.decompress().unwrap();
135    /// assert_eq!(decompressed, data.as_bytes());
136    /// ```
137    pub fn from_decompressed_data(
138        decompressed_data: impl AsRef<[u8]>,
139        digest: Option<Digest>,
140    ) -> Self {
141        let decompressed_data = decompressed_data.as_ref();
142        let compressed_data = compress_to_vec(decompressed_data, 6);
143        let checksum = crc32(decompressed_data);
144        let decompressed_size = decompressed_data.len();
145        let compressed_size = compressed_data.len();
146        if compressed_size != 0 && compressed_size < decompressed_size {
147            Self {
148                checksum,
149                decompressed_size,
150                compressed_data,
151                digest,
152            }
153        } else {
154            Self {
155                checksum,
156                decompressed_size,
157                compressed_data: decompressed_data.to_vec(),
158                digest,
159            }
160        }
161    }
162
163    /// Decompresses and returns the original decompressed data.
164    ///
165    /// This method performs the reverse of the compression process, restoring
166    /// the original data. It also verifies the integrity of the data using the
167    /// stored checksum.
168    ///
169    /// # Returns
170    ///
171    /// A `Result` containing the decompressed data if successful,
172    /// or an error if decompression fails or the checksum doesn't match.
173    ///
174    /// # Errors
175    ///
176    /// Returns an error if:
177    /// - The compressed data is corrupt and cannot be decompressed
178    /// - The checksum of the decompressed data doesn't match the stored
179    ///   checksum
180    ///
181    /// # Example
182    ///
183    /// ```
184    /// use bc_components::Compressed;
185    ///
186    /// // Original data
187    /// let original = b"This is some example data to compress";
188    ///
189    /// // Compress it
190    /// let compressed = Compressed::from_decompressed_data(original, None);
191    ///
192    /// // Deompress to get the original data back
193    /// let decompressed = compressed.decompress().unwrap();
194    /// assert_eq!(decompressed, original);
195    /// ```
196    pub fn decompress(&self) -> Result<Vec<u8>> {
197        let compressed_size = self.compressed_data.len();
198        if compressed_size >= self.decompressed_size {
199            return Ok(self.compressed_data.clone());
200        }
201
202        let decompressed_data = decompress_to_vec(&self.compressed_data)
203            .map_err(|_| Error::compression("corrupt compressed data"))?;
204        if crc32(&decompressed_data) != self.checksum {
205            return Err(Error::compression(
206                "compressed data checksum mismatch",
207            ));
208        }
209
210        Ok(decompressed_data)
211    }
212
213    /// Returns the size of the compressed data in bytes.
214    ///
215    /// # Returns
216    ///
217    /// The size of the compressed data in bytes.
218    ///
219    /// # Example
220    ///
221    /// ```
222    /// use bc_components::Compressed;
223    ///
224    /// let data = b"Hello world!";
225    /// let compressed = Compressed::from_decompressed_data(data, None);
226    ///
227    /// // For small inputs like this, compression might not be effective
228    /// // so the compressed_size might equal the original size
229    /// println!("Compressed size: {}", compressed.compressed_size());
230    /// ```
231    pub fn compressed_size(&self) -> usize { self.compressed_data.len() }
232
233    /// Returns the compression ratio of the data.
234    ///
235    /// The compression ratio is calculated as (compressed size) / (decompressed
236    /// size), so lower values indicate better compression.
237    ///
238    /// # Returns
239    ///
240    /// A floating-point value representing the compression ratio.
241    /// - Values less than 1.0 indicate effective compression
242    /// - Values equal to 1.0 indicate no compression was applied
243    /// - Values of NaN can occur if the decompressed size is zero
244    ///
245    /// # Example
246    ///
247    /// ```
248    /// use bc_components::Compressed;
249    ///
250    /// // A string with a lot of repetition should compress well
251    /// let data = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
252    /// let compressed = Compressed::from_decompressed_data(data.as_bytes(), None);
253    ///
254    /// // Should have a good compression ratio (much less than 1.0)
255    /// let ratio = compressed.compression_ratio();
256    /// assert!(ratio < 0.5);
257    /// ```
258    pub fn compression_ratio(&self) -> f64 {
259        (self.compressed_size() as f64) / (self.decompressed_size as f64)
260    }
261
262    /// Returns a reference to the digest of the compressed data, if available.
263    ///
264    /// # Returns
265    ///
266    /// An optional reference to the `Digest` associated with this compressed
267    /// data.
268    ///
269    /// # Example
270    ///
271    /// ```
272    /// use bc_components::{Compressed, Digest};
273    ///
274    /// let data = b"Hello world!";
275    /// let digest = Digest::from_image(data);
276    /// let compressed =
277    ///     Compressed::from_decompressed_data(data, Some(digest.clone()));
278    ///
279    /// // We can retrieve the digest we associated with the compressed data
280    /// assert_eq!(compressed.digest_ref_opt(), Some(&digest));
281    /// ```
282    pub fn digest_ref_opt(&self) -> Option<&Digest> { self.digest.as_ref() }
283
284    /// Returns whether this compressed data has an associated digest.
285    ///
286    /// # Returns
287    ///
288    /// `true` if this compressed data has a digest, `false` otherwise.
289    ///
290    /// # Example
291    ///
292    /// ```
293    /// use bc_components::{Compressed, Digest};
294    ///
295    /// // Create compressed data without a digest
296    /// let compressed1 = Compressed::from_decompressed_data(b"Hello", None);
297    /// assert!(!compressed1.has_digest());
298    ///
299    /// // Create compressed data with a digest
300    /// let digest = Digest::from_image(b"Hello");
301    /// let compressed2 =
302    ///     Compressed::from_decompressed_data(b"Hello", Some(digest));
303    /// assert!(compressed2.has_digest());
304    /// ```
305    pub fn has_digest(&self) -> bool { self.digest.is_some() }
306}
307
308/// Implementation of the `DigestProvider` trait for `Compressed`.
309///
310/// Allows `Compressed` objects with digests to be used with APIs that accept
311/// `DigestProvider` implementations.
312impl DigestProvider for Compressed {
313    /// Returns the cryptographic digest associated with this compressed data.
314    ///
315    /// # Returns
316    ///
317    /// A `Cow<'_, Digest>` containing the digest.
318    ///
319    /// # Panics
320    ///
321    /// Panics if there is no digest associated with this compressed data.
322    /// Use `has_digest()` or `digest_ref_opt()` to check before calling this
323    /// method.
324    fn digest(&self) -> Cow<'_, Digest> {
325        Cow::Owned(self.digest.as_ref().unwrap().clone())
326    }
327}
328
329/// Implementation of the `Debug` trait for `Compressed`.
330///
331/// Provides a human-readable debug representation of a `Compressed` object
332/// showing its key properties: checksum, sizes, compression ratio, and digest.
333impl std::fmt::Debug for Compressed {
334    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
335        write!(
336            f,
337            "Compressed(checksum: {}, size: {}/{}, ratio: {:.2}, digest: {})",
338            hex::encode(self.checksum.to_be_bytes()),
339            self.compressed_size(),
340            self.decompressed_size,
341            self.compression_ratio(),
342            self.digest_ref_opt()
343                .map(|d| d.short_description())
344                .unwrap_or_else(|| "None".to_string())
345        )
346    }
347}
348
349/// Implementation of `AsRef<Compressed>` for `Compressed`.
350///
351/// This allows passing a `Compressed` instance to functions that take
352/// `AsRef<Compressed>` parameters.
353impl AsRef<Compressed> for Compressed {
354    fn as_ref(&self) -> &Compressed { self }
355}
356
357/// Implementation of the `CBORTagged` trait for `Compressed`.
358///
359/// Defines the CBOR tag(s) used when serializing a `Compressed` object.
360impl CBORTagged for Compressed {
361    fn cbor_tags() -> Vec<Tag> { tags_for_values(&[tags::TAG_COMPRESSED]) }
362}
363
364/// Conversion from `Compressed` to CBOR for serialization.
365impl From<Compressed> for CBOR {
366    fn from(value: Compressed) -> Self { value.tagged_cbor() }
367}
368
369/// Implementation of CBOR encoding for `Compressed`.
370///
371/// Defines how a `Compressed` object is serialized to untagged CBOR.
372/// The format is:
373/// ```text
374/// [
375///   checksum: uint,
376///   decompressed_size: uint,
377///   compressed_data: bytes,
378///   digest?: Digest  // Optional
379/// ]
380/// ```
381impl CBORTaggedEncodable for Compressed {
382    fn untagged_cbor(&self) -> CBOR {
383        let mut elements = vec![
384            self.checksum.into(),
385            self.decompressed_size.into(),
386            CBOR::to_byte_string(&self.compressed_data),
387        ];
388        if let Some(digest) = self.digest.clone() {
389            elements.push(digest.into());
390        }
391        CBORCase::Array(elements).into()
392    }
393}
394
395/// Conversion from CBOR to `Compressed` for deserialization.
396impl TryFrom<CBOR> for Compressed {
397    type Error = dcbor::Error;
398
399    fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
400        Self::from_tagged_cbor(cbor)
401    }
402}
403
404/// Implementation of CBOR decoding for `Compressed`.
405///
406/// Defines how to create a `Compressed` object from untagged CBOR.
407impl CBORTaggedDecodable for Compressed {
408    fn from_untagged_cbor(cbor: CBOR) -> dcbor::Result<Self> {
409        let elements = cbor.try_into_array()?;
410        if elements.len() < 3 || elements.len() > 4 {
411            return Err("invalid number of elements in compressed".into());
412        }
413        let checksum = elements[0].clone().try_into()?;
414        let decompressed_size = elements[1].clone().try_into()?;
415        let compressed_data = elements[2].clone().try_into_byte_string()?;
416        let digest = if elements.len() == 4 {
417            Some(elements[3].clone().try_into()?)
418        } else {
419            None
420        };
421        Ok(Self::new(
422            checksum,
423            decompressed_size,
424            compressed_data,
425            digest,
426        )?)
427    }
428}
429
430#[cfg(test)]
431mod tests {
432    use crate::Compressed;
433
434    #[test]
435    fn test_1() {
436        let source =
437            b"Lorem ipsum dolor sit amet consectetur adipiscing elit mi nibh ornare proin blandit diam ridiculus, faucibus mus dui eu vehicula nam donec dictumst sed vivamus bibendum aliquet efficitur. Felis imperdiet sodales dictum morbi vivamus augue dis duis aliquet velit ullamcorper porttitor, lobortis dapibus hac purus aliquam natoque iaculis blandit montes nunc pretium.";
438        let compressed = Compressed::from_decompressed_data(source, None);
439        assert_eq!(
440            format!("{:?}", compressed),
441            "Compressed(checksum: 3eeb10a0, size: 217/364, ratio: 0.60, digest: None)"
442        );
443        assert_eq!(compressed.decompress().unwrap(), source);
444    }
445
446    #[test]
447    fn test_2() {
448        let source = b"Lorem ipsum dolor sit amet consectetur adipiscing";
449        let compressed = Compressed::from_decompressed_data(source, None);
450        assert_eq!(
451            format!("{:?}", compressed),
452            "Compressed(checksum: 29db1793, size: 45/49, ratio: 0.92, digest: None)"
453        );
454        assert_eq!(compressed.decompress().unwrap(), source);
455    }
456
457    #[test]
458    fn test_3() {
459        let source = b"Lorem";
460        let compressed = Compressed::from_decompressed_data(source, None);
461        assert_eq!(
462            format!("{:?}", compressed),
463            "Compressed(checksum: 44989b39, size: 5/5, ratio: 1.00, digest: None)"
464        );
465        assert_eq!(compressed.decompress().unwrap(), source);
466    }
467
468    #[test]
469    fn test_4() {
470        let source = b"";
471        let compressed = Compressed::from_decompressed_data(source, None);
472        assert_eq!(
473            format!("{:?}", compressed),
474            "Compressed(checksum: 00000000, size: 0/0, ratio: NaN, digest: None)"
475        );
476        assert_eq!(compressed.decompress().unwrap(), source);
477    }
478}