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
110
111
112
113
114
use iref::{IriRef, IriRefBuf};

pub struct InvalidCompactIri<T>(pub T);

#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct CompactIri(str);

impl CompactIri {
	pub fn new(s: &str) -> Result<&Self, InvalidCompactIri<&str>> {
		match s.split_once(':') {
			Some((prefix, suffix)) if prefix != "_" && !suffix.starts_with("//") => {
				match IriRef::new(s) {
					Ok(_) => Ok(unsafe { Self::new_unchecked(s) }),
					Err(_) => Err(InvalidCompactIri(s)),
				}
			}
			_ => Err(InvalidCompactIri(s)),
		}
	}

	/// Creates a new compact IRI without parsing it.
	///
	/// # Safety
	///
	/// The input string must be a compact IRI.
	pub unsafe fn new_unchecked(s: &str) -> &Self {
		std::mem::transmute(s)
	}

	pub fn as_str(&self) -> &str {
		&self.0
	}

	pub fn to_owned(&self) -> CompactIriBuf {
		CompactIriBuf(self.0.to_owned())
	}

	pub fn prefix(&self) -> &str {
		let i = self.find(':').unwrap();
		&self[0..i]
	}

	pub fn suffix(&self) -> &str {
		let i = self.find(':').unwrap();
		&self[i + 1..]
	}

	pub fn as_iri_ref(&self) -> IriRef {
		IriRef::new(self.as_str()).unwrap()
	}
}

impl std::ops::Deref for CompactIri {
	type Target = str;

	fn deref(&self) -> &str {
		&self.0
	}
}

impl std::borrow::Borrow<str> for CompactIri {
	fn borrow(&self) -> &str {
		&self.0
	}
}

impl AsRef<str> for CompactIri {
	fn as_ref(&self) -> &str {
		&self.0
	}
}

#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct CompactIriBuf(String);

impl CompactIriBuf {
	pub fn new(s: String) -> Result<Self, InvalidCompactIri<String>> {
		match CompactIri::new(&s) {
			Ok(_) => Ok(unsafe { Self::new_unchecked(s) }),
			Err(_) => Err(InvalidCompactIri(s)),
		}
	}

	/// Creates a new compact IRI without parsing it.
	///
	/// # Safety
	///
	/// The input string must be a compact IRI.
	pub unsafe fn new_unchecked(s: String) -> Self {
		Self(s)
	}

	pub fn as_compact_iri(&self) -> &CompactIri {
		unsafe { CompactIri::new_unchecked(&self.0) }
	}

	pub fn into_iri_ref(self) -> IriRefBuf {
		IriRefBuf::from_string(self.0).unwrap()
	}
}

impl std::borrow::Borrow<CompactIri> for CompactIriBuf {
	fn borrow(&self) -> &CompactIri {
		self.as_compact_iri()
	}
}

impl std::ops::Deref for CompactIriBuf {
	type Target = CompactIri;

	fn deref(&self) -> &CompactIri {
		self.as_compact_iri()
	}
}