Skip to content

Instantly share code, notes, and snippets.

@MikuroXina
Created August 13, 2023 02:06
Show Gist options
  • Save MikuroXina/7c22558bf2ee299f4169de6a0c2286b9 to your computer and use it in GitHub Desktop.
Save MikuroXina/7c22558bf2ee299f4169de6a0c2286b9 to your computer and use it in GitHub Desktop.
Coordinate Compression utility with Rust.
use std::collections::BTreeMap;
#[derive(Debug)]
pub struct CoCo<K: Ord> {
forward: BTreeMap<K, usize>,
backward: Vec<K>,
}
impl<K: Ord> CoCo<K> {
pub const fn new() -> Self {
Self {
forward: BTreeMap::new(),
backward: vec![],
}
}
pub fn forward(&mut self, key: K) -> usize
where
K: Clone,
{
if let Some(idx) = self.forward.get(&key) {
*idx
} else {
let new_idx = self.backward.len();
self.forward.insert(key.clone(), new_idx);
self.backward.push(key);
new_idx
}
}
pub fn backward(&self, idx: usize) -> Option<&K> {
self.backward.get(idx)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment