Debian Codegraph @

src/tags.rs

raw symbols SCIP
1 //! Support for cbor tags
2 use core::fmt;
3 use core::marker::PhantomData;
4 use serde::de::{
5 Deserialize, Deserializer, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, Visitor,
6 };
7 use serde::forward_to_deserialize_any;
8 use serde::ser::{Serialize, Serializer};
9
10 /// signals that a newtype is from a CBOR tag
11 pub(crate) const CBOR_NEWTYPE_NAME: &str = "\0cbor_tag";
12
13 /// A value that is optionally tagged with a cbor tag
14 ///
15 /// this only serves as an intermediate helper for tag serialization or deserialization
16 pub struct Tagged<T> {
17 /// cbor tag
18 pub tag: Option<u64>,
19 /// value
20 pub value: T,
21 }
22
23 impl<T> Tagged<T> {
24 /// Create a new tagged value
25 pub fn new(tag: Option<u64>, value: T) -> Self {
26 Self { tag, value }
27 }
28 }
29
30 impl<T: Serialize> Serialize for Tagged<T> {
31 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
32 set_tag(self.tag);
33 let r = s.serialize_newtype_struct(CBOR_NEWTYPE_NAME, &self.value);
34 set_tag(None);
35 r
36 }
37 }
38
39 fn untagged<T>(value: T) -> Tagged<T> {
40 Tagged::new(None, value)
41 }
42
43 macro_rules! delegate {
44 ($name: ident, $type: ty) => {
45 fn $name<E: serde::de::Error>(self, v: $type) -> Result<Self::Value, E> {
46 T::deserialize(v.into_deserializer()).map(untagged)
47 }
48 };
49 }
50
51 struct EnumDeserializer<A>(A);
52
53 impl<'de, A> Deserializer<'de> for EnumDeserializer<A>
54 where
55 A: EnumAccess<'de>,
56 {
57 type Error = A::Error;
58
59 fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
60 visitor.visit_enum(self.0)
61 }
62
63 forward_to_deserialize_any! {
64 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
65 bytes byte_buf option unit unit_struct newtype_struct seq tuple
66 tuple_struct map struct enum identifier ignored_any
67 }
68 }
69
70 struct NoneDeserializer<E>(PhantomData<E>);
71
72 impl<'de, E> Deserializer<'de> for NoneDeserializer<E>
73 where
74 E: serde::de::Error,
75 {
76 type Error = E;
77
78 fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
79 visitor.visit_none()
80 }
81
82 forward_to_deserialize_any! {
83 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
84 bytes byte_buf option unit unit_struct newtype_struct seq tuple
85 tuple_struct map struct enum identifier ignored_any
86 }
87 }
88
89 struct BytesDeserializer<'a, E>(&'a [u8], PhantomData<E>);
90
91 impl<'de, E> Deserializer<'de> for BytesDeserializer<'_, E>
92 where
93 E: serde::de::Error,
94 {
95 type Error = E;
96
97 fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
98 visitor.visit_bytes(self.0)
99 }
100
101 forward_to_deserialize_any! {
102 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
103 bytes byte_buf option unit unit_struct newtype_struct seq tuple
104 tuple_struct map struct enum identifier ignored_any
105 }
106 }
107
108 /// A visitor that intercepts *just* visit_newtype_struct and passes through everything else.
109 struct MaybeTaggedVisitor<T>(PhantomData<T>);
110
111 impl<'de, T: Deserialize<'de>> Visitor<'de> for MaybeTaggedVisitor<T> {
112 type Value = Tagged<T>;
113
114 fn expecting(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
115 fmt.write_str("a cbor tag newtype")
116 }
117
118 delegate!(visit_bool, bool);
119
120 delegate!(visit_i8, i8);
121 delegate!(visit_i16, i16);
122 delegate!(visit_i32, i32);
123 delegate!(visit_i64, i64);
124
125 delegate!(visit_u8, u8);
126 delegate!(visit_u16, u16);
127 delegate!(visit_u32, u32);
128 delegate!(visit_u64, u64);
129
130 delegate!(visit_f32, f32);
131 delegate!(visit_f64, f64);
132
133 delegate!(visit_char, char);
134 delegate!(visit_str, &str);
135 delegate!(visit_borrowed_str, &'de str);
136
137 #[cfg(feature = "std")]
138 delegate!(visit_byte_buf, Vec<u8>);
139
140 #[cfg(feature = "std")]
141 delegate!(visit_string, String);
142
143 fn visit_bytes<E: serde::de::Error>(self, value: &[u8]) -> Result<Self::Value, E> {
144 T::deserialize(BytesDeserializer(value, PhantomData)).map(untagged)
145 }
146
147 fn visit_borrowed_bytes<E: serde::de::Error>(self, value: &'de [u8]) -> Result<Self::Value, E> {
148 T::deserialize(serde::de::value::BorrowedBytesDeserializer::new(value)).map(untagged)
149 }
150
151 fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
152 T::deserialize(().into_deserializer()).map(untagged)
153 }
154
155 fn visit_none<E: serde::de::Error>(self) -> Result<Self::Value, E> {
156 T::deserialize(NoneDeserializer(PhantomData)).map(untagged)
157 }
158
159 fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
160 T::deserialize(deserializer).map(untagged)
161 }
162
163 fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Self::Value, A::Error> {
164 T::deserialize(serde::de::value::SeqAccessDeserializer::new(seq)).map(untagged)
165 }
166
167 fn visit_map<V: MapAccess<'de>>(self, map: V) -> Result<Self::Value, V::Error> {
168 T::deserialize(serde::de::value::MapAccessDeserializer::new(map)).map(untagged)
169 }
170
171 fn visit_enum<A: EnumAccess<'de>>(self, data: A) -> Result<Self::Value, A::Error> {
172 T::deserialize(EnumDeserializer(data)).map(untagged)
173 }
174
175 fn visit_newtype_struct<D: serde::Deserializer<'de>>(
176 self,
177 deserializer: D,
178 ) -> Result<Self::Value, D::Error> {
179 let t = get_tag();
180 T::deserialize(deserializer).map(|v| Tagged::new(t, v))
181 }
182 }
183
184 impl<'de, T: serde::de::Deserialize<'de>> serde::de::Deserialize<'de> for Tagged<T> {
185 fn deserialize<D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
186 deserializer.deserialize_any(MaybeTaggedVisitor::<T>(PhantomData))
187 }
188 }
189
190 /// function to get the current cbor tag
191 ///
192 /// The only place where it makes sense to call this function is within visit_newtype_struct of a serde visitor.
193 /// This is a low level API. In most cases it is preferable to use Tagged
194 pub fn current_cbor_tag() -> Option<u64> {
195 get_tag()
196 }
197
198 #[cfg(feature = "tags")]
199 pub(crate) fn set_tag(value: Option<u64>) {
200 CBOR_TAG.with(|f| *f.borrow_mut() = value);
201 }
202
203 #[cfg(feature = "tags")]
204 pub(crate) fn get_tag() -> Option<u64> {
205 CBOR_TAG.with(|f| *f.borrow())
206 }
207
208 #[cfg(not(feature = "tags"))]
209 pub(crate) fn set_tag(_value: Option<u64>) {}
210
211 #[cfg(not(feature = "tags"))]
212 pub(crate) fn get_tag() -> Option<u64> {
213 None
214 }
215
216 #[cfg(feature = "tags")]
217 use std::cell::RefCell;
218
219 #[cfg(feature = "tags")]
220 thread_local!(static CBOR_TAG: RefCell<Option<u64>> = const { RefCell::new(None) });