serde_content/
lib.rs

1//! A container for the Serde data model.
2
3#![cfg_attr(not(feature = "std"), no_std)]
4#![forbid(unsafe_code)]
5#![cfg_attr(test, deny(warnings))]
6#![deny(missing_docs, unused_imports)]
7
8extern crate alloc;
9
10mod de;
11mod error;
12mod number;
13mod ser;
14mod tests;
15
16use alloc::borrow::Cow;
17use alloc::boxed::Box;
18use alloc::string::String;
19use alloc::vec::Vec;
20
21pub use error::Data as FoundData;
22pub use error::Error;
23pub use error::ErrorKind;
24pub use error::Expected;
25pub use error::Found;
26pub use error::Result;
27pub use number::Number;
28#[cfg(feature = "serde")]
29pub use {de::Deserializer, de::Unexpected, de::ValueVisitor, ser::Serializer};
30
31/// Represents struct and enum data.
32#[derive(Debug, Clone, PartialEq, PartialOrd)]
33pub enum Data<'a> {
34    /// Represents unit structs and unit enum variants.
35    Unit,
36    /// Represents newtype structs and enum variants.
37    NewType {
38        /// The value of the newtype struct or enum variant.
39        value: Value<'a>,
40    },
41    /// Represents tuple structs and enum variants.
42    Tuple {
43        /// The values of the tuple struct or enum variant.
44        values: Vec<Value<'a>>,
45    },
46    /// Represents object-like structs and enum variants.
47    Struct {
48        /// A vector of field names and their values.
49        fields: Vec<(Cow<'static, str>, Value<'a>)>,
50    },
51}
52
53impl Data<'_> {
54    /// Moves data where possible or otherwise clones it into an owned object.
55    pub fn into_owned(self) -> Data<'static> {
56        match self {
57            Data::Unit => Data::Unit,
58            Data::NewType { value } => Data::NewType {
59                value: value.into_owned(),
60            },
61            Data::Tuple { values } => Data::Tuple {
62                values: values.into_iter().map(Value::into_owned).collect(),
63            },
64            Data::Struct { fields } => Data::Struct {
65                fields: fields
66                    .into_iter()
67                    .map(|(key, value)| (key, value.into_owned()))
68                    .collect(),
69            },
70        }
71    }
72}
73
74/// Struct and enum data type.
75#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
76#[cfg_attr(feature = "derive", derive(serde::Serialize, serde::Deserialize))]
77pub enum DataType {
78    /// Unit struct or unit enum variant.
79    Unit,
80    /// Newtype struct or enum variant.
81    NewType,
82    /// Tuple struct or enum variant.
83    Tuple,
84    /// Object-like struct or enum variant.
85    Struct,
86}
87
88/// Represents a Rust struct.
89#[derive(Debug, Clone, PartialEq, PartialOrd)]
90pub struct Struct<'a> {
91    /// The name of the struct.
92    pub name: Cow<'static, str>,
93    /// The data of the struct.
94    pub data: Data<'a>,
95}
96
97impl Struct<'_> {
98    /// Moves data where possible or otherwise clones it into an owned object.
99    pub fn into_owned(self) -> Struct<'static> {
100        Struct {
101            data: self.data.into_owned(),
102            ..self
103        }
104    }
105}
106
107/// Represents a Rust enum.
108#[derive(Debug, Clone, PartialEq, PartialOrd)]
109pub struct Enum<'a> {
110    /// The name of the enum.
111    pub name: Cow<'static, str>,
112    /// The index of the enum variant.
113    pub variant_index: u32,
114    /// The name of the enum variant.
115    pub variant: Cow<'static, str>,
116    /// The data of the enum.
117    pub data: Data<'a>,
118}
119
120impl Enum<'_> {
121    /// Moves data where possible or otherwise clones it into an owned object.
122    pub fn into_owned(self) -> Enum<'static> {
123        Enum {
124            data: self.data.into_owned(),
125            ..self
126        }
127    }
128}
129
130/// Represents any valid Rust value.
131#[derive(Debug, Clone, PartialEq, PartialOrd)]
132pub enum Value<'a> {
133    /// Represents the Rust unit type, `()`.
134    Unit,
135    /// Represents a Rust boolean.
136    Bool(bool),
137    /// Represents any Rust number.
138    Number(Number),
139    /// Represents a Rust character.
140    Char(char),
141    /// Represents a Rust string.
142    String(Cow<'a, str>),
143    /// Represents a Rust byte array.
144    Bytes(Cow<'a, [u8]>),
145    /// Represents an array of Rust values.
146    Seq(Vec<Value<'a>>),
147    /// Represents a map of Rust values.
148    Map(Vec<(Value<'a>, Value<'a>)>),
149    /// Represents optional Rust values.
150    Option(Option<Box<Value<'a>>>),
151    /// Represents a Rust struct.
152    Struct(Box<Struct<'a>>),
153    /// Represents a Rust enum.
154    Enum(Box<Enum<'a>>),
155    /// Represents a Rust tuple.
156    Tuple(Vec<Value<'a>>),
157}
158
159impl Value<'_> {
160    /// Moves data where possible or otherwise clones it into an owned object.
161    pub fn into_owned(self) -> Value<'static> {
162        match self {
163            Value::Unit => Value::Unit,
164            Value::Bool(v) => Value::Bool(v),
165            Value::Number(v) => Value::Number(v),
166            Value::Char(v) => Value::Char(v),
167            Value::String(v) => Value::String(Cow::Owned(v.into_owned())),
168            Value::Bytes(v) => Value::Bytes(Cow::Owned(v.into_owned())),
169            Value::Seq(v) => Value::Seq(v.into_iter().map(Self::into_owned).collect()),
170            Value::Map(v) => Value::Map(
171                v.into_iter()
172                    .map(|(key, value)| (key.into_owned(), value.into_owned()))
173                    .collect(),
174            ),
175            Value::Option(v) => match v {
176                Some(v) => Value::Option(Some(Box::new(v.into_owned()))),
177                None => Value::Option(None),
178            },
179            Value::Struct(v) => Value::Struct(Box::new(v.into_owned())),
180            Value::Enum(v) => Value::Enum(Box::new(v.into_owned())),
181            Value::Tuple(v) => Value::Tuple(v.into_iter().map(Self::into_owned).collect()),
182        }
183    }
184}
185
186impl From<()> for Value<'static> {
187    fn from(_: ()) -> Self {
188        Self::Unit
189    }
190}
191
192impl From<bool> for Value<'static> {
193    fn from(value: bool) -> Self {
194        Self::Bool(value)
195    }
196}
197
198impl<T> From<T> for Value<'static>
199where
200    T: Into<Number>,
201{
202    fn from(value: T) -> Self {
203        Self::Number(value.into())
204    }
205}
206
207impl From<char> for Value<'static> {
208    fn from(value: char) -> Self {
209        Self::Char(value)
210    }
211}
212
213impl<'a> From<Cow<'a, str>> for Value<'a> {
214    fn from(value: Cow<'a, str>) -> Self {
215        Self::String(value)
216    }
217}
218
219impl<'a> From<&'a str> for Value<'a> {
220    fn from(value: &'a str) -> Self {
221        Self::String(Cow::Borrowed(value))
222    }
223}
224
225impl<'a> From<&'a String> for Value<'a> {
226    fn from(value: &'a String) -> Self {
227        Self::String(Cow::Borrowed(value))
228    }
229}
230
231impl From<String> for Value<'static> {
232    fn from(value: String) -> Self {
233        Self::String(Cow::Owned(value))
234    }
235}
236
237impl<'a> From<&'a [u8]> for Value<'a> {
238    fn from(value: &'a [u8]) -> Self {
239        Self::Bytes(Cow::Borrowed(value))
240    }
241}
242
243impl<'a> From<&'a Vec<u8>> for Value<'a> {
244    fn from(value: &'a Vec<u8>) -> Self {
245        Self::Bytes(Cow::Borrowed(value))
246    }
247}
248
249impl From<Vec<u8>> for Value<'static> {
250    fn from(value: Vec<u8>) -> Self {
251        Self::Bytes(Cow::Owned(value))
252    }
253}