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(Self::Err::from).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        Ok(UriReference(s.0))
33    }
34}
35
36impl TryFrom<&str> for UriReference {
37    type Error = crate::Error;
38
39    fn try_from(s: &str) -> Result<Self, Self::Error> {
40        fluent_uri::UriRef::parse(s.to_owned()).map_err(Self::Error::from).map(UriReference)
41    }
42}
43
44impl TryFrom<String> for UriReference {
45    type Error = crate::Error;
46
47    fn try_from(s: String) -> Result<Self, Self::Error> {
48        fluent_uri::UriRef::parse(s).map_err(Self::Error::from).map(UriReference)
49    }
50}
51
52impl std::fmt::Display for UriReference {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        self.0.as_str().fmt(f)
55    }
56}
57
58impl UriReference {
59    pub fn as_str(&self) -> &str {
60        self.0.as_str()
61    }
62}
63
64// impl From<UriReference> for fluent_uri::UriRef<String> {
65//     fn from(uri: UriReference) -> Self {
66//         uri.0
67//     }
68// }
69
70#[cfg(feature = "testkit")]
71impl<> proptest::arbitrary::Arbitrary for UriReference {
72    type Parameters = ();
73    type Strategy = proptest::strategy::BoxedStrategy<Self>;
74
75    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
76        use proptest::prelude::*;
77        (prop_oneof![
78            "\\/[a-z_\\-\\/]+".prop_map(|s| UriReference::from_str(&s).unwrap()),
79            Just("https://example.com/").prop_map(|s| UriReference::from_str(s).unwrap()),
80        ]).boxed()
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use proptest::prelude::*;
87    use super::*;
88
89    proptest! {
90        #[test]
91        #[cfg(feature = "testkit")]
92        fn arbitraries_are_json_valid(s in any::<UriReference>()) {
93            let json_str = serde_json::to_string(&s).unwrap();
94            let actual = serde_json::from_str::<UriReference>(&json_str).unwrap();
95            assert_eq!(s, actual);
96        }
97    }
98}