ridx_syntax/name_res/
ident_key.rs1use std::borrow::Borrow;
15use std::fmt;
16use std::hash::{Hash, Hasher};
17use std::ops::Deref;
18
19const INLINE_CAP: usize = 30;
20
21#[derive(Clone)]
23pub enum IdentKey {
24 Inline { len: u8, buf: [u8; INLINE_CAP] },
25 Heap(Box<str>),
26}
27
28impl IdentKey {
29 #[inline]
30 pub fn new(s: &str) -> Self {
31 let bytes = s.as_bytes();
32 if bytes.len() <= INLINE_CAP {
33 let mut buf = [0u8; INLINE_CAP];
34 buf[..bytes.len()].copy_from_slice(bytes);
35 Self::Inline { len: bytes.len() as u8, buf }
36 } else {
37 Self::Heap(s.into())
38 }
39 }
40
41 #[inline]
42 pub fn as_bytes(&self) -> &[u8] {
43 match self {
44 Self::Inline { len, buf } => &buf[..*len as usize],
45 Self::Heap(b) => b.as_bytes(),
46 }
47 }
48
49 #[inline]
50 pub fn as_str(&self) -> &str {
51 match self {
52 Self::Inline { len, buf } => std::str::from_utf8(&buf[..*len as usize]).unwrap_or(""),
53 Self::Heap(b) => b,
54 }
55 }
56}
57
58impl From<&str> for IdentKey {
59 #[inline]
60 fn from(s: &str) -> Self {
61 Self::new(s)
62 }
63}
64
65impl From<String> for IdentKey {
66 #[inline]
67 fn from(s: String) -> Self {
68 if s.len() <= INLINE_CAP {
69 Self::new(&s)
70 } else {
71 Self::Heap(s.into_boxed_str())
72 }
73 }
74}
75
76impl Deref for IdentKey {
77 type Target = str;
78
79 #[inline]
80 fn deref(&self) -> &str {
81 self.as_str()
82 }
83}
84
85impl AsRef<str> for IdentKey {
86 #[inline]
87 fn as_ref(&self) -> &str {
88 self.as_str()
89 }
90}
91
92impl Borrow<str> for IdentKey {
93 #[inline]
94 fn borrow(&self) -> &str {
95 self.as_str()
96 }
97}
98
99impl PartialEq for IdentKey {
100 #[inline]
101 fn eq(&self, other: &Self) -> bool {
102 self.as_bytes() == other.as_bytes()
103 }
104}
105
106impl Eq for IdentKey {}
107
108impl PartialEq<str> for IdentKey {
109 #[inline]
110 fn eq(&self, other: &str) -> bool {
111 self.as_bytes() == other.as_bytes()
112 }
113}
114
115impl PartialEq<&str> for IdentKey {
116 #[inline]
117 fn eq(&self, other: &&str) -> bool {
118 self.as_bytes() == other.as_bytes()
119 }
120}
121
122impl Hash for IdentKey {
123 #[inline]
124 fn hash<H: Hasher>(&self, state: &mut H) {
125 state.write(self.as_bytes());
126 state.write_u8(0xff);
127 }
128}
129
130impl fmt::Debug for IdentKey {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 fmt::Debug::fmt(self.as_str(), f)
133 }
134}
135
136impl fmt::Display for IdentKey {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 fmt::Display::fmt(self.as_str(), f)
139 }
140}