data_anchor_utils/
lib.rs

1#[cfg(feature = "compression")]
2pub mod compression;
3pub mod encoding;
4
5#[cfg(feature = "compression")]
6mod wrapper {
7    /// Utility functions for encoding and compression in Data Anchor.
8    #[derive(Debug, thiserror::Error)]
9    pub enum DataAnchorUtilsError {
10        #[error(transparent)]
11        CompressionError(#[from] crate::compression::DataAnchorCompressionError),
12        #[error(transparent)]
13        EncodingError(#[from] crate::encoding::DataAnchorEncodingError),
14    }
15
16    /// Result type for Data Anchor utilities, encapsulating potential errors.
17    pub type DataAnchorUtilsResult<T = ()> = Result<T, DataAnchorUtilsError>;
18
19    /// Utility functions for encoding and compression in Data Anchor.
20    pub fn encode_and_compress<T>(
21        encoding: &EncodingType,
22        compression: &CompressionType,
23        data: &T,
24    ) -> DataAnchorUtilsResult<Vec<u8>>
25    where
26        T: crate::encoding::Encodable,
27    {
28        let encoded_data = encoding.encode(data)?;
29        Ok(compression.compress(&encoded_data)?)
30    }
31
32    /// Utility function to decompress and decode data in Data Anchor.
33    pub fn decompress_and_decode<T>(data: &[u8]) -> DataAnchorUtilsResult<T>
34    where
35        T: crate::encoding::Decodable,
36    {
37        let decompressed_data = CompressionType::default().decompress(data)?;
38        Ok(EncodingType::default().decode(&decompressed_data)?)
39    }
40
41    #[cfg(feature = "async")]
42    mod _async {
43        use super::DataAnchorUtilsResult;
44        use crate::{
45            compression::{CompressionType, DataAnchorCompressionAsync},
46            encoding::{DataAnchorEncoding, EncodingType},
47        };
48
49        /// Utility functions for encoding and compression in Data Anchor.
50        pub async fn encode_and_compress_async<T>(
51            encoding: &EncodingType,
52            compression: &CompressionType,
53            data: &T,
54        ) -> DataAnchorUtilsResult<Vec<u8>>
55        where
56            T: crate::encoding::Encodable,
57        {
58            let encoded_data = encoding.encode(data)?;
59            Ok(compression.compress_async(&encoded_data).await?)
60        }
61
62        /// Utility function to decompress and decode data in Data Anchor.
63        pub async fn decompress_and_decode_async<T>(data: &[u8]) -> DataAnchorUtilsResult<T>
64        where
65            T: crate::encoding::Decodable,
66        {
67            let decompressed_data = CompressionType::default().decompress_async(data).await?;
68            Ok(EncodingType::default().decode(&decompressed_data)?)
69        }
70    }
71
72    #[cfg(feature = "async")]
73    pub use _async::*;
74
75    use crate::{
76        compression::{CompressionType, DataAnchorCompression},
77        encoding::{DataAnchorEncoding, EncodingType},
78    };
79}
80
81#[cfg(feature = "compression")]
82pub use wrapper::*;