use crate::error::MuninError;
const STRING_START_INDEX: i32 = 10;
const NULL_INDEX: i32 = 0;
const EMPTY_INDEX: i32 = 1;
#[derive(Debug, Default)]
pub struct StringTable {
entries: Vec<String>,
}
impl StringTable {
pub fn new() -> Self {
Self {
entries: Vec::new(),
}
}
pub fn add(&mut self, value: String) -> i32 {
let index = STRING_START_INDEX + self.entries.len() as i32;
self.entries.push(value);
index
}
pub fn get(&self, index: i32) -> Result<Option<&str>, MuninError> {
if index == NULL_INDEX {
return Ok(None);
}
if index == EMPTY_INDEX {
return Ok(Some(""));
}
let table_index = index - STRING_START_INDEX;
if table_index < 0 || table_index as usize >= self.entries.len() {
return Err(MuninError::InvalidIndex {
kind: "string",
index,
});
}
Ok(Some(&self.entries[table_index as usize]))
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn entries(&self) -> &[String] {
&self.entries
}
pub fn entries_mut(&mut self) -> &mut [String] {
&mut self.entries
}
}
#[cfg(test)]
mod tests;