stringtab.rs 1.16 KiB
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
// Map strings to unique identifiers and counts uids
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct StringTable {
count: usize,
string_to_index: HashMap<String, usize>,
index_to_string: HashMap<usize, String>,
}
impl StringTable {
pub fn new() -> StringTable {
StringTable {
count: 0,
string_to_index: HashMap::new(),
index_to_string: HashMap::new(),
}
}
// Produce the UID for a string
pub fn lookup_string(&mut self, s: String) -> usize {
match self.string_to_index.get(&s) {
Some(n) => *n,
None => {
let n = self.count;
self.count += 1;
self.string_to_index.insert(s.clone(), n);
self.index_to_string.insert(n, s);
n
}
}
}
// Identify the string corresponding to a UID
pub fn lookup_id(&self, n: usize) -> Option<String> {
self.index_to_string.get(&n).cloned()
}
}
impl Default for StringTable {
fn default() -> Self {
StringTable::new()
}
}