dcbor/
cbor.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import_stdlib!();

use anyhow::{bail, Result};
use unicode_normalization::UnicodeNormalization;

use crate::{decode::decode_cbor, error::CBORError, tag::Tag, varint::{EncodeVarInt, MajorType}, Map, Simple, ByteString};

use super::string_util::flanked;

#[cfg(feature = "multithreaded")]
use sync::Arc as RefCounted;

#[cfg(not(feature = "multithreaded"))]
use rc::Rc as RefCounted;

/// A symbolic representation of CBOR data.
#[derive(Clone)]
pub struct CBOR(RefCounted<CBORCase>);

impl CBOR {
    pub fn as_case(&self) -> &CBORCase {
        &self.0
    }

    pub fn into_case(self) -> CBORCase {
        match RefCounted::try_unwrap(self.0) {
            Ok(b) => b,
            Err(ref_counted) => (*ref_counted).clone(),
        }
    }
}

impl From<CBORCase> for CBOR {
    fn from(case: CBORCase) -> Self {
        Self(RefCounted::new(case))
    }
}

#[derive(Debug, Clone)]
pub enum CBORCase {
    /// Unsigned integer (major type 0).
    Unsigned(u64),
    /// Negative integer (major type 1).
    ///
    /// Actual value is -1 - n
    Negative(u64),
    /// Byte string (major type 2).
    ByteString(ByteString),
    /// UTF-8 string (major type 3).
    Text(String),
    /// Array (major type 4).
    Array(Vec<CBOR>),
    /// Map (major type 5).
    Map(Map),
    /// Tagged value (major type 6).
    Tagged(Tag, CBOR),
    /// Simple value (major type 7).
    Simple(Simple)
}

/// Affordances for decoding CBOR from binary representation.
impl CBOR {
    /// Decodes the given date into CBOR symbolic representation.
    pub fn try_from_data(data: impl AsRef<[u8]>) -> Result<CBOR> {
        decode_cbor(data)
    }

    /// Decodes the given data into CBOR symbolic representation given as a hexadecimal string.
    ///
    /// Panics if the string is not well-formed hexadecimal with no spaces or
    /// other characters.
    pub fn try_from_hex(hex: &str) -> Result<CBOR> {
        let data = hex::decode(hex).unwrap();
        Self::try_from_data(data)
    }

    pub fn to_cbor_data(&self) -> Vec<u8> {
        match self.as_case() {
            CBORCase::Unsigned(x) => x.encode_varint(MajorType::Unsigned),
            CBORCase::Negative(x) => x.encode_varint(MajorType::Negative),
            CBORCase::ByteString(x) => {
                let mut buf = x.len().encode_varint(MajorType::ByteString);
                buf.extend(x);
                buf
            },
            CBORCase::Text(x) => {
                let nfc = x.nfc().collect::<String>();
                let mut buf = nfc.len().encode_varint(MajorType::Text);
                buf.extend(nfc.as_bytes());
                buf
            },
            CBORCase::Array(x) => {
                let mut buf = x.len().encode_varint(MajorType::Array);
                for item in x {
                    buf.extend(item.to_cbor_data());
                }
                buf
            },
            CBORCase::Map(x) => x.cbor_data(),
            CBORCase::Tagged(tag, item) => {
                let mut buf = tag.value().encode_varint(MajorType::Tagged);
                buf.extend(item.to_cbor_data());
                buf
            },
            CBORCase::Simple(x) => x.cbor_data(),
        }
    }
}

impl CBOR {
    /// Create a new CBOR value representing a byte string.
    pub fn to_byte_string(data: impl AsRef<[u8]>) -> CBOR {
        CBORCase::ByteString(data.as_ref().into()).into()
    }

    /// Create a new CBOR value representing a byte string given as a hexadecimal string.
    ///
    /// Panics if the string is not well-formed hexadecimal.
    pub fn to_byte_string_from_hex(hex: impl AsRef<str>) -> CBOR {
        Self::to_byte_string(hex::decode(hex.as_ref()).unwrap())
    }

    /// Create a new CBOR value representing a tagged value.
    pub fn to_tagged_value(tag: impl Into<Tag>, item: impl Into<CBOR>) -> CBOR {
        CBORCase::Tagged(tag.into(), item.into()).into()
    }
}

impl CBOR {
    /// Extract the CBOR value as a byte string.
    ///
    /// Returns `Ok` if the value is a byte string, `Err` otherwise.
    pub fn try_into_byte_string(self) -> Result<Vec<u8>> {
        match self.into_case() {
            CBORCase::ByteString(b) => Ok(b.into()),
            _ => bail!(CBORError::WrongType)
        }
    }

    pub fn into_byte_string(self) -> Option<Vec<u8>> {
        self.try_into_byte_string().ok()
    }

    /// Extract the CBOR value as a text string.
    ///
    /// Returns `Ok` if the value is a text string, `Err` otherwise.
    pub fn try_into_text(self) -> Result<String> {
        match self.into_case() {
            CBORCase::Text(t) => Ok(t),
            _ => bail!(CBORError::WrongType)
        }
    }

    /// Extract the CBOR value as an array.
    ///
    /// Returns `Ok` if the value is an array, `Err` otherwise.
    pub fn try_into_array(self) -> Result<Vec<CBOR>> {
        match self.into_case() {
            CBORCase::Array(a) => Ok(a),
            _ => bail!(CBORError::WrongType)
        }
    }

    /// Extract the CBOR value as a map.
    ///
    /// Returns `Ok` if the value is a map, `Err` otherwise.
    pub fn try_into_map(self) -> Result<Map> {
        match self.into_case() {
            CBORCase::Map(m) => Ok(m),
            _ => bail!(CBORError::WrongType)
        }
    }

    /// Extract the CBOR value as a tagged value.
    ///
    /// Returns `Ok` if the value is a tagged value, `Err` otherwise.
    pub fn try_into_tagged_value(self) -> Result<(Tag, CBOR)> {
        match self.into_case() {
            CBORCase::Tagged(tag, value) => Ok((tag, value)),
            _ => bail!(CBORError::WrongType)
        }
    }

    /// Extract the CBOR value as an expected tagged value.
    ///
    /// Returns `Ok` if the value is a tagged value with the expected tag, `Err`
    /// otherwise.
    pub fn try_into_expected_tagged_value(self, expected_tag: impl Into<Tag>) -> Result<CBOR> {
        let (tag, value) = self.try_into_tagged_value()?;
        let expected_tag = expected_tag.into();
        if tag == expected_tag {
            Ok(value)
        } else {
            bail!(CBORError::WrongTag(expected_tag, tag))
        }
    }

    /// Extract the CBOR value as a simple value.
    ///
    /// Returns `Ok` if the value is a simple value, `Err` otherwise.
    pub fn try_into_simple_value(self) -> Result<Simple> {
        match self.into_case() {
            CBORCase::Simple(s) => Ok(s),
            _ => bail!(CBORError::WrongType)
        }
    }
}

/// Associated constants for common CBOR simple values.
impl CBOR {
    /// The CBOR simple value representing `false`.
    pub fn r#false() -> Self {
        CBORCase::Simple(Simple::False).into()
    }

    /// The CBOR simple value representing `true`.
    pub fn r#true() -> Self {
        CBORCase::Simple(Simple::True).into()
    }

    /// The CBOR simple value representing `null` (`None`).
    pub fn null() -> Self {
        CBORCase::Simple(Simple::Null).into()
    }
}

impl PartialEq for CBOR {
    fn eq(&self, other: &Self) -> bool {
        match (self.as_case(), other.as_case()) {
            (CBORCase::Unsigned(l0), CBORCase::Unsigned(r0)) => l0 == r0,
            (CBORCase::Negative(l0), CBORCase::Negative(r0)) => l0 == r0,
            (CBORCase::ByteString(l0), CBORCase::ByteString(r0)) => l0 == r0,
            (CBORCase::Text(l0), CBORCase::Text(r0)) => l0 == r0,
            (CBORCase::Array(l0), CBORCase::Array(r0)) => l0 == r0,
            (CBORCase::Map(l0), CBORCase::Map(r0)) => l0 == r0,
            (CBORCase::Tagged(l0, l1), CBORCase::Tagged(r0, r1)) => l0 == r0 && l1 == r1,
            (CBORCase::Simple(l0), CBORCase::Simple(r0)) => l0 == r0,
            _ => false,
        }
    }
}

fn format_string(s: &str) -> String {
    let mut result = "".to_string();
    for c in s.chars() {
        if c == '"' {
            result.push_str(r#"\""#);
        } else {
            result.push(c);
        }
    }
    flanked(&result, r#"""#, r#"""#)
}

fn format_array(a: &[CBOR]) -> String {
    let s: Vec<String> = a.iter().map(|x| format!("{}", x)).collect();
    flanked(&s.join(", "), "[", "]")
}

fn format_map(m: &Map) -> String {
    let s: Vec<String> = m.iter().map(|x| format!("{}: {}", x.0, x.1)).collect();
    flanked(&s.join(", "), "{", "}")
}

impl fmt::Debug for CBOR {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.as_case() {
            CBORCase::Unsigned(x) => f.debug_tuple("unsigned").field(x).finish(),
            CBORCase::Negative(x) => f.debug_tuple("negative").field(&(-1 - (*x as i128))).finish(),
            CBORCase::ByteString(x) => f.write_fmt(format_args!("bytes({})", hex::encode(x))),
            CBORCase::Text(x) => f.debug_tuple("text").field(x).finish(),
            CBORCase::Array(x) => f.debug_tuple("array").field(x).finish(),
            CBORCase::Map(x) => f.debug_tuple("map").field(x).finish(),
            CBORCase::Tagged(tag, item) => f.write_fmt(format_args!("tagged({}, {:?})", tag, item)),
            CBORCase::Simple(x) => f.write_fmt(format_args!("simple({})", x.name())),
        }
    }
}

impl fmt::Display for CBOR {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self.as_case() {
            CBORCase::Unsigned(x) => format!("{}", x),
            CBORCase::Negative(x) => format!("{}", -1 - (*x as i128)),
            CBORCase::ByteString(x) => format!("h'{}'", hex::encode(x)),
            CBORCase::Text(x) => format_string(x),
            CBORCase::Array(x) => format_array(x),
            CBORCase::Map(x) => format_map(x),
            CBORCase::Tagged(tag, item) => format!("{}({})", tag, item),
            CBORCase::Simple(x) => format!("{}", x),
        };
        f.write_str(&s)
    }
}