velesdb_core/column_store/
string_table.rs1use rustc_hash::FxHashMap;
9
10use super::types::StringId;
11
12#[derive(Debug, Default)]
14pub struct StringTable {
15 string_to_id: FxHashMap<String, StringId>,
17 id_to_string: Vec<String>,
19}
20
21impl StringTable {
22 #[must_use]
24 pub fn new() -> Self {
25 Self::default()
26 }
27
28 pub fn intern(&mut self, s: &str) -> StringId {
36 if let Some(&id) = self.string_to_id.get(s) {
37 return id;
38 }
39
40 let len = self.id_to_string.len();
42 assert!(
43 len < u32::MAX as usize,
44 "StringTable overflow: cannot intern more than {} strings",
45 u32::MAX
46 );
47 #[allow(clippy::cast_possible_truncation)] let id = StringId(len as u32);
49 self.id_to_string.push(s.to_string());
50 self.string_to_id.insert(s.to_string(), id);
51 id
52 }
53
54 #[must_use]
56 pub fn get(&self, id: StringId) -> Option<&str> {
57 self.id_to_string.get(id.0 as usize).map(String::as_str)
58 }
59
60 #[must_use]
62 pub fn get_id(&self, s: &str) -> Option<StringId> {
63 self.string_to_id.get(s).copied()
64 }
65
66 #[must_use]
68 pub fn len(&self) -> usize {
69 self.id_to_string.len()
70 }
71
72 #[must_use]
74 pub fn is_empty(&self) -> bool {
75 self.id_to_string.is_empty()
76 }
77}