Created
August 13, 2023 02:06
-
-
Save MikuroXina/7c22558bf2ee299f4169de6a0c2286b9 to your computer and use it in GitHub Desktop.
Coordinate Compression utility with Rust.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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