xml_data/parser/
value.rs

1use crate::{
2	Result,
3};
4use std::borrow::Cow;
5
6/// Trait to parse attributes and inner text
7///
8/// This is implemented my "marker" types to decide how to parse a type (the same type can be
9/// parsed differently depending on the marker type)
10pub trait Value<T> {
11	/// Serialize value to text
12	fn parse_value(text: Cow<'_, str>) -> Result<T>;
13}
14
15/// Implements `Value` for all types implementing `std::str::FromStr`; this is a good default.
16pub struct ValueDefault;
17
18impl<T> Value<T> for ValueDefault
19where
20	T: std::str::FromStr,
21	T::Err: std::error::Error + 'static,
22{
23	fn parse_value(text: Cow<'_, str>) -> Result<T> {
24		Ok(text.parse::<T>()?)
25	}
26}
27
28/// Implements `Value` for `String` and `Cow<str>`.
29pub struct ValueString;
30
31impl Value<String> for ValueString {
32	fn parse_value(text: Cow<'_, str>) -> Result<String> {
33		Ok(text.into_owned())
34	}
35}
36
37impl<'a> Value<Cow<'a, str>> for ValueString {
38	fn parse_value(text: Cow<'_, str>) -> Result<Cow<'a, str>> {
39		Ok(Cow::Owned(text.into_owned()))
40	}
41}