Skip to main content

deser_core/ser/
describe.rs

1//! Describing the Rust shape of values.
2/// Receives the description of the Rust shape of a value.
3///
4/// The data model of deser is small: a struct is a map with string keys, a
5/// tuple is a sequence, `Some(42)` is just `42`.  Formats which want to
6/// reflect the Rust shape of values (for instance a `Debug`-like formatter)
7/// can ask a value to [`describe`](crate::ser::Serialize::describe) itself.
8/// The description is pulled: values are only asked if a format wants to
9/// know, which means that formats which do not care pay nothing for it.
10///
11/// The [`SerializeDriver`](crate::ser::SerializeDriver) passes the value an
12/// event belongs to along with the event.  The value of the end event of a
13/// map or sequence is the value that started it.  Keys of structs come with
14/// a value that describes nothing (the description of the struct says that
15/// the keys are field names).
16///
17/// Wrappers describe themselves and then delegate to the value they wrap,
18/// which is how nested wrappers such as `Some(Meters(5.0))` are described:
19/// the describer receives [`some`](Describe::some),
20/// [`newtype`](Describe::newtype) and then nothing (as `f64` has no
21/// description of its own).
22///
23/// ```
24/// use deser::ser::{Describe, SerializeRef};
25///
26/// #[derive(Default)]
27/// struct Names(Vec<String>);
28///
29/// impl Describe for Names {
30///     fn structure(&mut self, name: &str) {
31///         self.0.push(format!("struct {}", name));
32///     }
33///
34///     fn some(&mut self) {
35///         self.0.push("some".into());
36///     }
37/// }
38///
39/// let mut names = Names::default();
40/// SerializeRef::new(&Some(Some(42))).describe(&mut names);
41/// assert_eq!(names.0, ["some", "some"]);
42/// ```
43///
44/// The names passed to the describer are the names used when serializing
45/// (after renames), variants that are named by integers or booleans are
46/// described with their name as text.
47///
48/// All methods ignore the call by default so that describers only need to
49/// implement what they care about.  New methods can be added in the future.
50///
51/// Types describe themselves with
52/// [`Serialize::describe`](crate::ser::Serialize::describe) (a value) and
53/// [`Deserialize::describe_type`](crate::de::Deserialize::describe_type)
54/// (what is known without a value).  Descriptions are mostly informational
55/// (for formats like a `Debug`-like formatter), but some facts change how
56/// values are represented, so the descriptions have to be accurate:
57///
58/// * [`unit_struct`](Self::unit_struct): newtype variants of internally
59///   tagged enums whose content is a unit struct are the tag alone.  The
60///   serializer checks the description of the value, the deserializer the
61///   one of the type, so both have to describe the unit struct.
62pub trait Describe {
63    /// The value is a struct with named fields.
64    ///
65    /// It's serialized as map with the names of the fields as keys.
66    fn structure(&mut self, name: &str) {
67        let _ = name;
68    }
69
70    /// The names of the fields of the struct that was just described with
71    /// [`structure`](Self::structure), in the order they are serialized.
72    ///
73    /// The keys of the map the struct is serialized as are a subsequence
74    /// of these names: fields can be skipped but no other keys are
75    /// emitted.  This lets formats know which keys can still come, for
76    /// instance to write parts of the output before the struct ends.
77    /// Structs whose keys are not known upfront (like derived structs with
78    /// flattened fields) do not describe their fields.
79    ///
80    /// ```
81    /// use deser::ser::Describe;
82    ///
83    /// #[derive(deser::Serialize)]
84    /// struct Link {
85    ///     #[deser(rename = "@href")]
86    ///     href: String,
87    ///     #[deser(skip_serializing)]
88    ///     cache: u32,
89    ///     title: String,
90    /// }
91    ///
92    /// #[derive(Default)]
93    /// struct Fields(&'static [&'static str]);
94    ///
95    /// impl Describe for Fields {
96    ///     fn fields(&mut self, names: &'static [&'static str]) {
97    ///         self.0 = names;
98    ///     }
99    /// }
100    ///
101    /// let mut fields = Fields::default();
102    /// let link = Link { href: "/".into(), cache: 0, title: "x".into() };
103    /// deser::ser::SerializeRef::new(&link).describe(&mut fields);
104    /// assert_eq!(fields.0, ["@href", "title"]);
105    /// ```
106    fn fields(&mut self, names: &'static [&'static str]) {
107        let _ = names;
108    }
109
110    /// The value is a newtype struct.
111    ///
112    /// It's serialized as the value it wraps, the description of that value
113    /// follows.
114    fn newtype(&mut self, name: &str) {
115        let _ = name;
116    }
117
118    /// The value is a tuple struct (a struct with more than one unnamed
119    /// field).
120    ///
121    /// It's serialized as sequence.
122    fn tuple_struct(&mut self, name: &str) {
123        let _ = name;
124    }
125
126    /// The value is a unit struct (a struct without fields).
127    ///
128    /// It's serialized as null and deserialized from null.  This is not
129    /// only informational: newtype variants of internally tagged enums with
130    /// a unit struct as content are the tag alone (`{"type": "A"}`), other
131    /// content that is null is not.  Only unit
132    /// structs themselves and wrappers that are serialized and deserialized
133    /// as the value they wrap (like `Box`) describe this, not newtypes or
134    /// options of unit structs.
135    fn unit_struct(&mut self, name: &str) {
136        let _ = name;
137    }
138
139    /// The value is a variant of an enum.
140    ///
141    /// How the variant is serialized depends on its [`VariantRepr`].  For
142    /// externally tagged variants with content the value is a map with a
143    /// single entry, the key is the name of the variant and the value the
144    /// content.
145    fn variant(&mut self, variant: &Variant<'_>) {
146        let _ = variant;
147    }
148
149    /// The value is `Some` of an `Option`.
150    ///
151    /// It's serialized as the value it wraps, the description of that value
152    /// follows.
153    fn some(&mut self) {}
154
155    /// The value is `None` of an `Option`.
156    ///
157    /// It's serialized as null.
158    fn none(&mut self) {}
159
160    /// The value is a tuple.
161    ///
162    /// It's serialized as sequence.
163    fn tuple(&mut self) {}
164
165    /// The value is a set.
166    ///
167    /// It's serialized as sequence.
168    fn set(&mut self) {}
169}
170
171/// Describes a variant of an enum.
172///
173/// See [`Describe::variant`].
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175#[non_exhaustive]
176pub struct Variant<'a> {
177    /// The name of the enum.
178    pub enum_name: &'a str,
179    /// The name of the variant.
180    pub name: &'a str,
181    /// The kind of variant.
182    pub kind: VariantKind,
183    /// How the variant is represented.
184    pub repr: VariantRepr<'a>,
185}
186
187impl<'a> Variant<'a> {
188    /// Creates a variant description.
189    pub const fn new(
190        enum_name: &'a str,
191        name: &'a str,
192        kind: VariantKind,
193        repr: VariantRepr<'a>,
194    ) -> Variant<'a> {
195        Variant {
196            enum_name,
197            name,
198            kind,
199            repr,
200        }
201    }
202}
203
204/// The kind of an enum variant.
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
206#[non_exhaustive]
207pub enum VariantKind {
208    /// A variant without content (`A`).
209    Unit,
210    /// A variant with a single unnamed field (`A(T)`).
211    Newtype,
212    /// A variant with multiple unnamed fields (`A(T, U)`).
213    Tuple,
214    /// A variant with named fields (`A { x: T }`).
215    Struct,
216}
217
218/// How an enum variant is represented.
219///
220/// This corresponds to the representations of the derive (see
221/// [`derive`][derive-module]).
222///
223#[cfg_attr(feature = "derive", doc = "[derive-module]: crate::derive")]
224#[cfg_attr(
225    not(feature = "derive"),
226    doc = "[derive-module]: https://docs.rs/deser/latest/deser/derive/"
227)]
228#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
229#[non_exhaustive]
230pub enum VariantRepr<'a> {
231    /// Externally tagged: unit variants are their name, others a map with
232    /// the name as key and the content as value.
233    External,
234    /// Internally tagged: a map with the name in the given key and the
235    /// fields of the content.
236    Internal {
237        /// The key of the name.
238        tag: &'a str,
239    },
240    /// Adjacently tagged: a map with the name and the content in the given
241    /// keys.
242    Adjacent {
243        /// The key of the name.
244        tag: &'a str,
245        /// The key of the content.
246        content: &'a str,
247    },
248    /// Untagged: just the content.
249    Untagged,
250}
251
252/// Returns `true` if a description is the one of a unit struct.
253///
254/// The description is given by a function that describes a value or type
255/// (like `|d| value.describe(d)` or `T::describe_type`).  It's the
256/// description of a unit struct if it says
257/// [`unit_struct`](Describe::unit_struct) and does not wrap it (newtypes
258/// and options of unit structs are not unit structs).  The serializer and
259/// the deserializer decide with this whether newtype variants of internally
260/// tagged enums are the tag alone, so they agree for all types whose
261/// descriptions agree.
262#[cfg(feature = "derive")]
263pub(crate) fn is_unit_struct(describe: impl FnOnce(&mut dyn Describe)) -> bool {
264    #[derive(Default)]
265    struct IsUnitStruct {
266        unit_struct: bool,
267        wrapped: bool,
268    }
269
270    impl Describe for IsUnitStruct {
271        fn unit_struct(&mut self, _name: &str) {
272            self.unit_struct = true;
273        }
274
275        fn newtype(&mut self, _name: &str) {
276            self.wrapped = true;
277        }
278
279        fn some(&mut self) {
280            self.wrapped = true;
281        }
282
283        fn none(&mut self) {
284            self.wrapped = true;
285        }
286    }
287
288    let mut d = IsUnitStruct::default();
289    describe(&mut d);
290    d.unit_struct && !d.wrapped
291}