bc_envelope/base/
envelope_decodable.rs

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