Skip to main content

cdevents_sdk/
uri_reference.rs

1use std::str::FromStr;
2
3use serde::{Serialize, Deserialize};
4use crate::Uri;
5
6#[derive(Debug, Clone, Default, Serialize, Deserialize)]
7pub struct UriReference(
8    //#[serde(with = "crate::serde::fluent_uri")]
9    pub(crate) fluent_uri::UriRef<String>
10);
11
12impl PartialEq for UriReference {
13    fn eq(&self, other: &Self) -> bool {
14        self.0.as_str() == other.0.as_str()
15    }
16}
17
18impl Eq for UriReference {}
19
20impl FromStr for UriReference {
21    type Err = crate::Error;
22
23    fn from_str(s: &str) -> Result<Self, Self::Err> {
24        fluent_uri::UriRef::parse(s.to_owned()).map_err(|(e,_)| Self::Err::from(e)).map(UriReference)
25    }
26}
27
28impl TryFrom<Uri> for UriReference {
29    type Error = crate::Error;
30
31    fn try_from(s: Uri) -> Result<Self, Self::Error> {
32        //fluent_uri::UriRef::try_from(s.0).map_err(Self::Error::from).map(UriReference)
33        Ok(UriReference(s.0))
34    }
35}
36
37impl TryFrom<&str> for UriReference {
38    type Error = crate::Error;
39
40    fn try_from(s: &str) -> Result<Self, Self::Error> {
41        fluent_uri::UriRef::parse(s.to_owned()).map_err(|(e,_)| Self::Error::from(e)).map(UriReference)
42    }
43}
44
45impl TryFrom<String> for UriReference {
46    type Error = crate::Error;
47
48    fn try_from(s: String) -> Result<Self, Self::Error> {
49        fluent_uri::UriRef::parse(s).map_err(|(e,_)| Self::Error::from(e)).map(UriReference)
50    }
51}
52
53impl std::fmt::Display for UriReference {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        self.0.as_str().fmt(f)
56    }
57}
58
59impl UriReference {
60    pub fn as_str(&self) -> &str {
61        self.0.as_str()
62    }
63}
64
65// impl From<UriReference> for fluent_uri::UriRef<String> {
66//     fn from(uri: UriReference) -> Self {
67//         uri.0
68//     }
69// }
70
71#[cfg(feature = "testkit")]
72impl<> proptest::arbitrary::Arbitrary for UriReference {
73    type Parameters = ();
74    type Strategy = proptest::strategy::BoxedStrategy<Self>;
75
76    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
77        use proptest::prelude::*;
78        (prop_oneof![
79            "\\/[a-z_\\-\\/]+".prop_map(|s| UriReference::from_str(&s).unwrap()),
80            Just("https://example.com/").prop_map(|s| UriReference::from_str(s).unwrap()),
81        ]).boxed()
82    }
83}
84
85#[cfg(test)]
86mod tests {
87    use proptest::prelude::*;
88    use super::*;
89
90    proptest! {
91        #[test]
92        #[cfg(feature = "testkit")]
93        fn arbitraries_are_json_valid(s in any::<UriReference>()) {
94            let json_str = serde_json::to_string(&s).unwrap();
95            let actual = serde_json::from_str::<UriReference>(&json_str).unwrap();
96            assert_eq!(s, actual);
97        }
98    }
99}