use crate::{BytesInterner, InternerSymbol, Symbol};
use std::{collections::hash_map::RandomState, hash::BuildHasher};
pub struct Interner<S = Symbol, H = RandomState> {
pub(crate) inner: BytesInterner<S, H>,
}
impl Default for Interner {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl Interner<Symbol, RandomState> {
#[inline]
pub fn new() -> Self {
Self::with_capacity(0)
}
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
Self::with_capacity_and_hasher(capacity, Default::default())
}
}
impl<S: InternerSymbol, H: BuildHasher> Interner<S, H> {
#[inline]
pub fn with_hasher(hash_builder: H) -> Self {
Self::with_capacity_and_hasher(0, hash_builder)
}
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: H) -> Self {
Self { inner: BytesInterner::with_capacity_and_hasher(capacity, hash_builder) }
}
#[inline]
pub fn len(&self) -> usize {
self.inner.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
pub fn iter(&self) -> impl ExactSizeIterator<Item = (S, &str)> + Clone {
self.all_symbols().map(|s| (s, self.resolve(s)))
}
#[inline]
pub fn all_symbols(&self) -> impl ExactSizeIterator<Item = S> + Send + Sync + Clone {
(0..self.len()).map(S::from_usize)
}
pub fn intern(&self, s: &str) -> S {
self.inner.intern(s.as_bytes())
}
pub fn intern_mut(&mut self, s: &str) -> S {
self.inner.intern_mut(s.as_bytes())
}
pub fn intern_static<'a, 'b: 'a>(&'a self, s: &'b str) -> S {
self.inner.intern_static(s.as_bytes())
}
pub fn intern_mut_static<'a, 'b: 'a>(&'a mut self, s: &'b str) -> S {
self.inner.intern_mut_static(s.as_bytes())
}
pub fn intern_many<'a>(&self, strings: impl IntoIterator<Item = &'a str>) {
self.inner.intern_many(strings.into_iter().map(str::as_bytes));
}
pub fn intern_many_mut<'a>(&mut self, strings: impl IntoIterator<Item = &'a str>) {
self.inner.intern_many_mut(strings.into_iter().map(str::as_bytes));
}
pub fn intern_many_static<'a, 'b: 'a>(&'a self, strings: impl IntoIterator<Item = &'b str>) {
self.inner.intern_many_static(strings.into_iter().map(str::as_bytes));
}
pub fn intern_many_mut_static<'a, 'b: 'a>(
&'a mut self,
strings: impl IntoIterator<Item = &'b str>,
) {
self.inner.intern_many_mut_static(strings.into_iter().map(str::as_bytes));
}
#[inline]
#[must_use]
#[cfg_attr(debug_assertions, track_caller)]
pub fn resolve(&self, sym: S) -> &str {
unsafe { std::str::from_utf8_unchecked(self.inner.resolve(sym)) }
}
}