-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathattributes.rs
More file actions
175 lines (162 loc) · 5.88 KB
/
Copy pathattributes.rs
File metadata and controls
175 lines (162 loc) · 5.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
//! Implementation of the deserializer from attributes
use std::borrow::Cow;
use serde::de::{DeserializeSeed, Deserializer, Error, MapAccess, Visitor};
use serde::forward_to_deserialize_any;
use crate::de::key::QNameDeserializer;
use crate::de::SimpleTypeDeserializer;
use crate::de::{EntityResolver, PredefinedEntityResolver};
use crate::errors::serialize::DeError;
use crate::events::attributes::Attributes;
use crate::XmlVersion;
impl<'i> Attributes<'i> {
/// Converts this iterator into a serde's [`MapAccess`] trait to use with serde.
/// The returned object also implements the [`Deserializer`] trait.
///
/// # Parameters
/// - `prefix`: a prefix of the field names in structs that should be stripped
/// to get the local attribute name. The [`crate::de::Deserializer`] uses `"@"`
/// as a prefix, but [`Self::into_deserializer()`] uses empty string, which mean
/// that we do not strip anything.
///
/// # Example
/// ```
/// # use pretty_assertions::assert_eq;
/// use quick_xml::events::BytesStart;
/// use quick_xml::de::PredefinedEntityResolver;
/// use quick_xml::XmlVersion;
/// use serde::Deserialize;
///
/// #[derive(Debug, PartialEq, Deserialize)]
/// struct MyData<'i> {
/// question: &'i str,
/// answer: u32,
/// }
///
/// #[derive(Debug, PartialEq, Deserialize)]
/// struct MyDataPrefixed<'i> {
/// #[serde(rename = "@question")] question: &'i str,
/// #[serde(rename = "@answer")] answer: u32,
/// }
///
/// let tag = BytesStart::from_content(
/// "tag
/// question = 'The Ultimate Question of Life, the Universe, and Everything'
/// answer = '42'",
/// 3
/// );
/// // Strip nothing from the field names
/// let de = tag.attributes().clone().into_map_access(XmlVersion::V1_0, "", &PredefinedEntityResolver);
/// assert_eq!(
/// MyData::deserialize(de).unwrap(),
/// MyData {
/// question: "The Ultimate Question of Life, the Universe, and Everything",
/// answer: 42,
/// }
/// );
///
/// // Strip "@" from the field name
/// let de = tag.attributes().into_map_access(XmlVersion::V1_0, "@", &PredefinedEntityResolver);
/// assert_eq!(
/// MyDataPrefixed::deserialize(de).unwrap(),
/// MyDataPrefixed {
/// question: "The Ultimate Question of Life, the Universe, and Everything",
/// answer: 42,
/// }
/// );
/// ```
#[inline]
pub const fn into_map_access<E: EntityResolver>(
self,
version: XmlVersion,
prefix: &'static str,
entity_resolver: &'i E,
) -> AttributesDeserializer<'i, E> {
AttributesDeserializer {
iter: self,
value: None,
prefix,
key_buf: String::new(),
version,
entity_resolver,
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// A deserializer used to make possible to pack all attributes into a struct.
/// It is created by [`Attributes::into_map_access`] or [`Attributes::into_deserializer`]
/// methods.
///
/// This deserializer always call [`Visitor::visit_map`] with self as [`MapAccess`].
///
/// # Lifetime
///
/// `'i` is a lifetime of the original buffer from which attributes were parsed.
/// In particular, when reader was created from a string, this is lifetime of the
/// string.
#[derive(Debug, Clone)]
pub struct AttributesDeserializer<'i, E: EntityResolver = PredefinedEntityResolver> {
iter: Attributes<'i>,
/// The value of the attribute, read in last call to `next_key_seed`.
value: Option<Cow<'i, [u8]>>,
/// This prefix will be stripped from struct fields before match against attribute name.
prefix: &'static str,
/// Buffer to store attribute name as a field name exposed to serde consumers.
/// Kept in the deserializer to avoid many small allocations
key_buf: String,
version: XmlVersion,
entity_resolver: &'i E,
}
impl<'de, E: EntityResolver> Deserializer<'de> for AttributesDeserializer<'de, E> {
type Error = DeError;
#[inline]
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
visitor.visit_map(self)
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
bytes byte_buf option unit unit_struct newtype_struct seq tuple
tuple_struct map struct enum identifier ignored_any
}
}
impl<'de, E: EntityResolver> MapAccess<'de> for AttributesDeserializer<'de, E> {
type Error = DeError;
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
where
K: DeserializeSeed<'de>,
{
debug_assert_eq!(self.value, None);
match self.iter.next() {
None => Ok(None),
Some(Ok(attr)) => {
self.value = Some(attr.value);
self.key_buf.clear();
self.key_buf.push_str(self.prefix);
let de =
QNameDeserializer::from_attr(attr.key, self.iter.decoder(), &mut self.key_buf)?;
seed.deserialize(de).map(Some)
}
Some(Err(err)) => Err(Error::custom(err)),
}
}
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
where
V: DeserializeSeed<'de>,
{
match self.value.take() {
Some(value) => {
let de = SimpleTypeDeserializer::from_attr(
&value,
0..value.len(),
self.version,
self.iter.decoder(),
self.entity_resolver,
);
seed.deserialize(de)
}
None => Err(DeError::KeyNotRead),
}
}
}