1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use bc_components::{Digest, PrivateKeyBase, PublicKeyBase, SSKRShare, Salt, SealedMessage, Signature, ARID, URI, UUID};
#[cfg(feature = "encrypt")]
use bc_components::EncryptedMessage;
#[cfg(feature = "compress")]
use bc_components::Compressed;
use bytes::Bytes;
#[cfg(any(feature = "encrypt", feature = "compress"))]
use anyhow::{Error, Result};
use dcbor::CBOR;

use crate::{Assertion, Envelope};

pub trait EnvelopeEncodable {
    fn into_envelope(self) -> Envelope;
    fn to_envelope(&self) -> Envelope where Self: Clone {
        self.clone().into_envelope()
    }
}

impl<T> EnvelopeEncodable for T where T: Into<Envelope> + Clone {
    fn into_envelope(self) -> Envelope {
        self.into()
    }
}

impl EnvelopeEncodable for Assertion {
    fn into_envelope(self) -> Envelope {
        Envelope::new_with_assertion(self)
    }
}

#[cfg(feature = "encrypt")]
impl TryFrom<EncryptedMessage> for Envelope {
    type Error = Error;

    fn try_from(value: EncryptedMessage) -> Result<Self> {
        Envelope::new_with_encrypted(value)
    }
}

#[cfg(feature = "compress")]
impl TryFrom<Compressed> for Envelope {
    type Error = Error;

    fn try_from(compressed: Compressed) -> Result<Self> {
        Envelope::new_with_compressed(compressed)
    }
}

impl EnvelopeEncodable for CBOR {
    fn into_envelope(self) -> Envelope {
        Envelope::new_leaf(self)
    }
}

impl EnvelopeEncodable for String {
    fn into_envelope(self) -> Envelope {
        Envelope::new_leaf(self)
    }
}

impl EnvelopeEncodable for &str {
    fn into_envelope(self) -> Envelope {
        Envelope::new_leaf(self)
    }
}

macro_rules! impl_envelope_encodable {
    ($type:ty) => {
        impl EnvelopeEncodable for $type {
            fn into_envelope(self) -> Envelope {
                Envelope::new_leaf(self)
            }
        }
    }
}

impl_envelope_encodable!(u8);
impl_envelope_encodable!(u16);
impl_envelope_encodable!(u32);
impl_envelope_encodable!(u64);
impl_envelope_encodable!(usize);
impl_envelope_encodable!(i8);
impl_envelope_encodable!(i16);
impl_envelope_encodable!(i32);
impl_envelope_encodable!(i64);
impl_envelope_encodable!(bool);
impl_envelope_encodable!(f64);
impl_envelope_encodable!(f32);

impl_envelope_encodable!(Bytes);

impl_envelope_encodable!(dcbor::Date);
impl_envelope_encodable!(PublicKeyBase);
impl_envelope_encodable!(PrivateKeyBase);
impl_envelope_encodable!(SealedMessage);
impl_envelope_encodable!(Signature);
impl_envelope_encodable!(SSKRShare);
impl_envelope_encodable!(Digest);
impl_envelope_encodable!(ARID);
impl_envelope_encodable!(Salt);
impl_envelope_encodable!(URI);
impl_envelope_encodable!(UUID);