json_ld_syntax_next/
compact_iri.rs

1use iref::{IriRef, IriRefBuf};
2
3pub struct InvalidCompactIri<T>(pub T);
4
5#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
6pub struct CompactIri(str);
7
8impl CompactIri {
9	pub fn new(s: &str) -> Result<&Self, InvalidCompactIri<&str>> {
10		match s.split_once(':') {
11			Some((prefix, suffix)) if prefix != "_" && !suffix.starts_with("//") => {
12				match IriRef::new(s) {
13					Ok(_) => Ok(unsafe { Self::new_unchecked(s) }),
14					Err(_) => Err(InvalidCompactIri(s)),
15				}
16			}
17			_ => Err(InvalidCompactIri(s)),
18		}
19	}
20
21	/// Creates a new compact IRI without parsing it.
22	///
23	/// # Safety
24	///
25	/// The input string must be a compact IRI.
26	pub unsafe fn new_unchecked(s: &str) -> &Self {
27		std::mem::transmute(s)
28	}
29
30	pub fn as_str(&self) -> &str {
31		&self.0
32	}
33
34	pub fn to_owned(&self) -> CompactIriBuf {
35		CompactIriBuf(self.0.to_owned())
36	}
37
38	pub fn prefix(&self) -> &str {
39		let i = self.find(':').unwrap();
40		&self[0..i]
41	}
42
43	pub fn suffix(&self) -> &str {
44		let i = self.find(':').unwrap();
45		&self[i + 1..]
46	}
47
48	pub fn as_iri_ref(&self) -> &IriRef {
49		IriRef::new(self.as_str()).unwrap()
50	}
51}
52
53impl std::ops::Deref for CompactIri {
54	type Target = str;
55
56	fn deref(&self) -> &str {
57		&self.0
58	}
59}
60
61impl std::borrow::Borrow<str> for CompactIri {
62	fn borrow(&self) -> &str {
63		&self.0
64	}
65}
66
67impl AsRef<str> for CompactIri {
68	fn as_ref(&self) -> &str {
69		&self.0
70	}
71}
72
73#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
74pub struct CompactIriBuf(String);
75
76impl CompactIriBuf {
77	pub fn new(s: String) -> Result<Self, InvalidCompactIri<String>> {
78		match CompactIri::new(&s) {
79			Ok(_) => Ok(unsafe { Self::new_unchecked(s) }),
80			Err(_) => Err(InvalidCompactIri(s)),
81		}
82	}
83
84	/// Creates a new compact IRI without parsing it.
85	///
86	/// # Safety
87	///
88	/// The input string must be a compact IRI.
89	pub unsafe fn new_unchecked(s: String) -> Self {
90		Self(s)
91	}
92
93	pub fn as_compact_iri(&self) -> &CompactIri {
94		unsafe { CompactIri::new_unchecked(&self.0) }
95	}
96
97	pub fn into_iri_ref(self) -> IriRefBuf {
98		IriRefBuf::new(self.0).unwrap()
99	}
100
101	pub fn into_string(self) -> String {
102		self.0
103	}
104}
105
106impl std::borrow::Borrow<CompactIri> for CompactIriBuf {
107	fn borrow(&self) -> &CompactIri {
108		self.as_compact_iri()
109	}
110}
111
112impl std::ops::Deref for CompactIriBuf {
113	type Target = CompactIri;
114
115	fn deref(&self) -> &CompactIri {
116		self.as_compact_iri()
117	}
118}