Skip to content

Instantly share code, notes, and snippets.

@wallabra
Created February 16, 2025 18:25
Show Gist options
  • Save wallabra/1b4a5707f9bc9d0a84d01b32c74996b0 to your computer and use it in GitHub Desktop.
Save wallabra/1b4a5707f9bc9d0a84d01b32c74996b0 to your computer and use it in GitHub Desktop.
Grouped Slotmap
#[derive(Clone, Debug)]
pub struct GroupedKey<K: Clone> {
group_key: K,
item_key: usize,
}
impl<K> GroupedKey<K> {
fn new(group_key: K, item_key: usize) -> Self {
Self {
group_key,
item_key
}
}
}
#[derive(Clone, Debug)]
pub struct GroupedSlotMap<K: Key, V: Clone, const BaseLen: usize = 8> {
buf: HopSlotMap<K, SmallVec<[V; BaseLen]>>,
}
impl<K: Key, V: Clone, const BaseLen: usize> GroupedSlotMap<K, V, BaseLen> {
pub fn insert_group(&mut self, items: &[V]) -> K {
self.buf.insert(items.iter().cloned().collect())
}
pub fn insert(&mut self, item: V) -> K {
self.buf.insert(vec![item].into())
}
}
impl<K: Key, V: Clone, const BaseLen: usize> Index<K> for GroupedSlotMap<K, V, BaseLen> {
type Output = SmallVec<[V; BaseLen]>;
fn index(&self, index: K) -> &Self::Output {
&self.buf[index]
}
}
impl<K: Key, V: Clone, const BaseLen: usize> Index<GroupedKey<K>>
for GroupedSlotMap<K, V, BaseLen>
{
type Output = V;
fn index(&self, index: GroupedKey<K>) -> &Self::Output {
&self.buf[index.group_key][index.item_key]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment