bc_components/
reference.rs

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use std::borrow::Cow;
use bc_ur::prelude::*;
use crate::{ digest_provider::DigestProvider, tags, Digest };
use anyhow::{ bail, Result, Error };

/// Implementers of this trait provide a globally unique reference to themselves.
pub trait ReferenceProvider {
    fn reference(&self) -> Reference;

    /// The data as a hexadecimal string.
    fn ref_hex(&self) -> String {
        self.reference().ref_hex()
    }

    /// The first four bytes of the reference
    fn ref_data_short(&self) -> [u8; 4] {
        self.reference().ref_data_short()
    }

    /// The first four bytes of the reference as a hexadecimal string.
    fn ref_hex_short(&self) -> String {
        self.reference().ref_hex_short()
    }

    /// The first four bytes of the reference as upper-case ByteWords.
    fn ref_bytewords(&self, prefix: Option<&str>) -> String {
        self.reference().bytewords_identifier(prefix)
    }

    /// The first four bytes of the reference as Bytemoji.
    fn ref_bytemoji(&self, prefix: Option<&str>) -> String {
        self.reference().bytemoji_identifier(prefix)
    }
}

/// A globally unique reference to a globally unique object
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Reference([u8; Self::REFERENCE_SIZE]);

impl Reference {
    pub const REFERENCE_SIZE: usize = 32;

    /// Create a new reference from data.
    pub fn from_data(data: [u8; Self::REFERENCE_SIZE]) -> Self {
        Self(data)
    }

    /// Create a new reference from data.
    ///
    /// Returns `None` if the data is not the correct length.
    pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
        let data = data.as_ref();
        if data.len() != Self::REFERENCE_SIZE {
            bail!("Invalid reference size");
        }
        let mut arr = [0u8; Self::REFERENCE_SIZE];
        arr.copy_from_slice(data.as_ref());
        Ok(Self::from_data(arr))
    }

    /// Create a new reference from the given digest.
    pub fn from_digest(digest: Digest) -> Self {
        Self::from_data(*digest.data())
    }

    /// Get the data of the reference.
    pub fn data(&self) -> &[u8; Self::REFERENCE_SIZE] {
        self.into()
    }

    /// Create a new reference from the given hexadecimal string.
    ///
    /// # Panics
    /// Panics if the string is not exactly 64 hexadecimal digits.
    pub fn from_hex(hex: impl AsRef<str>) -> Self {
        Self::from_data_ref(hex::decode(hex.as_ref()).unwrap()).unwrap()
    }

    /// The data as a hexadecimal string.
    pub fn ref_hex(&self) -> String {
        hex::encode(self.0)
    }

    /// The first four bytes of the reference
    pub fn ref_data_short(&self) -> [u8; 4] {
        self.0[0..4].try_into().unwrap()
    }

    /// The first four bytes of the reference as a hexadecimal string.
    pub fn ref_hex_short(&self) -> String {
        hex::encode(self.ref_data_short())
    }

    /// The first four bytes of the XID as upper-case ByteWords.
    pub fn bytewords_identifier(&self, prefix: Option<&str>) -> String {
        let s = bytewords::identifier(&self.ref_data_short()).to_uppercase();
        if let Some(prefix) = prefix {
            format!("{prefix} {s}")
        } else {
            s
        }
    }

    /// The first four bytes of the XID as Bytemoji.
    pub fn bytemoji_identifier(&self, prefix: Option<&str>) -> String {
        let s = bytewords::bytemoji_identifier(&self.0[..4].try_into().unwrap()).to_uppercase();
        if let Some(prefix) = prefix {
            format!("{prefix} {s}")
        } else {
            s
        }
    }
}

/// Implement the `ReferenceProvider` trait for `Reference`.
///
/// Yes, this creates a Reference to a Reference.
impl ReferenceProvider for Reference {
    fn reference(&self) -> Reference {
        Reference::from_digest(self.digest().into_owned())
    }
}

impl<'a> From<&'a Reference> for &'a [u8; Reference::REFERENCE_SIZE] {
    fn from(value: &'a Reference) -> Self {
        &value.0
    }
}

impl<'a> From<&'a Reference> for &'a [u8] {
    fn from(value: &'a Reference) -> Self {
        &value.0
    }
}

impl AsRef<[u8]> for Reference {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl AsRef<Reference> for Reference {
    fn as_ref(&self) -> &Reference {
        self
    }
}

impl std::cmp::PartialOrd for Reference {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.0.cmp(&other.0))
    }
}

impl std::cmp::Ord for Reference {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.cmp(&other.0)
    }
}

impl DigestProvider for Reference {
    fn digest(&self) -> Cow<'_, Digest> {
        Cow::Owned(Digest::from_image(self.tagged_cbor().to_cbor_data()))
    }
}

impl std::fmt::Debug for Reference {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Reference({})", self.ref_hex())
    }
}

impl std::fmt::Display for Reference {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Reference({})", self.ref_hex_short())
    }
}

impl CBORTagged for Reference {
    fn cbor_tags() -> Vec<Tag> {
        tags_for_values(&[tags::TAG_REFERENCE])
    }
}

impl From<Reference> for CBOR {
    fn from(value: Reference) -> Self {
        value.tagged_cbor()
    }
}

impl CBORTaggedEncodable for Reference {
    fn untagged_cbor(&self) -> CBOR {
        CBOR::to_byte_string(self.0)
    }
}

impl TryFrom<CBOR> for Reference {
    type Error = Error;

    fn try_from(cbor: CBOR) -> Result<Self, Self::Error> {
        Self::from_tagged_cbor(cbor)
    }
}

impl CBORTaggedDecodable for Reference {
    fn from_untagged_cbor(cbor: CBOR) -> Result<Self> {
        let data = CBOR::try_into_byte_string(cbor)?;
        Self::from_data_ref(data)
    }
}

// Convert from an instance reference to an instance.
impl From<&Reference> for Reference {
    fn from(digest: &Reference) -> Self {
        digest.clone()
    }
}

// Convert from a byte vector to an instance.
impl From<Reference> for Vec<u8> {
    fn from(digest: Reference) -> Self {
        digest.0.to_vec()
    }
}

// Convert a reference to an instance to a byte vector.
impl From<&Reference> for Vec<u8> {
    fn from(digest: &Reference) -> Self {
        digest.0.to_vec()
    }
}