Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_reflect/src/serde/de/helpers.rs
6600 views
1
use alloc::{
2
string::{String, ToString},
3
vec::Vec,
4
};
5
use core::{
6
fmt,
7
fmt::{Debug, Display, Formatter},
8
};
9
use serde::{
10
de::{Error, Visitor},
11
Deserialize,
12
};
13
14
/// A debug struct used for error messages that displays a list of expected values.
15
///
16
/// # Example
17
///
18
/// ```ignore (Can't import private struct from doctest)
19
/// let expected = vec!["foo", "bar", "baz"];
20
/// assert_eq!("`foo`, `bar`, `baz`", format!("{}", ExpectedValues(expected)));
21
/// ```
22
pub(super) struct ExpectedValues<T: Display>(pub Vec<T>);
23
24
impl<T: Display> FromIterator<T> for ExpectedValues<T> {
25
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
26
Self(iter.into_iter().collect())
27
}
28
}
29
30
impl<T: Display> Debug for ExpectedValues<T> {
31
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
32
let len = self.0.len();
33
for (index, item) in self.0.iter().enumerate() {
34
write!(f, "`{item}`")?;
35
if index < len - 1 {
36
write!(f, ", ")?;
37
}
38
}
39
Ok(())
40
}
41
}
42
43
/// Represents a simple reflected identifier.
44
#[derive(Debug, Clone, Eq, PartialEq)]
45
pub(super) struct Ident(pub String);
46
47
impl<'de> Deserialize<'de> for Ident {
48
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
49
where
50
D: serde::Deserializer<'de>,
51
{
52
struct IdentVisitor;
53
54
impl<'de> Visitor<'de> for IdentVisitor {
55
type Value = Ident;
56
57
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
58
formatter.write_str("identifier")
59
}
60
61
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
62
where
63
E: Error,
64
{
65
Ok(Ident(value.to_string()))
66
}
67
68
fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
69
where
70
E: Error,
71
{
72
Ok(Ident(value))
73
}
74
}
75
76
deserializer.deserialize_identifier(IdentVisitor)
77
}
78
}
79
80