anathema_store/storage/
strings.rs

1use std::fmt::{self, Display};
2
3use super::Storage;
4use crate::slab::SlabIndex;
5
6pub struct Strings {
7    inner: Storage<StringId, String, ()>,
8}
9
10impl Strings {
11    pub fn empty() -> Self {
12        Self {
13            inner: Storage::empty(),
14        }
15    }
16
17    pub fn push(&mut self, string: impl Into<String>) -> StringId {
18        self.inner.push(string, ())
19    }
20
21    pub fn lookup(&self, string: &str) -> Option<StringId> {
22        self.inner.iter().find_map(|(i, (k, _))| match k == string {
23            true => Some(i),
24            false => None,
25        })
26    }
27
28    pub fn get(&self, string_id: StringId) -> Option<&str> {
29        self.inner.get(string_id).map(|(k, _v)| k.as_str())
30    }
31
32    pub fn get_unchecked(&self, string_id: StringId) -> String {
33        self.inner.get_unchecked(string_id).0.clone()
34    }
35
36    pub fn get_ref_unchecked(&self, string_id: StringId) -> &str {
37        &self.inner.get_unchecked(string_id).0
38    }
39}
40
41// TODO: change this to u16
42#[derive(Debug, Copy, Clone, PartialEq)]
43pub struct StringId(usize);
44
45impl SlabIndex for StringId {
46    const MAX: usize = usize::MAX;
47
48    fn as_usize(&self) -> usize {
49        self.0
50    }
51
52    fn from_usize(index: usize) -> Self
53    where
54        Self: Sized,
55    {
56        Self(index)
57    }
58}
59
60impl Display for StringId {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        write!(f, "<sid {}>", self.0)
63    }
64}
65
66impl From<usize> for StringId {
67    fn from(value: usize) -> Self {
68        Self(value)
69    }
70}