source2_demo/string_table/
container.rs

1use crate::error::StringTableError;
2use crate::string_table::*;
3use crate::HashMap;
4
5/// String tables container.
6#[derive(Default, Clone)]
7pub struct StringTables {
8    pub(crate) tables: Vec<StringTable>,
9    pub(crate) name_to_table: HashMap<String, usize>,
10}
11
12impl StringTables {
13    /// Iterator over all string tables.
14    pub fn iter(&self) -> impl Iterator<Item = &StringTable> {
15        self.tables.iter()
16    }
17
18    /// Returns [`StringTable`] for given id.
19    pub fn get_by_id(&self, id: usize) -> Result<&StringTable, StringTableError> {
20        self.tables
21            .get(id)
22            .ok_or(StringTableError::TableNotFoundById(id as i32))
23    }
24
25    /// Returns [`StringTable`] for given name.
26    pub fn get_by_name(&self, name: &str) -> Result<&StringTable, StringTableError> {
27        self.name_to_table
28            .get(name)
29            .ok_or_else(|| StringTableError::TableNotFoundByName(name.to_string()))
30            .map(|&idx| &self.tables[idx])
31    }
32
33    pub(crate) fn get_by_name_mut(
34        &mut self,
35        name: &str,
36    ) -> Result<&mut StringTable, StringTableError> {
37        self.name_to_table
38            .get(name)
39            .ok_or_else(|| StringTableError::TableNotFoundByName(name.to_string()))
40            .map(|&idx| self.tables.get_mut(idx).unwrap())
41    }
42}