-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_iri.rs
More file actions
109 lines (91 loc) · 2.71 KB
/
_iri.rs
File metadata and controls
109 lines (91 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use std::borrow::Cow;
/// Wrapper around a [`Cow<str>`] guaranteeing that the underlying text satisfies [RFC3987].
///
/// [RFC3987]: https://datatracker.ietf.org/doc/rfc3987/
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Iri<'a>(Cow<'a, str>);
impl<'a> Iri<'a> {
/// Return a new [`Iri`], assuming the argument is a valid IRI.
pub fn new_unchecked(txt: impl Into<Cow<'a, str>>) -> Self {
Iri(txt.into())
}
/// Return the inner [`Cow<str>`](Cow).
pub fn unwrap(self) -> Cow<'a, str> {
self.0
}
/// Apply a function to the inner txt, assuming the result of the function is still a valid IRI.
pub fn unchecked_map(self, mut f: impl FnMut(Cow<'a, str>) -> Cow<'a, str>) -> Self {
Self(f(self.0))
}
/// Borrow this [`Iri`] as another [`Iri`].
pub fn borrowed(&self) -> Iri<'_> {
Iri::new_unchecked(self.as_ref())
}
}
impl std::borrow::Borrow<str> for Iri<'_> {
fn borrow(&self) -> &str {
self.0.as_ref()
}
}
impl std::convert::AsRef<str> for Iri<'_> {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl std::ops::Deref for Iri<'_> {
type Target = str;
fn deref(&self) -> &Self::Target {
self.0.as_ref()
}
}
impl std::cmp::PartialEq<&str> for Iri<'_> {
fn eq(&self, other: &&str) -> bool {
self.0.as_ref() == *other
}
}
impl std::cmp::PartialEq<Iri<'_>> for &str {
fn eq(&self, other: &Iri) -> bool {
*self == other.0.as_ref()
}
}
impl std::cmp::PartialOrd<&str> for Iri<'_> {
fn partial_cmp(&self, other: &&str) -> Option<std::cmp::Ordering> {
Some(self.0.as_ref().cmp(other))
}
}
impl std::cmp::PartialOrd<Iri<'_>> for &str {
fn partial_cmp(&self, other: &Iri<'_>) -> Option<std::cmp::Ordering> {
Some(self.cmp(&other.0.as_ref()))
}
}
impl std::fmt::Display for Iri<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "<{}>", self.0.as_ref())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn as_str() {
let ex = "http://example.org/foo/bar";
let iri1 = Iri::new_unchecked(ex.to_string());
assert!(iri1.starts_with("http:"));
assert_eq!(iri1, ex);
assert_eq!(ex, iri1);
assert!("http:" < iri1 && iri1 < "i");
}
#[test]
fn borrowed() {
let ex = "http://example.org/foo/bar";
let iri1 = Iri::new_unchecked(ex.to_string());
let iri2 = iri1.borrowed();
assert_eq!(iri1, iri2);
}
#[test]
fn display() {
let ex = "http://example.org/foo/bar";
let iri1 = Iri::new_unchecked(ex.to_string());
assert_eq!(iri1.to_string(), format!("<{ex}>"));
}
}