1extern crate alloc;
4
5use alloc::borrow::{Cow, ToOwned};
6
7use crate::document::constructor::DocumentConstructor;
8use crate::parse::{FromEure, ParseContext, ParseError};
9use crate::write::IntoEure;
10
11pub struct BorrowedCow;
28
29impl<'doc, T> FromEure<'doc, Cow<'doc, T>> for BorrowedCow
30where
31 T: ToOwned + ?Sized,
32 for<'a> &'a T: FromEure<'a>,
33 for<'a> <&'a T as FromEure<'a>>::Error: Into<ParseError>,
34{
35 type Error = ParseError;
36
37 fn parse(ctx: &ParseContext<'doc>) -> Result<Cow<'doc, T>, Self::Error> {
38 ctx.parse::<&'doc T>()
39 .map(Cow::Borrowed)
40 .map_err(Into::into)
41 }
42}
43
44impl<'a, T> IntoEure<Cow<'a, T>> for BorrowedCow
45where
46 T: ToOwned + ?Sized,
47 T::Owned: IntoEure,
48{
49 type Error = <T::Owned as IntoEure>::Error;
50
51 fn write(value: Cow<'a, T>, c: &mut DocumentConstructor) -> Result<(), Self::Error> {
52 <T::Owned as IntoEure>::write(value.into_owned(), c)
53 }
54}
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59 use crate::document::node::NodeValue;
60 use crate::eure;
61 use crate::text::Text;
62 use crate::value::PrimitiveValue;
63
64 #[test]
65 fn test_borrowed_cow_str_from_eure() {
66 let doc = eure!({ name = "hello" });
67 let root_id = doc.get_root_id();
68 let rec = doc.parse_record(root_id).unwrap();
69 let value: Cow<'_, str> = rec.parse_field_with("name", BorrowedCow::parse).unwrap();
70 assert!(matches!(value, Cow::Borrowed(_)));
71 assert_eq!(value, "hello");
72 }
73
74 #[test]
75 fn test_borrowed_cow_str_into_eure() {
76 let mut c = DocumentConstructor::new();
77 let value: Cow<'_, str> = Cow::Borrowed("hello");
78 BorrowedCow::write(value, &mut c).unwrap();
79 let doc = c.finish();
80 assert_eq!(
81 doc.root().content,
82 NodeValue::Primitive(PrimitiveValue::Text(Text::plaintext("hello")))
83 );
84 }
85}