dtmt/lib/sdk/src/context.rs
Lucas Schwiderski 036c20bd8c
feat(lib): Implement IdString type
This type is similar to an `Either` between a `Murmur64` hash and a
`String`. This is necessary to be able to retain hash information where
the hash is not in the dictionary, but at the same time allow string
names where they are available.

Up until now, when reading a bundle, all hashes would be converted to
strings, which made sense for displaying those names. But when writing
the same bundle back, those strings ended up being re-hashed, resulting
in incorrect hashes.
2023-02-17 22:51:46 +01:00

57 lines
1.4 KiB
Rust

use std::path::PathBuf;
use crate::murmur::{Dictionary, HashGroup, IdString64, Murmur32, Murmur64};
pub struct Context {
pub lookup: Dictionary,
pub ljd: Option<String>,
pub revorb: Option<String>,
pub ww2ogg: Option<String>,
pub game_dir: Option<PathBuf>,
}
impl Context {
pub fn new() -> Self {
Self {
lookup: Dictionary::new(),
ljd: None,
revorb: None,
ww2ogg: None,
game_dir: None,
}
}
pub fn lookup_hash<M>(&self, hash: M, group: HashGroup) -> IdString64
where
M: Into<Murmur64>,
{
let hash = hash.into();
if let Some(s) = self.lookup.lookup(hash, group) {
tracing::debug!(%hash, string = s, "Murmur64 lookup successful");
s.to_string().into()
} else {
tracing::debug!(%hash, "Murmur64 lookup failed");
hash.into()
}
}
pub fn lookup_hash_short<M>(&self, hash: M, group: HashGroup) -> String
where
M: Into<Murmur32>,
{
let hash = hash.into();
if let Some(s) = self.lookup.lookup_short(hash, group) {
tracing::debug!(%hash, string = s, "Murmur32 lookup successful");
s.to_owned()
} else {
tracing::debug!(%hash, "Murmur32 lookup failed");
format!("{hash:08X}")
}
}
}
impl Default for Context {
fn default() -> Self {
Self::new()
}
}