xml_data/parser/
fixed_element.rs

1use crate::{
2	parser::{
3		ElementState,
4		ElementParser,
5	},
6	Result,
7	errors,
8};
9use std::borrow::Cow;
10
11/// Convenience trait to implement instead of `ElementState` if your element has a fixed tag.
12pub trait FixedElementState: Default {
13	/// Same as `ElementState::Output`
14	type Output: Sized;
15
16	/// Fixed tag
17	const TAG: &'static str;
18
19	/// Same as `ElementState::parse_element_attribute`
20	fn parse_element_attribute(&mut self, key: &str, value: Cow<'_, str>) -> Result<()> {
21		let _ = value;
22		return Err(errors::unexpected_attribute(key));
23	}
24
25	/// Same as `ElementState::parse_element_inner_text`
26	fn parse_element_inner_text(&mut self, text: Cow<'_, str>) -> Result<()> {
27		if !text.trim().is_empty() {
28			return Err(errors::unexpected_text());
29		}
30		Ok(())
31	}
32
33	/// Same as `ElementState::parse_element_inner_node`
34	fn parse_element_inner_node<P: ElementParser>(&mut self, tag: &str, parser: P) -> Result<()> {
35		let _ = parser;
36		return Err(errors::unexpected_element(tag));
37	}
38
39	/// Same as `ElementState::parse_element_finish`
40	fn parse_element_finish(self) -> Result<Self::Output>;
41}
42
43impl<E: FixedElementState> ElementState for E {
44	type Output = <E as FixedElementState>::Output;
45
46	fn parse_element_start(tag: &str) -> Option<Self> {
47		if tag == Self::TAG {
48			Some(E::default())
49		} else {
50			None
51		}
52	}
53
54	fn parse_element_attribute(&mut self, key: &str, value: Cow<'_, str>) -> Result<()> {
55		<E as FixedElementState>::parse_element_attribute(self, key, value)
56	}
57
58	fn parse_element_inner_text(&mut self, text: Cow<'_, str>) -> Result<()> {
59		<E as FixedElementState>::parse_element_inner_text(self, text)
60	}
61
62	fn parse_element_inner_node<P: ElementParser>(&mut self, tag: &str, parser: P) -> Result<()> {
63		<E as FixedElementState>::parse_element_inner_node(self, tag, parser)
64	}
65
66	fn parse_element_finish(self) -> Result<Self::Output> {
67		<E as FixedElementState>::parse_element_finish(self)
68	}
69
70	fn parse_error_not_found<T>() -> Result<T> {
71		Err(errors::missing_element(Self::TAG))
72	}
73}