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