ciborium/
tag.rs

1//! Contains helper types for dealing with CBOR tags
2
3use serde::{de, de::Error as _, forward_to_deserialize_any, ser, Deserialize, Serialize};
4
5#[derive(Deserialize, Serialize)]
6#[serde(rename = "@@TAG@@")]
7enum Internal<T> {
8    #[serde(rename = "@@UNTAGGED@@")]
9    Untagged(T),
10
11    #[serde(rename = "@@TAGGED@@")]
12    Tagged(u64, T),
13}
14
15/// An optional CBOR tag and its data item
16///
17/// No semantic evaluation of the tag is made.
18#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub struct Captured<V>(pub Option<u64>, pub V);
20
21impl<'de, V: Deserialize<'de>> Deserialize<'de> for Captured<V> {
22    #[inline]
23    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
24        match Internal::deserialize(deserializer)? {
25            Internal::Tagged(t, v) => Ok(Captured(Some(t), v)),
26            Internal::Untagged(v) => Ok(Captured(None, v)),
27        }
28    }
29}
30
31impl<V: Serialize> Serialize for Captured<V> {
32    #[inline]
33    fn serialize<S: ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
34        match self.0 {
35            Some(tag) => Internal::Tagged(tag, &self.1).serialize(serializer),
36            None => Internal::Untagged(&self.1).serialize(serializer),
37        }
38    }
39}
40
41/// A required CBOR tag
42///
43/// This data type indicates that the specified tag, and **only** that tag,
44/// is required during deserialization. If the tag is missing, deserialization
45/// will fail. The tag will always be emitted during serialization.
46#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
47pub struct Required<V, const TAG: u64>(pub V);
48
49impl<'de, V: Deserialize<'de>, const TAG: u64> Deserialize<'de> for Required<V, TAG> {
50    #[inline]
51    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
52        match Internal::deserialize(deserializer)? {
53            Internal::Tagged(t, v) if t == TAG => Ok(Required(v)),
54            _ => Err(de::Error::custom("required tag not found")),
55        }
56    }
57}
58
59impl<V: Serialize, const TAG: u64> Serialize for Required<V, TAG> {
60    #[inline]
61    fn serialize<S: ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
62        Internal::Tagged(TAG, &self.0).serialize(serializer)
63    }
64}
65
66/// An optional CBOR tag
67///
68/// This data type indicates that the specified tag, and **only** that tag,
69/// is accepted, but not required, during deserialization. The tag will always
70/// be emitted during serialization.
71#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
72pub struct Accepted<V, const TAG: u64>(pub V);
73
74impl<'de, V: Deserialize<'de>, const TAG: u64> Deserialize<'de> for Accepted<V, TAG> {
75    #[inline]
76    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
77        match Internal::deserialize(deserializer)? {
78            Internal::Tagged(t, v) if t == TAG => Ok(Accepted(v)),
79            Internal::Untagged(v) => Ok(Accepted(v)),
80            _ => Err(de::Error::custom("required tag not found")),
81        }
82    }
83}
84
85impl<V: Serialize, const TAG: u64> Serialize for Accepted<V, TAG> {
86    #[inline]
87    fn serialize<S: ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
88        Internal::Tagged(TAG, &self.0).serialize(serializer)
89    }
90}
91
92pub(crate) struct TagAccess<D> {
93    parent: Option<D>,
94    state: usize,
95    tag: Option<u64>,
96}
97
98impl<D> TagAccess<D> {
99    pub fn new(parent: D, tag: Option<u64>) -> Self {
100        Self {
101            parent: Some(parent),
102            state: 0,
103            tag,
104        }
105    }
106}
107
108impl<'de, D: de::Deserializer<'de>> de::Deserializer<'de> for &mut TagAccess<D> {
109    type Error = D::Error;
110
111    #[inline]
112    fn deserialize_any<V: de::Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
113        self.state += 1;
114
115        match self.state {
116            1 => visitor.visit_str(match self.tag {
117                Some(..) => "@@TAGGED@@",
118                None => "@@UNTAGGED@@",
119            }),
120
121            _ => visitor.visit_u64(self.tag.unwrap()),
122        }
123    }
124
125    forward_to_deserialize_any! {
126        i8 i16 i32 i64 i128
127        u8 u16 u32 u64 u128
128        bool f32 f64
129        char str string
130        bytes byte_buf
131        seq map
132        struct tuple tuple_struct
133        identifier ignored_any
134        option unit unit_struct newtype_struct enum
135    }
136}
137
138impl<'de, D: de::Deserializer<'de>> de::EnumAccess<'de> for TagAccess<D> {
139    type Error = D::Error;
140    type Variant = Self;
141
142    #[inline]
143    fn variant_seed<V: de::DeserializeSeed<'de>>(
144        mut self,
145        seed: V,
146    ) -> Result<(V::Value, Self::Variant), Self::Error> {
147        let variant = seed.deserialize(&mut self)?;
148        Ok((variant, self))
149    }
150}
151
152impl<'de, D: de::Deserializer<'de>> de::VariantAccess<'de> for TagAccess<D> {
153    type Error = D::Error;
154
155    #[inline]
156    fn unit_variant(self) -> Result<(), Self::Error> {
157        Err(Self::Error::custom("expected tag"))
158    }
159
160    #[inline]
161    fn newtype_variant_seed<U: de::DeserializeSeed<'de>>(
162        mut self,
163        seed: U,
164    ) -> Result<U::Value, Self::Error> {
165        seed.deserialize(self.parent.take().unwrap())
166    }
167
168    #[inline]
169    fn tuple_variant<V: de::Visitor<'de>>(
170        self,
171        _len: usize,
172        visitor: V,
173    ) -> Result<V::Value, Self::Error> {
174        visitor.visit_seq(self)
175    }
176
177    #[inline]
178    fn struct_variant<V: de::Visitor<'de>>(
179        self,
180        _fields: &'static [&'static str],
181        _visitor: V,
182    ) -> Result<V::Value, Self::Error> {
183        Err(Self::Error::custom("expected tag"))
184    }
185}
186
187impl<'de, D: de::Deserializer<'de>> de::SeqAccess<'de> for TagAccess<D> {
188    type Error = D::Error;
189
190    #[inline]
191    fn next_element_seed<T: de::DeserializeSeed<'de>>(
192        &mut self,
193        seed: T,
194    ) -> Result<Option<T::Value>, Self::Error> {
195        if self.state < 2 {
196            return Ok(Some(seed.deserialize(self)?));
197        }
198
199        Ok(match self.parent.take() {
200            Some(x) => Some(seed.deserialize(x)?),
201            None => None,
202        })
203    }
204}
205
206#[derive(Debug)]
207pub(crate) struct Error;
208
209impl core::fmt::Display for Error {
210    #[inline]
211    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
212        write!(f, "{:?}", self)
213    }
214}
215
216impl ser::StdError for Error {}
217
218impl ser::Error for Error {
219    fn custom<U: core::fmt::Display>(_msg: U) -> Self {
220        Error
221    }
222}
223
224pub(crate) struct Serializer;
225
226impl ser::Serializer for Serializer {
227    type Ok = u64;
228    type Error = Error;
229
230    type SerializeSeq = Self;
231    type SerializeTuple = Self;
232    type SerializeTupleStruct = Self;
233    type SerializeTupleVariant = Self;
234    type SerializeMap = Self;
235    type SerializeStruct = Self;
236    type SerializeStructVariant = Self;
237
238    #[inline]
239    fn serialize_bool(self, _: bool) -> Result<u64, Self::Error> {
240        Err(Error)
241    }
242
243    #[inline]
244    fn serialize_i8(self, _: i8) -> Result<u64, Self::Error> {
245        Err(Error)
246    }
247
248    #[inline]
249    fn serialize_i16(self, _: i16) -> Result<u64, Self::Error> {
250        Err(Error)
251    }
252
253    #[inline]
254    fn serialize_i32(self, _: i32) -> Result<u64, Self::Error> {
255        Err(Error)
256    }
257
258    #[inline]
259    fn serialize_i64(self, _: i64) -> Result<u64, Self::Error> {
260        Err(Error)
261    }
262
263    #[inline]
264    fn serialize_i128(self, _: i128) -> Result<u64, Self::Error> {
265        Err(Error)
266    }
267
268    #[inline]
269    fn serialize_u8(self, v: u8) -> Result<u64, Self::Error> {
270        Ok(v.into())
271    }
272
273    #[inline]
274    fn serialize_u16(self, v: u16) -> Result<u64, Self::Error> {
275        Ok(v.into())
276    }
277
278    #[inline]
279    fn serialize_u32(self, v: u32) -> Result<u64, Self::Error> {
280        Ok(v.into())
281    }
282
283    #[inline]
284    fn serialize_u64(self, v: u64) -> Result<u64, Self::Error> {
285        Ok(v)
286    }
287
288    #[inline]
289    fn serialize_u128(self, _: u128) -> Result<u64, Self::Error> {
290        Err(Error)
291    }
292
293    #[inline]
294    fn serialize_f32(self, _: f32) -> Result<u64, Self::Error> {
295        Err(Error)
296    }
297
298    #[inline]
299    fn serialize_f64(self, _: f64) -> Result<u64, Self::Error> {
300        Err(Error)
301    }
302
303    #[inline]
304    fn serialize_char(self, _: char) -> Result<u64, Self::Error> {
305        Err(Error)
306    }
307
308    #[inline]
309    fn serialize_str(self, _: &str) -> Result<u64, Self::Error> {
310        Err(Error)
311    }
312
313    #[inline]
314    fn serialize_bytes(self, _: &[u8]) -> Result<u64, Self::Error> {
315        Err(Error)
316    }
317
318    #[inline]
319    fn serialize_none(self) -> Result<u64, Self::Error> {
320        Err(Error)
321    }
322
323    #[inline]
324    fn serialize_some<U: ?Sized + ser::Serialize>(self, _: &U) -> Result<u64, Self::Error> {
325        Err(Error)
326    }
327
328    #[inline]
329    fn serialize_unit(self) -> Result<u64, Self::Error> {
330        Err(Error)
331    }
332
333    #[inline]
334    fn serialize_unit_struct(self, _name: &'static str) -> Result<u64, Self::Error> {
335        Err(Error)
336    }
337
338    #[inline]
339    fn serialize_unit_variant(
340        self,
341        _name: &'static str,
342        _index: u32,
343        _variant: &'static str,
344    ) -> Result<u64, Self::Error> {
345        Err(Error)
346    }
347
348    #[inline]
349    fn serialize_newtype_struct<U: ?Sized + ser::Serialize>(
350        self,
351        _name: &'static str,
352        _value: &U,
353    ) -> Result<u64, Self::Error> {
354        Err(Error)
355    }
356
357    #[inline]
358    fn serialize_newtype_variant<U: ?Sized + ser::Serialize>(
359        self,
360        _name: &'static str,
361        _index: u32,
362        _variant: &'static str,
363        _value: &U,
364    ) -> Result<u64, Self::Error> {
365        Err(Error)
366    }
367
368    #[inline]
369    fn serialize_seq(self, _length: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
370        Err(Error)
371    }
372
373    #[inline]
374    fn serialize_tuple(self, _length: usize) -> Result<Self::SerializeTuple, Self::Error> {
375        Err(Error)
376    }
377
378    #[inline]
379    fn serialize_tuple_struct(
380        self,
381        _name: &'static str,
382        _length: usize,
383    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
384        Err(Error)
385    }
386
387    #[inline]
388    fn serialize_tuple_variant(
389        self,
390        _name: &'static str,
391        _index: u32,
392        _variant: &'static str,
393        _length: usize,
394    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
395        Err(Error)
396    }
397
398    #[inline]
399    fn serialize_map(self, _length: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
400        Err(Error)
401    }
402
403    #[inline]
404    fn serialize_struct(
405        self,
406        _name: &'static str,
407        _length: usize,
408    ) -> Result<Self::SerializeStruct, Self::Error> {
409        Err(Error)
410    }
411
412    #[inline]
413    fn serialize_struct_variant(
414        self,
415        _name: &'static str,
416        _index: u32,
417        _variant: &'static str,
418        _length: usize,
419    ) -> Result<Self::SerializeStructVariant, Self::Error> {
420        Err(Error)
421    }
422
423    #[inline]
424    fn is_human_readable(&self) -> bool {
425        false
426    }
427}
428
429impl ser::SerializeSeq for Serializer {
430    type Ok = u64;
431    type Error = Error;
432
433    #[inline]
434    fn serialize_element<U: ?Sized + ser::Serialize>(&mut self, _value: &U) -> Result<(), Error> {
435        Err(Error)
436    }
437
438    #[inline]
439    fn end(self) -> Result<Self::Ok, Self::Error> {
440        Err(Error)
441    }
442}
443
444impl ser::SerializeTuple for Serializer {
445    type Ok = u64;
446    type Error = Error;
447
448    #[inline]
449    fn serialize_element<U: ?Sized + ser::Serialize>(&mut self, _value: &U) -> Result<(), Error> {
450        Err(Error)
451    }
452
453    #[inline]
454    fn end(self) -> Result<Self::Ok, Self::Error> {
455        Err(Error)
456    }
457}
458
459impl ser::SerializeTupleStruct for Serializer {
460    type Ok = u64;
461    type Error = Error;
462
463    #[inline]
464    fn serialize_field<U: ?Sized + ser::Serialize>(&mut self, _value: &U) -> Result<(), Error> {
465        Err(Error)
466    }
467
468    #[inline]
469    fn end(self) -> Result<Self::Ok, Self::Error> {
470        Err(Error)
471    }
472}
473
474impl ser::SerializeTupleVariant for Serializer {
475    type Ok = u64;
476    type Error = Error;
477
478    #[inline]
479    fn serialize_field<U: ?Sized + ser::Serialize>(&mut self, _value: &U) -> Result<(), Error> {
480        Err(Error)
481    }
482
483    #[inline]
484    fn end(self) -> Result<Self::Ok, Self::Error> {
485        Err(Error)
486    }
487}
488
489impl ser::SerializeMap for Serializer {
490    type Ok = u64;
491    type Error = Error;
492
493    #[inline]
494    fn serialize_key<U: ?Sized + ser::Serialize>(&mut self, _key: &U) -> Result<(), Error> {
495        Err(Error)
496    }
497
498    #[inline]
499    fn serialize_value<U: ?Sized + ser::Serialize>(&mut self, _value: &U) -> Result<(), Error> {
500        Err(Error)
501    }
502
503    #[inline]
504    fn end(self) -> Result<Self::Ok, Self::Error> {
505        Err(Error)
506    }
507}
508
509impl ser::SerializeStruct for Serializer {
510    type Ok = u64;
511    type Error = Error;
512
513    #[inline]
514    fn serialize_field<U: ?Sized + ser::Serialize>(
515        &mut self,
516        _key: &'static str,
517        _value: &U,
518    ) -> Result<(), Error> {
519        Err(Error)
520    }
521
522    #[inline]
523    fn end(self) -> Result<Self::Ok, Self::Error> {
524        Err(Error)
525    }
526}
527
528impl ser::SerializeStructVariant for Serializer {
529    type Ok = u64;
530    type Error = Error;
531
532    #[inline]
533    fn serialize_field<U: ?Sized + ser::Serialize>(
534        &mut self,
535        _key: &'static str,
536        _value: &U,
537    ) -> Result<(), Self::Error> {
538        Err(Error)
539    }
540
541    #[inline]
542    fn end(self) -> Result<Self::Ok, Self::Error> {
543        Err(Error)
544    }
545}