Compressed

Struct Compressed 

Source
pub struct Compressed { /* private fields */ }
Expand description

A compressed binary object with integrity verification.

Compressed provides a way to efficiently store and transmit binary data using the DEFLATE compression algorithm. It includes built-in integrity verification through a CRC32 checksum and optional cryptographic digest.

The compression is implemented using the raw DEFLATE format as described in IETF RFC 1951 with the following configuration equivalent to:

deflateInit2(zstream, 5, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY)

Features:

  • Automatic compression with configurable compression level
  • Integrity verification via CRC32 checksum
  • Optional cryptographic digest for content identification
  • Smart behavior for small data (stores uncompressed if compression would increase size)
  • CBOR serialization/deserialization support

Implementations§

Source§

impl Compressed

Source

pub fn new( checksum: u32, uncompressed_size: usize, compressed_data: Vec<u8>, digest: Option<Digest>, ) -> Result<Self>

Creates a new Compressed object with the specified parameters.

This is a low-level constructor that allows direct creation of a Compressed object without performing compression. It’s primarily intended for deserialization or when working with pre-compressed data.

§Parameters
  • checksum - CRC32 checksum of the uncompressed data
  • uncompressed_size - Size of the original uncompressed data in bytes
  • compressed_data - The compressed data bytes
  • digest - Optional cryptographic digest of the content
§Returns

A Result containing the new Compressed object if successful, or an error if the parameters are invalid.

§Errors

Returns an error if the compressed data is larger than the uncompressed size, which would indicate a logical inconsistency.

§Example
use bc_components::Compressed;
use bc_crypto::hash::crc32;

let data = b"hello world";
let checksum = crc32(data);
let uncompressed_size = data.len();

// In a real scenario, this would be actually compressed data
let compressed_data = data.to_vec();

let compressed =
    Compressed::new(checksum, uncompressed_size, compressed_data, None)
        .unwrap();
Source

pub fn from_uncompressed_data( uncompressed_data: impl AsRef<[u8]>, digest: Option<Digest>, ) -> Self

Creates a new Compressed object by compressing the provided data.

This is the primary method for creating compressed data. It automatically handles compression using the DEFLATE algorithm with a compression level of 6.

If the compressed data would be larger than the original data (which can happen with small or already compressed inputs), the original data is stored instead.

§Parameters
  • uncompressed_data - The original data to compress
  • digest - Optional cryptographic digest of the content
§Returns

A new Compressed object containing the compressed (or original) data.

§Example
use bc_components::Compressed;

// Compress a string
let data = "This is a longer string that should compress well with repeated patterns. \
           This is a longer string that should compress well with repeated patterns.";
let compressed = Compressed::from_uncompressed_data(data.as_bytes(), None);

// The compressed size should be smaller than the original
assert!(compressed.compressed_size() < data.len());

// We can recover the original data
let uncompressed = compressed.uncompress().unwrap();
assert_eq!(uncompressed, data.as_bytes());
Source

pub fn uncompress(&self) -> Result<Vec<u8>>

Decompresses and returns the original uncompressed data.

This method performs the reverse of the compression process, restoring the original data. It also verifies the integrity of the data using the stored checksum.

§Returns

A Result containing the uncompressed data if successful, or an error if decompression fails or the checksum doesn’t match.

§Errors

Returns an error if:

  • The compressed data is corrupt and cannot be decompressed
  • The checksum of the decompressed data doesn’t match the stored checksum
§Example
use bc_components::Compressed;

// Original data
let original = b"This is some example data to compress";

// Compress it
let compressed = Compressed::from_uncompressed_data(original, None);

// Uncompress to get the original data back
let uncompressed = compressed.uncompress().unwrap();
assert_eq!(uncompressed, original);
Source

pub fn compressed_size(&self) -> usize

Returns the size of the compressed data in bytes.

§Returns

The size of the compressed data in bytes.

§Example
use bc_components::Compressed;

let data = b"Hello world!";
let compressed = Compressed::from_uncompressed_data(data, None);

// For small inputs like this, compression might not be effective
// so the compressed_size might equal the original size
println!("Compressed size: {}", compressed.compressed_size());
Source

pub fn compression_ratio(&self) -> f64

Returns the compression ratio of the data.

The compression ratio is calculated as (compressed size) / (uncompressed size), so lower values indicate better compression.

§Returns

A floating-point value representing the compression ratio.

  • Values less than 1.0 indicate effective compression
  • Values equal to 1.0 indicate no compression was applied
  • Values of NaN can occur if the uncompressed size is zero
§Example
use bc_components::Compressed;

// A string with a lot of repetition should compress well
let data = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
let compressed = Compressed::from_uncompressed_data(data.as_bytes(), None);

// Should have a good compression ratio (much less than 1.0)
let ratio = compressed.compression_ratio();
assert!(ratio < 0.5);
Source

pub fn digest_ref_opt(&self) -> Option<&Digest>

Returns a reference to the digest of the compressed data, if available.

§Returns

An optional reference to the Digest associated with this compressed data.

§Example
use bc_components::{Compressed, Digest};

let data = b"Hello world!";
let digest = Digest::from_image(data);
let compressed =
    Compressed::from_uncompressed_data(data, Some(digest.clone()));

// We can retrieve the digest we associated with the compressed data
assert_eq!(compressed.digest_ref_opt(), Some(&digest));
Source

pub fn has_digest(&self) -> bool

Returns whether this compressed data has an associated digest.

§Returns

true if this compressed data has a digest, false otherwise.

§Example
use bc_components::{Compressed, Digest};

// Create compressed data without a digest
let compressed1 = Compressed::from_uncompressed_data(b"Hello", None);
assert!(!compressed1.has_digest());

// Create compressed data with a digest
let digest = Digest::from_image(b"Hello");
let compressed2 =
    Compressed::from_uncompressed_data(b"Hello", Some(digest));
assert!(compressed2.has_digest());

Trait Implementations§

Source§

impl AsRef<Compressed> for Compressed

Implementation of AsRef<Compressed> for Compressed.

This allows passing a Compressed instance to functions that take AsRef<Compressed> parameters.

Source§

fn as_ref(&self) -> &Compressed

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl CBORTagged for Compressed

Implementation of the CBORTagged trait for Compressed.

Defines the CBOR tag(s) used when serializing a Compressed object.

Source§

fn cbor_tags() -> Vec<Tag>

Returns the CBOR tags associated with this type. Read more
Source§

impl CBORTaggedDecodable for Compressed

Implementation of CBOR decoding for Compressed.

Defines how to create a Compressed object from untagged CBOR.

Source§

fn from_untagged_cbor(cbor: CBOR) -> Result<Self>

Creates an instance of this type by decoding it from untagged CBOR. Read more
Source§

fn from_tagged_cbor(cbor: CBOR) -> Result<Self, Error>
where Self: Sized,

Creates an instance of this type by decoding it from tagged CBOR. Read more
Source§

fn from_tagged_cbor_data(data: impl AsRef<[u8]>) -> Result<Self, Error>
where Self: Sized,

Creates an instance of this type by decoding it from binary encoded tagged CBOR. Read more
Source§

fn from_untagged_cbor_data(data: impl AsRef<[u8]>) -> Result<Self, Error>
where Self: Sized,

Creates an instance of this type by decoding it from binary encoded untagged CBOR. Read more
Source§

impl CBORTaggedEncodable for Compressed

Implementation of CBOR encoding for Compressed.

Defines how a Compressed object is serialized to untagged CBOR. The format is:

[
  checksum: uint,
  uncompressed_size: uint,
  compressed_data: bytes,
  digest?: Digest  // Optional
]
Source§

fn untagged_cbor(&self) -> CBOR

Returns the untagged CBOR encoding of this instance. Read more
Source§

fn tagged_cbor(&self) -> CBOR

Returns the tagged CBOR encoding of this instance. Read more
Source§

fn tagged_cbor_data(&self) -> Vec<u8>

Returns the tagged value in CBOR binary representation. Read more
Source§

impl Clone for Compressed

Source§

fn clone(&self) -> Compressed

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Compressed

Implementation of the Debug trait for Compressed.

Provides a human-readable debug representation of a Compressed object showing its key properties: checksum, sizes, compression ratio, and digest.

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl DigestProvider for Compressed

Implementation of the DigestProvider trait for Compressed.

Allows Compressed objects with digests to be used with APIs that accept DigestProvider implementations.

Source§

fn digest(&self) -> Cow<'_, Digest>

Returns the cryptographic digest associated with this compressed data.

§Returns

A Cow<'_, Digest> containing the digest.

§Panics

Panics if there is no digest associated with this compressed data. Use has_digest() or digest_ref_opt() to check before calling this method.

Source§

impl From<Compressed> for CBOR

Conversion from Compressed to CBOR for serialization.

Source§

fn from(value: Compressed) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for Compressed

Source§

fn eq(&self, other: &Compressed) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl TryFrom<CBOR> for Compressed

Conversion from CBOR to Compressed for deserialization.

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(cbor: CBOR) -> Result<Self>

Performs the conversion.
Source§

impl Eq for Compressed

Source§

impl StructuralPartialEq for Compressed

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CBORDecodable for T
where T: TryFrom<CBOR, Error = Error>,

Source§

fn try_from_cbor(cbor: &CBOR) -> Result<Self, Error>

Source§

impl<T> CBOREncodable for T
where T: Into<CBOR> + Clone,

Source§

fn to_cbor(&self) -> CBOR

Converts this value to a CBOR object. Read more
Source§

fn to_cbor_data(&self) -> Vec<u8>

Converts this value directly to binary CBOR data. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> URDecodable for T

Source§

fn from_ur(ur: impl AsRef<UR>) -> Result<Self, Error>
where Self: Sized,

Source§

fn from_ur_string(ur_string: impl Into<String>) -> Result<Self, Error>
where Self: Sized,

Source§

impl<T> UREncodable for T

Source§

fn ur(&self) -> UR

Returns the UR representation of the object.
Source§

fn ur_string(&self) -> String

Returns the UR string representation of the object.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> CBORCodable for T

Source§

impl<T> CBORTaggedCodable for T

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> URCodable for T