Files
ReactionSystems/src/rsprocess/translator.rs

97 lines
2.5 KiB
Rust
Raw Normal View History

//! Module for translation and keeping track of strings.
2025-07-10 15:02:14 +02:00
use serde::{Deserialize, Serialize};
2025-08-24 03:35:32 +02:00
use std::collections::HashMap;
use std::fmt;
2025-08-27 23:58:43 +02:00
use super::element::IdType;
/// precision for printing frequencies
pub static PRECISION: &usize = &2;
2025-06-16 14:46:04 +02:00
2025-07-10 15:02:14 +02:00
/// Structure that keeps track of association string and id. Ids given
/// sequentially from 0.
2025-07-09 21:44:04 +02:00
#[derive(Clone, Debug, Serialize, Deserialize)]
2025-06-16 14:46:04 +02:00
pub struct Translator {
strings: HashMap<String, IdType>,
2025-06-18 11:28:04 +02:00
reverse: HashMap<IdType, String>,
last_id: IdType,
2025-06-16 14:46:04 +02:00
}
impl Translator {
pub fn new() -> Self {
Translator {
strings: HashMap::from([("*".into(), 0)]),
reverse: HashMap::from([(0, "*".into())]),
last_id: 1,
}
2025-06-16 14:46:04 +02:00
}
/// converts a string into an id
2025-06-18 11:28:04 +02:00
pub fn encode(&mut self, s: impl Into<String>) -> IdType {
let s = s.into();
let id = *(self.strings.entry(s.clone()).or_insert({
self.last_id += 1;
self.last_id
}));
self.reverse.insert(id, s.clone());
id
2025-06-18 11:28:04 +02:00
}
2025-06-16 14:46:04 +02:00
2025-07-12 02:42:28 +02:00
pub fn encode_not_mut(&self, s: impl Into<String>) -> Option<IdType> {
self.strings.get(&s.into()).copied()
2025-07-12 02:42:28 +02:00
}
/// converts an id into the corresponding string
2025-07-02 07:30:05 +02:00
pub fn decode(&self, el: IdType) -> Option<String> {
self.reverse.get(&el).map(|x| x.to_string())
2025-06-18 11:28:04 +02:00
}
2025-06-16 14:46:04 +02:00
}
impl Default for Translator {
fn default() -> Self {
Translator::new()
}
}
impl PartialEq for Translator {
fn eq(&self, other: &Self) -> bool {
for (s, id) in self.strings.iter() {
match other.strings.get(s) {
None => return false,
Some(id2) if id != id2 => return false,
_ => {}
}
}
true
}
}
// -----------------------------------------------------------------------------
// print structures
2025-06-18 11:28:04 +02:00
// -----------------------------------------------------------------------------
pub trait PrintableWithTranslator {
fn print(&self, f: &mut fmt::Formatter, translator: &Translator) -> fmt::Result;
}
pub struct Formatter<'a, T> {
data: &'a T,
translator: &'a Translator,
}
impl<'a, T> fmt::Display for Formatter<'a, T>
where
T: PrintableWithTranslator,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.data.print(f, self.translator)
}
}
impl<'a, T> Formatter<'a, T> {
pub fn from(translator: &'a Translator, data: &'a T) -> Self {
Self { data, translator }
}
}