iref_core/iri/
fragment.rs

1use pct_str::{PctStr, PctString};
2use std::{
3	cmp,
4	hash::{self, Hash},
5	ops,
6};
7
8use static_regular_grammar::RegularGrammar;
9
10use crate::common::FragmentImpl;
11
12/// IRI fragment.
13#[derive(RegularGrammar)]
14#[grammar(
15	file = "src/iri/grammar.abnf",
16	entry_point = "ifragment",
17	name = "IRI fragment",
18	no_deref,
19	cache = "automata/iri/fragment.aut.cbor"
20)]
21#[grammar(sized(
22	FragmentBuf,
23	derive(Debug, Display, PartialEq, Eq, PartialOrd, Ord, Hash)
24))]
25#[cfg_attr(feature = "serde", grammar(serde))]
26#[cfg_attr(feature = "ignore-grammars", grammar(disable))]
27pub struct Fragment(str);
28
29impl FragmentImpl for Fragment {
30	unsafe fn new_unchecked(bytes: &[u8]) -> &Self {
31		Self::new_unchecked(std::str::from_utf8_unchecked(bytes))
32	}
33
34	fn as_bytes(&self) -> &[u8] {
35		self.0.as_bytes()
36	}
37}
38
39impl Fragment {
40	/// Returns the fragment as a percent-encoded string slice.
41	#[inline]
42	pub fn as_pct_str(&self) -> &PctStr {
43		unsafe { PctStr::new_unchecked(self.as_str()) }
44	}
45}
46
47impl ops::Deref for Fragment {
48	type Target = PctStr;
49
50	fn deref(&self) -> &Self::Target {
51		self.as_pct_str()
52	}
53}
54
55impl cmp::PartialEq for Fragment {
56	#[inline]
57	fn eq(&self, other: &Fragment) -> bool {
58		self.as_pct_str() == other.as_pct_str()
59	}
60}
61
62impl Eq for Fragment {}
63
64impl<'a> PartialEq<&'a str> for Fragment {
65	#[inline]
66	fn eq(&self, other: &&'a str) -> bool {
67		self.as_str() == *other
68	}
69}
70
71impl PartialOrd for Fragment {
72	#[inline]
73	fn partial_cmp(&self, other: &Fragment) -> Option<cmp::Ordering> {
74		Some(self.cmp(other))
75	}
76}
77
78impl Ord for Fragment {
79	#[inline]
80	fn cmp(&self, other: &Fragment) -> cmp::Ordering {
81		self.as_pct_str().cmp(other.as_pct_str())
82	}
83}
84
85impl Hash for Fragment {
86	#[inline]
87	fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
88		self.as_pct_str().hash(hasher)
89	}
90}
91
92impl FragmentBuf {
93	pub fn into_pct_string(self) -> PctString {
94		unsafe { PctString::new_unchecked(self.0) }
95	}
96}