rxml/
xml_map.rs

1/*!
2# Map structure for XML names to values
3
4This module contains the supporting structures for the
5[`XmlMap`][`crate::XmlMap`] struct, which is used to represent the set of
6attributes on an XML element.
7
8It is used for instance in [`Event`][`crate::Event`].
9*/
10use alloc::collections::{btree_map, BTreeMap};
11use alloc::string::String;
12use core::borrow::Borrow;
13use core::fmt;
14use core::hash::Hash;
15use core::iter::FromIterator;
16
17use crate::{Namespace, NcName};
18
19/// Container struct for a set of attributes on an XML element.
20///
21/// This is basically a wrapper around one of the map types from the standard
22/// library (which one is an implementation detail).
23///
24/// It is provided instead of using `HashMap<(Namespace, NcName), V>` in
25/// the public API for the following reasons:
26///
27/// - Flexibility regarding the map implementation
28/// - Ease of use: standard library maps are excruciatingly annoying to use
29///   with tuple keys.
30///
31/// Other than that, it behaves and offers the same API like a standard
32/// library map.
33#[derive(Clone, Default)]
34pub struct XmlMap<V> {
35	inner: BTreeMap<Namespace, BTreeMap<NcName, V>>,
36}
37
38/// Type alias for the commonly used mapping type for XML attribute values.
39pub type AttrMap = XmlMap<String>;
40
41impl<V> XmlMap<V> {
42	/// Creates an empty `XmlMap`.
43	///
44	/// # Example
45	///
46	/// ```
47	/// # use rxml::{AttrMap, Namespace, NcName};
48	/// let map = AttrMap::new();
49	/// assert_eq!(map.len(), 0);
50	/// ```
51	#[inline(always)]
52	pub fn new() -> Self {
53		Self {
54			inner: BTreeMap::new(),
55		}
56	}
57
58	/// Clears the map, removing all key-value pairs.
59	///
60	/// # Example
61	///
62	/// ```
63	/// # use rxml::{AttrMap, Namespace, NcName};
64	/// let mut map = AttrMap::new();
65	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "hello".try_into().unwrap());
66	/// assert_eq!(map.len(), 1);
67	/// map.clear();
68	/// assert_eq!(map.len(), 0);
69	/// ```
70	#[inline(always)]
71	pub fn clear(&mut self) {
72		self.inner.clear()
73	}
74
75	/// Returns a reference to the value corresponding to the attribute.
76	///
77	/// # Example
78	///
79	/// ```
80	/// # use rxml::{AttrMap, Namespace, NcName};
81	/// let mut map = AttrMap::new();
82	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "hello".try_into().unwrap());
83	/// assert_eq!(map.get(&Namespace::NONE, "bar").unwrap(), "hello");
84	/// assert!(map.get(&Namespace::NONE, "baz").is_none());
85	/// assert!(map.get("other", "baz").is_none());
86	/// ```
87	#[inline(always)]
88	pub fn get<'a, NS: Ord + Hash + Eq + ?Sized, N: Ord + Hash + Eq + ?Sized>(
89		&'a self,
90		namespace: &NS,
91		name: &N,
92	) -> Option<&'a V>
93	where
94		Namespace: Borrow<NS>,
95		NcName: Borrow<N>,
96	{
97		self.inner.get(namespace).and_then(|inner| inner.get(name))
98	}
99
100	/// Returns `true` if the map contains a value for the specified
101	/// attribute.
102	///
103	/// # Example
104	///
105	/// ```
106	/// # use rxml::{AttrMap, Namespace, NcName};
107	/// let mut map = AttrMap::new();
108	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "hello".try_into().unwrap());
109	/// assert!(map.contains_key(&Namespace::NONE, "bar"));
110	/// assert!(!map.contains_key(&Namespace::NONE, "baz"));
111	/// assert!(!map.contains_key("other", "baz"));
112	/// ```
113	#[inline(always)]
114	pub fn contains_key<NS: Ord + Hash + Eq + ?Sized, N: Ord + Hash + Eq + ?Sized>(
115		&self,
116		namespace: &NS,
117		name: &N,
118	) -> bool
119	where
120		Namespace: Borrow<NS>,
121		NcName: Borrow<N>,
122	{
123		self.inner
124			.get(namespace)
125			.map(|inner| inner.contains_key(name))
126			.unwrap_or(false)
127	}
128
129	/// Returns a mutable reference to the value corresponding to the
130	/// attribute.
131	///
132	/// # Example
133	///
134	/// ```
135	/// # use rxml::{AttrMap, Namespace, NcName};
136	/// let mut map = AttrMap::new();
137	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "hello".try_into().unwrap());
138	/// map.get_mut(&Namespace::NONE, "bar").map(|x| x.push_str(" world".try_into().unwrap()));
139	/// assert_eq!(map.get(&Namespace::NONE, "bar").unwrap(), "hello world");
140	/// ```
141	pub fn get_mut<'a, NS: Ord + Hash + Eq + ?Sized, N: Ord + Hash + Eq + ?Sized>(
142		&'a mut self,
143		namespace: &NS,
144		name: &N,
145	) -> Option<&'a mut V>
146	where
147		Namespace: Borrow<NS>,
148		NcName: Borrow<N>,
149	{
150		self.inner
151			.get_mut(namespace)
152			.and_then(|inner| inner.get_mut(name))
153	}
154
155	/// Insert an attribute
156	///
157	/// # Example
158	///
159	/// ```
160	/// # use rxml::{AttrMap, Namespace, NcName};
161	/// let mut map = AttrMap::new();
162	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "hello".try_into().unwrap());
163	/// assert_eq!(map.get(&Namespace::NONE, "bar").unwrap(), "hello");
164	/// ```
165	pub fn insert(&mut self, namespace: Namespace, name: NcName, value: V) -> Option<V> {
166		match self.inner.entry(namespace) {
167			btree_map::Entry::Occupied(mut o) => o.get_mut().insert(name, value),
168			btree_map::Entry::Vacant(v) => v.insert(BTreeMap::new()).insert(name, value),
169		}
170	}
171
172	/// Removes an attribute from the map, returning the value of the
173	/// attribute if it was previously in the map.
174	///
175	/// # Example
176	///
177	/// ```
178	/// # use rxml::{AttrMap, Namespace, NcName};
179	/// let mut map = AttrMap::new();
180	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "hello".try_into().unwrap());
181	/// assert!(map.remove(&Namespace::NONE, "baz").is_none());
182	/// assert_eq!(map.remove(&Namespace::NONE, "bar").unwrap(), "hello");
183	/// assert!(map.remove(&Namespace::NONE, "bar").is_none());
184	/// ```
185	#[inline(always)]
186	pub fn remove<NS: Ord + Hash + Eq + ?Sized, N: Ord + Hash + Eq + ?Sized>(
187		&mut self,
188		namespace: &NS,
189		name: &N,
190	) -> Option<V>
191	where
192		Namespace: Borrow<NS>,
193		NcName: Borrow<N>,
194	{
195		match self.inner.get_mut(namespace) {
196			None => None,
197			Some(inner) => {
198				let result = inner.remove(name);
199				if inner.is_empty() {
200					self.inner.remove(namespace);
201				}
202				result
203			}
204		}
205	}
206
207	/// Retains only the elements specified by the predicate.
208	///
209	/// # Example
210	///
211	/// ```
212	/// # use rxml::{AttrMap, Namespace, NcName};
213	/// let mut map = AttrMap::new();
214	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "value 1".try_into().unwrap());
215	/// map.insert(Namespace::NONE, "baz".try_into().unwrap(), "value 2".try_into().unwrap());
216	/// map.insert("other".try_into().unwrap(), "bar".try_into().unwrap(), "value 3".try_into().unwrap());
217	/// map.retain(|_ns, name, _value| name == "bar");
218	/// assert_eq!(map.len(), 2);
219	/// ```
220	#[inline(always)]
221	pub fn retain<F: FnMut(&Namespace, &NcName, &mut V) -> bool>(&mut self, mut f: F) {
222		self.inner.retain(|ns, inner| {
223			inner.retain(|name, value| f(ns, name, value));
224			!inner.is_empty()
225		})
226	}
227
228	/// An iterator visiting all attribute namespace/name pairs in arbitrary
229	/// order.
230	///
231	/// # Example
232	///
233	/// ```
234	/// # use rxml::{AttrMap, Namespace, NcName};
235	/// let mut map = AttrMap::new();
236	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "value 1".try_into().unwrap());
237	/// map.insert(Namespace::NONE, "baz".try_into().unwrap(), "value 2".try_into().unwrap());
238	/// map.insert("other".try_into().unwrap(), "bar".try_into().unwrap(), "value 3".try_into().unwrap());
239	/// let data: Vec<_> = map.into_names().collect();
240	/// assert_eq!(data.len(), 3);
241	/// assert_eq!(data.iter().filter(|(ns, _)| ns.is_none()).count(), 2);
242	/// assert_eq!(data.iter().filter(|(ns, _)| !ns.is_none()).count(), 1);
243	/// ```
244	#[inline(always)]
245	pub fn into_names(self) -> IntoNames<V> {
246		IntoNames::new(self.inner.into_iter())
247	}
248
249	/// An iterator visiting all attribute values in arbitrary order.
250	///
251	/// # Example
252	///
253	/// ```
254	/// # use rxml::{AttrMap, Namespace, NcName};
255	/// let mut map = AttrMap::new();
256	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "value".try_into().unwrap());
257	/// map.insert(Namespace::NONE, "baz".try_into().unwrap(), "value".try_into().unwrap());
258	/// map.insert("other".try_into().unwrap(), "bar".try_into().unwrap(), "value".try_into().unwrap());
259	/// let data: Vec<_> = map.into_values().collect();
260	/// let str_data: Vec<&str> = data.iter().map(|x| x.as_str()).collect();
261	/// assert_eq!(&str_data, &["value", "value", "value"]);
262	/// ```
263	#[inline(always)]
264	pub fn into_values(self) -> IntoValues<V> {
265		IntoValues::new(self.inner.into_values())
266	}
267
268	/// An iterator visiting all attribute pairs in arbitrary order.
269	///
270	/// # Example
271	///
272	/// ```
273	/// # use rxml::{AttrMap, Namespace, NcName};
274	/// let mut map = AttrMap::new();
275	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "value".try_into().unwrap());
276	/// map.insert(Namespace::NONE, "baz".try_into().unwrap(), "value".try_into().unwrap());
277	/// map.insert("other".try_into().unwrap(), "bar".try_into().unwrap(), "value".try_into().unwrap());
278	/// let data: Vec<_> = map.iter().collect();
279	/// assert_eq!(data.len(), 3);
280	/// assert_eq!(data.iter().filter(|((ns, _), _)| ns.is_none()).count(), 2);
281	/// assert_eq!(data.iter().filter(|((ns, _), _)| !ns.is_none()).count(), 1);
282	/// ```
283	#[inline(always)]
284	pub fn iter(&self) -> Iter<'_, V> {
285		self.into_iter()
286	}
287
288	/// An iterator visiting all attribute pairs in arbitrary order, with
289	/// mutable references to the values.
290	///
291	/// # Example
292	///
293	/// ```
294	/// # use rxml::{AttrMap, Namespace, NcName};
295	/// let mut map = AttrMap::new();
296	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "value".try_into().unwrap());
297	/// map.insert(Namespace::NONE, "baz".try_into().unwrap(), "value".try_into().unwrap());
298	/// map.insert("other".try_into().unwrap(), "bar".try_into().unwrap(), "value".try_into().unwrap());
299	/// let data: Vec<_> = map.iter_mut().collect();
300	/// assert_eq!(data.len(), 3);
301	/// assert_eq!(data.iter().filter(|((ns, _), _)| ns.is_none()).count(), 2);
302	/// assert_eq!(data.iter().filter(|((ns, _), _)| !ns.is_none()).count(), 1);
303	/// ```
304	#[inline(always)]
305	pub fn iter_mut(&mut self) -> IterMut<'_, V> {
306		self.into_iter()
307	}
308
309	/// An iterator visiting all attribute namespace/name pairs in arbitrary
310	/// order.
311	///
312	/// # Example
313	///
314	/// ```
315	/// # use rxml::{AttrMap, Namespace, NcName};
316	/// let mut map = AttrMap::new();
317	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "value 1".try_into().unwrap());
318	/// map.insert(Namespace::NONE, "baz".try_into().unwrap(), "value 2".try_into().unwrap());
319	/// map.insert("other".try_into().unwrap(), "bar".try_into().unwrap(), "value 3".try_into().unwrap());
320	/// let data: Vec<_> = map.names().collect();
321	/// assert_eq!(data.len(), 3);
322	/// assert_eq!(data.iter().filter(|(ns, _)| ns.is_none()).count(), 2);
323	/// assert_eq!(data.iter().filter(|(ns, _)| !ns.is_none()).count(), 1);
324	/// ```
325	#[inline(always)]
326	pub fn names(&self) -> Names<'_, V> {
327		Names::new(self.inner.iter())
328	}
329
330	/// An iterator visiting all attribute values in arbitrary order.
331	///
332	/// # Example
333	///
334	/// ```
335	/// # use rxml::{AttrMap, Namespace, NcName};
336	/// let mut map = AttrMap::new();
337	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "value".try_into().unwrap());
338	/// map.insert(Namespace::NONE, "baz".try_into().unwrap(), "value".try_into().unwrap());
339	/// map.insert("other".try_into().unwrap(), "bar".try_into().unwrap(), "value".try_into().unwrap());
340	/// let data: Vec<_> = map.values().collect();
341	/// let str_data: Vec<&str> = data.iter().map(|x| x.as_str()).collect();
342	/// assert_eq!(&str_data, &["value", "value", "value"]);
343	/// ```
344	#[inline(always)]
345	pub fn values(&self) -> Values<'_, V> {
346		Values::new(self.inner.values())
347	}
348
349	/// An iterator visiting all attribute values as mutable references in
350	/// arbitrary order.
351	///
352	/// # Example
353	///
354	/// ```
355	/// # use rxml::{AttrMap, Namespace, NcName};
356	/// let mut map = AttrMap::new();
357	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "value".try_into().unwrap());
358	/// map.insert(Namespace::NONE, "baz".try_into().unwrap(), "value".try_into().unwrap());
359	/// map.insert("other".try_into().unwrap(), "bar".try_into().unwrap(), "value".try_into().unwrap());
360	/// let data: Vec<_> = map.values_mut().collect();
361	/// let str_data: Vec<&str> = data.iter().map(|x| x.as_str()).collect();
362	/// assert_eq!(&str_data, &["value", "value", "value"]);
363	/// ```
364	#[inline(always)]
365	pub fn values_mut(&mut self) -> ValuesMut<'_, V> {
366		ValuesMut::new(self.inner.values_mut())
367	}
368
369	/// Returns the number of attributes in the map.
370	///
371	/// # Example
372	///
373	/// ```
374	/// # use rxml::{AttrMap, Namespace, NcName};
375	/// let mut map = AttrMap::new();
376	/// assert!(map.is_empty());
377	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "hello".try_into().unwrap());
378	/// assert_eq!(map.len(), 1);
379	/// ```
380	#[inline(always)]
381	pub fn len(&self) -> usize {
382		self.inner.values().map(|x| x.len()).sum::<usize>()
383	}
384
385	/// Returns true if the map is empty.
386	///
387	/// # Example
388	///
389	/// ```
390	/// # use rxml::{AttrMap, Namespace, NcName};
391	/// let mut map = AttrMap::new();
392	/// assert!(map.is_empty());
393	/// map.insert(Namespace::NONE, "bar".try_into().unwrap(), "hello".try_into().unwrap());
394	/// assert!(!map.is_empty());
395	/// ```
396	pub fn is_empty(&self) -> bool {
397		self.inner.is_empty() || self.inner.values().all(|x| x.is_empty())
398	}
399
400	/// Gets the given key’s corresponding entry in the map for in-place
401	/// manipulation.
402	pub fn entry(&mut self, namespace: Namespace, name: NcName) -> Entry<'_, V> {
403		match self.inner.entry(namespace) {
404			btree_map::Entry::Vacant(entry) => {
405				Entry::Vacant(VacantEntry(VacantInner::OuterVacant { entry, name }))
406			}
407			btree_map::Entry::Occupied(entry) => {
408				let namespace = entry.key().clone();
409				match entry.into_mut().entry(name) {
410					btree_map::Entry::Vacant(entry) => {
411						Entry::Vacant(VacantEntry(VacantInner::InnerVacant { namespace, entry }))
412					}
413					btree_map::Entry::Occupied(entry) => {
414						Entry::Occupied(OccupiedEntry { namespace, entry })
415					}
416				}
417			}
418		}
419	}
420}
421
422impl<V: fmt::Debug> fmt::Debug for XmlMap<V> {
423	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
424		f.debug_map().entries(self.iter()).finish()
425	}
426}
427
428impl<V: PartialEq> PartialEq for XmlMap<V> {
429	fn eq(&self, other: &XmlMap<V>) -> bool {
430		if self.len() != other.len() {
431			return false;
432		}
433		for (lhs, rhs) in self.iter().zip(other.iter()) {
434			if lhs != rhs {
435				return false;
436			}
437		}
438		true
439	}
440}
441
442impl<V: Eq> Eq for XmlMap<V> {}
443
444/// A view into an occupied entry in a `XmlMap`.
445///
446/// It is part of the [`Entry`] enum.
447pub struct OccupiedEntry<'a, V> {
448	namespace: Namespace,
449	entry: btree_map::OccupiedEntry<'a, NcName, V>,
450}
451
452impl<'a, V> OccupiedEntry<'a, V> {
453	/// Gets a reference to the value in the entry.
454	#[inline(always)]
455	pub fn get(&self) -> &V {
456		self.entry.get()
457	}
458
459	/// Gets a mutable reference to the value in the entry.
460	#[inline(always)]
461	pub fn get_mut(&mut self) -> &mut V {
462		self.entry.get_mut()
463	}
464
465	/// Sets the value of the entry with the `OccupiedEntry`'s key, and
466	/// returns the entry's old value.
467	#[inline(always)]
468	pub fn insert(&mut self, value: V) -> V {
469		self.entry.insert(value)
470	}
471
472	/// Converts the entry into a mutable reference to its value.
473	///
474	/// If you need multiple references to the `OccupiedEntry`, see
475	/// [`get_mut`][`Self::get_mut`].
476	#[inline(always)]
477	pub fn into_mut(self) -> &'a mut V {
478		self.entry.into_mut()
479	}
480
481	/// Gets a reference to the value in the entry.
482	#[inline(always)]
483	pub fn key(&self) -> (&Namespace, &NcName) {
484		(&self.namespace, self.entry.key())
485	}
486
487	/// Takes the value of the entry out of the map, and returns it.
488	#[inline(always)]
489	pub fn remove(self) -> V {
490		// XXX: this does not remove the parent map if it now is empty, unlike
491		// other removal methods.
492		self.entry.remove()
493	}
494
495	/// Takes ownership of the attribute namespace, name and value
496	/// from the map.
497	#[inline(always)]
498	pub fn remove_entry(self) -> ((Namespace, NcName), V) {
499		// XXX: this does not remove the parent map if it now is empty, unlike
500		// other removal methods.
501		let (name, value) = self.entry.remove_entry();
502		((self.namespace, name), value)
503	}
504}
505
506enum VacantInner<'a, V> {
507	OuterVacant {
508		entry: btree_map::VacantEntry<'a, Namespace, BTreeMap<NcName, V>>,
509		name: NcName,
510	},
511	InnerVacant {
512		namespace: Namespace,
513		entry: btree_map::VacantEntry<'a, NcName, V>,
514	},
515}
516
517/// A view into a vacant entry in a `XmlMap`.
518///
519/// It is part of the [`Entry`] enum.
520pub struct VacantEntry<'a, V>(VacantInner<'a, V>);
521
522impl<'a, V> VacantEntry<'a, V> {
523	/// Gets a reference to the key that would be used when inserting a value
524	/// through the VacantEntry.
525	pub fn key(&self) -> (&Namespace, &NcName) {
526		match self.0 {
527			VacantInner::OuterVacant {
528				ref entry,
529				ref name,
530			} => (entry.key(), name),
531			VacantInner::InnerVacant {
532				ref namespace,
533				ref entry,
534			} => (namespace, entry.key()),
535		}
536	}
537
538	/// Takes ownership of the key.
539	pub fn into_key(self) -> (Namespace, NcName) {
540		match self.0 {
541			VacantInner::OuterVacant { entry, name } => (entry.into_key(), name),
542			VacantInner::InnerVacant { namespace, entry } => (namespace, entry.into_key()),
543		}
544	}
545
546	/// Sets the value of the entry with the `VacantEntry`'s attribute, and
547	/// returns a mutable reference to its value.
548	pub fn insert(self, value: V) -> &'a mut V {
549		match self.0 {
550			VacantInner::OuterVacant { entry, name } => {
551				let map = entry.insert(BTreeMap::new());
552				match map.entry(name) {
553					btree_map::Entry::Vacant(v) => v.insert(value),
554					_ => unreachable!(),
555				}
556			}
557			VacantInner::InnerVacant { entry, .. } => entry.insert(value),
558		}
559	}
560}
561
562/// A view into a single entry in an [`XmlMap`], which may either be vacant
563/// or occupied.
564///
565/// This `enum` is constructed from the [`XmlMap::entry`] method.
566pub enum Entry<'a, V> {
567	/// A vacant entry.
568	Vacant(VacantEntry<'a, V>),
569
570	/// An occupied entry.
571	Occupied(OccupiedEntry<'a, V>),
572}
573
574/// An owning iterator over the entries of an `XmlMap`.
575///
576/// This struct is created by the [`into_iter`][`IntoIterator::into_iter`]
577/// method on the `XmlMap`.
578pub struct IntoIter<V> {
579	outer: btree_map::IntoIter<Namespace, BTreeMap<NcName, V>>,
580	inner: Option<(Namespace, btree_map::IntoIter<NcName, V>)>,
581}
582
583impl<V> IntoIter<V> {
584	fn new(mut outer: btree_map::IntoIter<Namespace, BTreeMap<NcName, V>>) -> Self {
585		let inner = Self::fix_inner(outer.next());
586		Self { outer, inner }
587	}
588
589	fn fix_inner(
590		inner: Option<(Namespace, BTreeMap<NcName, V>)>,
591	) -> Option<(Namespace, btree_map::IntoIter<NcName, V>)> {
592		match inner {
593			Some((mut ns, map)) => {
594				ns.make_shared();
595				Some((ns, map.into_iter()))
596			}
597			None => None,
598		}
599	}
600}
601
602impl<V> Iterator for IntoIter<V> {
603	type Item = ((Namespace, NcName), V);
604
605	fn next(&mut self) -> Option<Self::Item> {
606		loop {
607			if let Some((namespace, inner)) = self.inner.as_mut() {
608				if let Some((name, value)) = inner.next() {
609					return Some(((namespace.clone(), name), value));
610				}
611				self.inner = Self::fix_inner(self.outer.next());
612			} else {
613				return None;
614			}
615		}
616	}
617}
618
619impl<V> IntoIterator for XmlMap<V> {
620	type IntoIter = IntoIter<V>;
621	type Item = ((Namespace, NcName), V);
622
623	fn into_iter(self) -> Self::IntoIter {
624		IntoIter::new(self.inner.into_iter())
625	}
626}
627
628/// An iterator over the entries of an `XmlMap`.
629///
630/// This struct is created by the [`XmlMap::iter`] method.
631pub struct Iter<'a, V> {
632	outer: btree_map::Iter<'a, Namespace, BTreeMap<NcName, V>>,
633	inner: Option<(&'a Namespace, btree_map::Iter<'a, NcName, V>)>,
634}
635
636impl<'a, V> Iter<'a, V> {
637	fn new(mut outer: btree_map::Iter<'a, Namespace, BTreeMap<NcName, V>>) -> Self {
638		let inner = outer.next().map(|(ns, inner)| (ns, inner.iter()));
639		Self { outer, inner }
640	}
641}
642
643impl<'a, V> Iterator for Iter<'a, V> {
644	type Item = ((&'a Namespace, &'a NcName), &'a V);
645
646	fn next(&mut self) -> Option<Self::Item> {
647		loop {
648			if let Some((namespace, inner)) = self.inner.as_mut() {
649				if let Some((name, value)) = inner.next() {
650					return Some(((namespace, name), value));
651				}
652				self.inner = self.outer.next().map(|(ns, inner)| (ns, inner.iter()));
653			} else {
654				return None;
655			}
656		}
657	}
658}
659
660impl<'a, V> IntoIterator for &'a XmlMap<V> {
661	type IntoIter = Iter<'a, V>;
662	type Item = ((&'a Namespace, &'a NcName), &'a V);
663
664	fn into_iter(self) -> Self::IntoIter {
665		Iter::new(self.inner.iter())
666	}
667}
668
669/// A mutable iterator over the entries of an `XmlMap`.
670///
671/// This struct is created by the [`XmlMap::iter_mut`] method.
672pub struct IterMut<'a, V> {
673	outer: btree_map::IterMut<'a, Namespace, BTreeMap<NcName, V>>,
674	inner: Option<(&'a Namespace, btree_map::IterMut<'a, NcName, V>)>,
675}
676
677impl<'a, V> IterMut<'a, V> {
678	fn new(mut outer: btree_map::IterMut<'a, Namespace, BTreeMap<NcName, V>>) -> Self {
679		let inner = outer.next().map(|(ns, inner)| (ns, inner.iter_mut()));
680		Self { outer, inner }
681	}
682}
683
684impl<'a, V> Iterator for IterMut<'a, V> {
685	type Item = ((&'a Namespace, &'a NcName), &'a mut V);
686
687	fn next(&mut self) -> Option<Self::Item> {
688		loop {
689			if let Some((namespace, inner)) = self.inner.as_mut() {
690				if let Some((name, value)) = inner.next() {
691					return Some(((namespace, name), value));
692				}
693				self.inner = self.outer.next().map(|(ns, inner)| (ns, inner.iter_mut()));
694			} else {
695				return None;
696			}
697		}
698	}
699}
700
701impl<'a, V> IntoIterator for &'a mut XmlMap<V> {
702	type IntoIter = IterMut<'a, V>;
703	type Item = ((&'a Namespace, &'a NcName), &'a mut V);
704
705	fn into_iter(self) -> Self::IntoIter {
706		IterMut::new(self.inner.iter_mut())
707	}
708}
709
710/// A iterator over the attribute namespaces and names of an `XmlMap`.
711///
712/// This struct is created by the [`XmlMap::names`] method.
713pub struct Names<'a, V> {
714	outer: btree_map::Iter<'a, Namespace, BTreeMap<NcName, V>>,
715	inner: Option<(&'a Namespace, btree_map::Keys<'a, NcName, V>)>,
716}
717
718impl<'a, V> Names<'a, V> {
719	fn new(mut outer: btree_map::Iter<'a, Namespace, BTreeMap<NcName, V>>) -> Self {
720		let inner = outer.next().map(|(ns, inner)| (ns, inner.keys()));
721		Self { outer, inner }
722	}
723}
724
725impl<'a, V> Iterator for Names<'a, V> {
726	type Item = (&'a Namespace, &'a NcName);
727
728	fn next(&mut self) -> Option<Self::Item> {
729		loop {
730			if let Some((namespace, inner)) = self.inner.as_mut() {
731				if let Some(name) = inner.next() {
732					return Some((namespace, name));
733				}
734				self.inner = self.outer.next().map(|(ns, inner)| (ns, inner.keys()));
735			} else {
736				return None;
737			}
738		}
739	}
740}
741
742/// A iterator over the attribute values of an `XmlMap`.
743///
744/// This struct is created by the [`XmlMap::values`] method.
745pub struct Values<'a, V> {
746	outer: btree_map::Values<'a, Namespace, BTreeMap<NcName, V>>,
747	inner: Option<btree_map::Values<'a, NcName, V>>,
748}
749
750impl<'a, V> Values<'a, V> {
751	fn new(mut outer: btree_map::Values<'a, Namespace, BTreeMap<NcName, V>>) -> Self {
752		let inner = outer.next().map(|inner| inner.values());
753		Self { outer, inner }
754	}
755}
756
757impl<'a, V> Iterator for Values<'a, V> {
758	type Item = &'a V;
759
760	fn next(&mut self) -> Option<Self::Item> {
761		loop {
762			if let Some(inner) = self.inner.as_mut() {
763				if let Some(value) = inner.next() {
764					return Some(value);
765				}
766				self.inner = self.outer.next().map(|inner| inner.values());
767			} else {
768				return None;
769			}
770		}
771	}
772}
773
774/// A mutable iterator over the attribute values of an `XmlMap`.
775///
776/// This struct is created by the [`XmlMap::values_mut`] method.
777pub struct ValuesMut<'a, V> {
778	outer: btree_map::ValuesMut<'a, Namespace, BTreeMap<NcName, V>>,
779	inner: Option<btree_map::ValuesMut<'a, NcName, V>>,
780}
781
782impl<'a, V> ValuesMut<'a, V> {
783	fn new(mut outer: btree_map::ValuesMut<'a, Namespace, BTreeMap<NcName, V>>) -> Self {
784		let inner = outer.next().map(|inner| inner.values_mut());
785		Self { outer, inner }
786	}
787}
788
789impl<'a, V> Iterator for ValuesMut<'a, V> {
790	type Item = &'a mut V;
791
792	fn next(&mut self) -> Option<Self::Item> {
793		loop {
794			if let Some(inner) = self.inner.as_mut() {
795				if let Some(value) = inner.next() {
796					return Some(value);
797				}
798				self.inner = self.outer.next().map(|inner| inner.values_mut());
799			} else {
800				return None;
801			}
802		}
803	}
804}
805
806/// An owning iterator over the attribute namespaces and names of an
807/// `XmlMap`.
808///
809/// This struct is created by the [`XmlMap::into_names`] method.
810pub struct IntoNames<V> {
811	outer: btree_map::IntoIter<Namespace, BTreeMap<NcName, V>>,
812	inner: Option<(Namespace, btree_map::IntoKeys<NcName, V>)>,
813}
814
815impl<V> IntoNames<V> {
816	fn new(mut outer: btree_map::IntoIter<Namespace, BTreeMap<NcName, V>>) -> Self {
817		let inner = Self::fix_inner(outer.next());
818		Self { outer, inner }
819	}
820
821	fn fix_inner(
822		inner: Option<(Namespace, BTreeMap<NcName, V>)>,
823	) -> Option<(Namespace, btree_map::IntoKeys<NcName, V>)> {
824		match inner {
825			Some((mut ns, map)) => {
826				ns.make_shared();
827				Some((ns, map.into_keys()))
828			}
829			None => None,
830		}
831	}
832}
833
834impl<V> Iterator for IntoNames<V> {
835	type Item = (Namespace, NcName);
836
837	fn next(&mut self) -> Option<Self::Item> {
838		loop {
839			if let Some((namespace, inner)) = self.inner.as_mut() {
840				if let Some(name) = inner.next() {
841					return Some((namespace.clone(), name));
842				}
843				self.inner = Self::fix_inner(self.outer.next());
844			} else {
845				return None;
846			}
847		}
848	}
849}
850
851/// An owning iterator over the attribute values of an `XmlMap`.
852///
853/// This struct is created by the [`XmlMap::into_values`] method.
854pub struct IntoValues<V> {
855	outer: btree_map::IntoValues<Namespace, BTreeMap<NcName, V>>,
856	inner: Option<btree_map::IntoValues<NcName, V>>,
857}
858
859impl<V> IntoValues<V> {
860	fn new(mut outer: btree_map::IntoValues<Namespace, BTreeMap<NcName, V>>) -> Self {
861		let inner = outer.next().map(|inner| inner.into_values());
862		Self { outer, inner }
863	}
864}
865
866impl<V> Iterator for IntoValues<V> {
867	type Item = V;
868
869	fn next(&mut self) -> Option<Self::Item> {
870		loop {
871			if let Some(inner) = self.inner.as_mut() {
872				if let Some(value) = inner.next() {
873					return Some(value);
874				}
875				self.inner = self.outer.next().map(|inner| inner.into_values());
876			} else {
877				return None;
878			}
879		}
880	}
881}
882
883impl<V> FromIterator<(Namespace, NcName, V)> for XmlMap<V> {
884	fn from_iter<T>(iter: T) -> Self
885	where
886		T: IntoIterator<Item = (Namespace, NcName, V)>,
887	{
888		let mut result = Self::new();
889		result.extend(iter);
890		result
891	}
892}
893
894impl<V> Extend<(Namespace, NcName, V)> for XmlMap<V> {
895	fn extend<T>(&mut self, iter: T)
896	where
897		T: IntoIterator<Item = (Namespace, NcName, V)>,
898	{
899		for (ns, name, v) in iter {
900			self.insert(ns, name, v);
901		}
902	}
903}
904
905impl<V> FromIterator<((Namespace, NcName), V)> for XmlMap<V> {
906	fn from_iter<T>(iter: T) -> Self
907	where
908		T: IntoIterator<Item = ((Namespace, NcName), V)>,
909	{
910		let mut result = Self::new();
911		result.extend(iter);
912		result
913	}
914}
915
916impl<V> Extend<((Namespace, NcName), V)> for XmlMap<V> {
917	fn extend<T>(&mut self, iter: T)
918	where
919		T: IntoIterator<Item = ((Namespace, NcName), V)>,
920	{
921		for ((ns, name), v) in iter {
922			self.insert(ns, name, v);
923		}
924	}
925}
926
927#[cfg(test)]
928mod tests {
929	use super::*;
930
931	#[test]
932	fn xml_map_get_does_not_borrow_namespace_or_name() {
933		fn foo<'a>(map: &'a AttrMap, ns: Namespace, name: NcName) -> Option<&'a String> {
934			map.get(&ns, &name)
935		}
936
937		let map = AttrMap::new();
938		foo(&map, Namespace::NONE, NcName::try_from("foo").unwrap());
939	}
940
941	#[test]
942	fn xml_map_get_mut_does_not_borrow_namespace_or_name() {
943		fn foo<'a>(map: &'a mut AttrMap, ns: Namespace, name: NcName) -> Option<&'a mut String> {
944			map.get_mut(&ns, &name)
945		}
946
947		let mut map = AttrMap::new();
948		foo(&mut map, Namespace::NONE, NcName::try_from("foo").unwrap());
949	}
950}