mago_interner/lib.rs
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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
use std::collections::HashSet;
use std::sync::Arc;
use lasso::Key;
use lasso::Rodeo;
use lasso::ThreadedRodeo;
use serde::Deserialize;
use serde::Serialize;
/// An string identifier that is used to represent an interned string.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
pub struct StringIdentifier(pub(crate) usize);
impl StringIdentifier {
/// Creates a new empty `StringIdentifier`.
pub const fn empty() -> Self {
Self(0)
}
/// Creates a new `StringIdentifier`.
///
/// # Arguments
///
/// * `val` - The value of the string identifier.
pub const fn new(val: usize) -> Self {
Self(val)
}
/// Returns `true` if the string is empty.
#[inline(always)]
pub const fn is_empty(&self) -> bool {
self.0 == 0
}
/// Returns the value of the string identifier.
#[inline(always)]
pub const fn value(&self) -> usize {
self.0
}
}
unsafe impl Key for StringIdentifier {
fn into_usize(self) -> usize {
self.0 - 1
}
fn try_from_usize(int: usize) -> Option<Self> {
Some(Self(int + 1))
}
}
#[derive(Debug)]
pub struct Interner {
rodeo: Rodeo<StringIdentifier>,
}
/// A string interner that stores strings and assigns them unique identifiers.
impl Interner {
/// Creates a new `Interner`.
pub fn new() -> Self {
Self { rodeo: Rodeo::new() }
}
/// Returns the number of strings stored in the interner.
pub fn len(&self) -> usize {
self.rodeo.len()
}
/// Returns `true` if the interner is empty.
pub fn is_empty(&self) -> bool {
self.rodeo.is_empty()
}
/// Returns the identifier for the specified interned string.
///
/// # Arguments
///
/// * string - The interned string.
pub fn get(&self, string: impl AsRef<str>) -> Option<StringIdentifier> {
let str = string.as_ref();
if str.is_empty() {
return Some(StringIdentifier::empty());
}
self.rodeo.get(str)
}
/// Interns the specified string, returning the identifier for it.
///
/// If the string is already interned, the existing identifier is returned.
///
/// # Arguments
///
/// * string - The string to intern.
pub fn intern(&mut self, string: impl AsRef<str>) -> StringIdentifier {
let str = string.as_ref();
if str.is_empty() {
return StringIdentifier::empty();
}
self.rodeo.get_or_intern(str)
}
/// Interns a string if it has not already been interned, then returns a reference
/// to the interned string.
///
/// # Arguments
///
/// * `string` - A string or any type that implements `AsRef<str>`, representing the
/// string to intern.
///
/// # Returns
///
/// A reference to the interned version of the string.
///
/// # Panics
///
/// This method will panic if it encounters an invalid identifier. This should never
/// occur unless there is an issue with the identifier or the interner is used
/// incorrectly.
pub fn interned_str(&mut self, string: impl AsRef<str>) -> &str {
let str = string.as_ref();
if str.is_empty() {
return "";
}
let identifier = self.rodeo.get_or_intern(str);
self.rodeo.try_resolve(&identifier).expect(
"invalid string identifier; this should never happen unless the identifier is \
corrupted or the interner is used incorrectly",
)
}
/// Given an identifier, returns the identifier for the same string but with all
/// characters in lowercase.
///
/// # Arguments
///
/// * `identifier` - The identifier of the string to lower.
///
/// # Returns
///
/// The identifier of the string with all characters in lowercase.
pub fn lowered(&mut self, identifier: &StringIdentifier) -> StringIdentifier {
let string = self.lookup(identifier);
self.intern(string.to_ascii_lowercase())
}
/// Returns the interned string for the specified identifier.
///
/// # Arguments
///
/// * identifier - The identifier to look up.
///
/// # Panics
///
/// Panics if the identifier is invalid
pub fn lookup(&self, identifier: &StringIdentifier) -> &str {
if identifier.is_empty() {
return "";
}
self.rodeo.try_resolve(identifier).expect(
"invalid string identifier; this should never happen unless the identifier is \
corrupted or the interner is used incorrectly",
)
}
}
/// A thread-safe interner, allowing multiple threads to concurrently intern strings.
#[derive(Debug, Clone)]
pub struct ThreadedInterner {
rodeo: Arc<ThreadedRodeo<StringIdentifier>>,
}
impl ThreadedInterner {
/// Creates a new `ThreadedInterner`.
pub fn new() -> Self {
Self { rodeo: Arc::new(ThreadedRodeo::new()) }
}
/// Returns the number of strings stored in the interner.
pub fn len(&self) -> usize {
self.rodeo.len()
}
/// Returns `true` if the interner is empty.
pub fn is_empty(&self) -> bool {
self.rodeo.is_empty()
}
/// Interns a string and returns its identifier.
///
/// If the string is already interned, the existing identifier is returned.
///
/// # Arguments
///
/// * `string` - The string to intern.
pub fn intern(&self, string: impl AsRef<str>) -> StringIdentifier {
let str = string.as_ref();
if str.is_empty() {
return StringIdentifier::empty();
}
self.rodeo.get_or_intern(str)
}
/// Interns a string if it has not already been interned, then returns a reference
/// to the interned string.
///
/// # Arguments
///
/// * `string` - A string or any type that implements `AsRef<str>`, representing the
/// string to intern.
///
/// # Returns
///
/// A reference to the interned version of the string.
///
/// # Panics
///
/// This method will panic if it encounters an invalid identifier. This should never
/// occur unless there is an issue with the identifier or the interner is used
/// incorrectly.
pub fn interned_str(&self, string: impl AsRef<str>) -> &str {
let str = string.as_ref();
if str.is_empty() {
return "";
}
let identifier = self.rodeo.get_or_intern(str);
self.rodeo.try_resolve(&identifier).expect(
"invalid string identifier; this should never happen unless the identifier is \
corrupted or the interner is used incorrectly",
)
}
/// Given an identifier, returns the identifier for the same string but with all
/// characters in lowercase.
///
/// # Arguments
///
/// * `identifier` - The identifier of the string to lower.
///
/// # Returns
///
/// The identifier of the string with all characters in lowercase.
pub fn lowered(&self, identifier: &StringIdentifier) -> StringIdentifier {
let string = self.lookup(identifier);
self.intern(string.to_ascii_lowercase())
}
/// Looks up an interned string by its identifier.
///
/// # Arguments
///
/// * `identifier` - The identifier of the interned string to look up.
///
/// # Panics
///
/// This method will panic if it encounters an invalid identifier. This should never
/// occur unless there is an issue with the identifier or the interner is used
/// incorrectly.
pub fn lookup(&self, identifier: &StringIdentifier) -> &str {
if identifier.is_empty() {
return "";
}
self.rodeo.try_resolve(identifier).expect(
"invalid string identifier; this should never happen unless the identifier is \
corrupted or the interner is used incorrectly",
)
}
/// Returns all interned strings and their identifiers as a hashmap.
pub fn all(&self) -> HashSet<(StringIdentifier, &str)> {
self.rodeo.iter().collect()
}
}
impl std::fmt::Display for StringIdentifier {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "string-identifier({})", self.0)
}
}
unsafe impl Send for ThreadedInterner {}
unsafe impl Sync for ThreadedInterner {}
impl std::default::Default for Interner {
fn default() -> Self {
Self::new()
}
}
impl std::default::Default for ThreadedInterner {
fn default() -> Self {
Self::new()
}
}