bc_envelope/base/
envelope_decodable.rs

1use bc_components::{
2    ARID, Digest, PrivateKeyBase, PrivateKeys, PublicKeys, Reference,
3    SSKRShare, Salt, SealedMessage, Signature, URI, UUID, XID,
4};
5use dcbor::prelude::*;
6
7use crate::{Envelope, Error, Result};
8
9#[macro_export]
10macro_rules! impl_envelope_decodable {
11    ($type:ty) => {
12        impl TryFrom<Envelope> for $type {
13            type Error = Error;
14
15            fn try_from(envelope: Envelope) -> Result<Self> {
16                let cbor = envelope.try_leaf()?;
17                Ok(cbor.try_into()?)
18            }
19        }
20    };
21}
22
23impl_envelope_decodable!(String);
24
25// Numeric types
26impl_envelope_decodable!(u8);
27impl_envelope_decodable!(u16);
28impl_envelope_decodable!(u32);
29impl_envelope_decodable!(u64);
30impl_envelope_decodable!(usize);
31impl_envelope_decodable!(i8);
32impl_envelope_decodable!(i16);
33impl_envelope_decodable!(i32);
34impl_envelope_decodable!(i64);
35
36// Boolean type
37impl_envelope_decodable!(bool);
38
39// CBOR types
40impl_envelope_decodable!(ByteString);
41impl_envelope_decodable!(Date);
42
43// Floating point types
44impl_envelope_decodable!(f64);
45impl_envelope_decodable!(f32);
46
47// Cryptographic types
48impl_envelope_decodable!(PublicKeys);
49impl_envelope_decodable!(PrivateKeys);
50impl_envelope_decodable!(PrivateKeyBase);
51impl_envelope_decodable!(SealedMessage);
52impl_envelope_decodable!(Signature);
53impl_envelope_decodable!(SSKRShare);
54impl_envelope_decodable!(Digest);
55impl_envelope_decodable!(Salt);
56
57// Identifier types
58impl_envelope_decodable!(ARID);
59impl_envelope_decodable!(URI);
60impl_envelope_decodable!(UUID);
61impl_envelope_decodable!(XID);
62impl_envelope_decodable!(Reference);
63
64/// Static methods for creating envelopes from CBOR data.
65impl Envelope {
66    /// Creates an envelope from a CBOR value.
67    ///
68    /// # Parameters
69    ///
70    /// * `cbor` - The CBOR value to convert into an envelope
71    ///
72    /// # Returns
73    ///
74    /// A new envelope created from the CBOR data.
75    ///
76    /// # Errors
77    ///
78    /// Returns an error if the CBOR does not represent a valid envelope
79    /// structure.
80    pub fn try_from_cbor(cbor: CBOR) -> dcbor::Result<Self> { cbor.try_into() }
81
82    /// Creates an envelope from raw CBOR binary data.
83    ///
84    /// # Parameters
85    ///
86    /// * `data` - The raw CBOR binary data to convert into an envelope
87    ///
88    /// # Returns
89    ///
90    /// A new envelope created from the CBOR data.
91    ///
92    /// # Errors
93    ///
94    /// Returns an error if the data is not valid CBOR or does not represent
95    /// a valid envelope structure.
96    pub fn try_from_cbor_data(data: Vec<u8>) -> dcbor::Result<Self> {
97        let cbor = CBOR::try_from_data(data)?;
98        Self::try_from_cbor(cbor)
99    }
100}