bc_components/compressed.rs
1use std::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_opt(), Some(digest));
281 /// ```
282 pub fn digest_opt(&self) -> Option<Digest> { self.digest }
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 `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) -> Digest { self.digest.unwrap() }
325}
326
327/// Implementation of the `Debug` trait for `Compressed`.
328///
329/// Provides a human-readable debug representation of a `Compressed` object
330/// showing its key properties: checksum, sizes, compression ratio, and digest.
331impl std::fmt::Debug for Compressed {
332 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
333 write!(
334 f,
335 "Compressed(checksum: {}, size: {}/{}, ratio: {:.2}, digest: {})",
336 hex::encode(self.checksum.to_be_bytes()),
337 self.compressed_size(),
338 self.decompressed_size,
339 self.compression_ratio(),
340 self.digest_opt()
341 .map(|d| d.short_description())
342 .unwrap_or_else(|| "None".to_string())
343 )
344 }
345}
346
347/// Implementation of `AsRef<Compressed>` for `Compressed`.
348///
349/// This allows passing a `Compressed` instance to functions that take
350/// `AsRef<Compressed>` parameters.
351impl AsRef<Compressed> for Compressed {
352 fn as_ref(&self) -> &Compressed { self }
353}
354
355/// Implementation of the `CBORTagged` trait for `Compressed`.
356///
357/// Defines the CBOR tag(s) used when serializing a `Compressed` object.
358impl CBORTagged for Compressed {
359 fn cbor_tags() -> Vec<Tag> { tags_for_values(&[tags::TAG_COMPRESSED]) }
360}
361
362/// Conversion from `Compressed` to CBOR for serialization.
363impl From<Compressed> for CBOR {
364 fn from(value: Compressed) -> Self { value.tagged_cbor() }
365}
366
367/// Implementation of CBOR encoding for `Compressed`.
368///
369/// Defines how a `Compressed` object is serialized to untagged CBOR.
370/// The format is:
371/// ```text
372/// [
373/// checksum: uint,
374/// decompressed_size: uint,
375/// compressed_data: bytes,
376/// digest?: Digest // Optional
377/// ]
378/// ```
379impl CBORTaggedEncodable for Compressed {
380 fn untagged_cbor(&self) -> CBOR {
381 let mut elements = vec![
382 self.checksum.into(),
383 self.decompressed_size.into(),
384 CBOR::to_byte_string(&self.compressed_data),
385 ];
386 if let Some(digest) = self.digest {
387 elements.push(digest.into());
388 }
389 CBORCase::Array(elements).into()
390 }
391}
392
393/// Conversion from CBOR to `Compressed` for deserialization.
394impl TryFrom<CBOR> for Compressed {
395 type Error = dcbor::Error;
396
397 fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
398 Self::from_tagged_cbor(cbor)
399 }
400}
401
402/// Implementation of CBOR decoding for `Compressed`.
403///
404/// Defines how to create a `Compressed` object from untagged CBOR.
405impl CBORTaggedDecodable for Compressed {
406 fn from_untagged_cbor(cbor: CBOR) -> dcbor::Result<Self> {
407 let elements = cbor.try_into_array()?;
408 if elements.len() < 3 || elements.len() > 4 {
409 return Err("invalid number of elements in compressed".into());
410 }
411 let checksum = elements[0].clone().try_into()?;
412 let decompressed_size = elements[1].clone().try_into()?;
413 let compressed_data = elements[2].clone().try_into_byte_string()?;
414 let digest = if elements.len() == 4 {
415 Some(elements[3].clone().try_into()?)
416 } else {
417 None
418 };
419 Ok(Self::new(
420 checksum,
421 decompressed_size,
422 compressed_data,
423 digest,
424 )?)
425 }
426}
427
428#[cfg(test)]
429mod tests {
430 use crate::Compressed;
431
432 #[test]
433 fn test_1() {
434 let source =
435 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.";
436 let compressed = Compressed::from_decompressed_data(source, None);
437 assert_eq!(
438 format!("{:?}", compressed),
439 "Compressed(checksum: 3eeb10a0, size: 217/364, ratio: 0.60, digest: None)"
440 );
441 assert_eq!(compressed.decompress().unwrap(), source);
442 }
443
444 #[test]
445 fn test_2() {
446 let source = b"Lorem ipsum dolor sit amet consectetur adipiscing";
447 let compressed = Compressed::from_decompressed_data(source, None);
448 assert_eq!(
449 format!("{:?}", compressed),
450 "Compressed(checksum: 29db1793, size: 45/49, ratio: 0.92, digest: None)"
451 );
452 assert_eq!(compressed.decompress().unwrap(), source);
453 }
454
455 #[test]
456 fn test_3() {
457 let source = b"Lorem";
458 let compressed = Compressed::from_decompressed_data(source, None);
459 assert_eq!(
460 format!("{:?}", compressed),
461 "Compressed(checksum: 44989b39, size: 5/5, ratio: 1.00, digest: None)"
462 );
463 assert_eq!(compressed.decompress().unwrap(), source);
464 }
465
466 #[test]
467 fn test_4() {
468 let source = b"";
469 let compressed = Compressed::from_decompressed_data(source, None);
470 assert_eq!(
471 format!("{:?}", compressed),
472 "Compressed(checksum: 00000000, size: 0/0, ratio: NaN, digest: None)"
473 );
474 assert_eq!(compressed.decompress().unwrap(), source);
475 }
476}