use std::collections::HashMap;
pub(super) struct IriInterner {
map: HashMap<String, u32>,
iris: Vec<String>,
}
impl IriInterner {
pub(super) fn new() -> Self {
IriInterner {
map: HashMap::new(),
iris: Vec::new(),
}
}
pub(super) fn get_or_intern(&mut self, iri: &str) -> u32 {
if let Some(&id) = self.map.get(iri) {
return id;
}
let id = self.iris.len() as u32;
self.iris.push(iri.to_string());
self.map.insert(iri.to_string(), id);
id
}
pub(super) fn iri(&self, id: u32) -> &str {
&self.iris[id as usize]
}
pub(super) fn len(&self) -> usize {
self.iris.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dense_sequential_ids() {
let mut i = IriInterner::new();
assert_eq!(i.get_or_intern("http://a"), 0);
assert_eq!(i.get_or_intern("http://b"), 1);
assert_eq!(i.get_or_intern("http://a"), 0);
assert_eq!(i.get_or_intern("http://c"), 2);
assert_eq!(i.len(), 3);
assert_eq!(i.iri(1), "http://b");
}
}