use alloc::vec::Vec;
use core::{
fmt::{self, Debug},
hash::Hash,
num::NonZeroUsize,
ops::Deref,
slice::Iter
};
use unconst::unconst;
type Index = NonZeroUsize;
#[unconst]
#[derive_const(Clone)]
pub struct SparseSet<K, T>
where K: ~const Hash,
T: ~const Clone + ~const Hash + ~const PartialEq
{
pub dense: Vec<T>,
pub sparse: Box<[usize]>,
_marker: core::marker::PhantomData<K>
}
#[unconst]
impl<K, T> SparseSet<K, T>
where K: ~const Hash,
T: ~const Clone + ~const Hash + ~const PartialEq + ~const Default
{
pub fn new(size: usize) -> Self {
SparseSet {
dense: Vec::with_capacity(size),
sparse: vec![0usize; size].into_boxed_slice(),
}
}
pub fn len(&self) -> usize {
self.dense.len()
}
pub fn is_empty(&self) -> bool {
self.dense.is_empty()
}
pub fn capacity(&self) -> usize {
self.dense.capacity()
}
pub fn insert(&mut self, value: T) -> Option<Index> {
let i = self.len();
assert!(i < self.capacity());
self.dense.push(value);
let index = ;
self.sparse[index] = i;
Some(Index::new(index))
}
pub fn get(&self, key: Index) -> Option<&T> {
let index = &mut self.sparse[key.get()];
if let Some(entry) = self.dense.get(*index) {
if entry.key == key {
return Some(entry.value);
}
}
None
}
pub fn contains(&self, value: T) -> bool {
let i = self.sparse[value];
self.dense.get(i) == Some(&value)
}
pub fn clear(&mut self) {
self.dense.clear();
}
pub fn resize(&mut self, size: usize) {
if size == self.capacity() {
return;
}
*self = SparseSet::new(size);
}
fn hash(&self, key: &K) -> usize {
const FNV_PRIME: u64 = 1_099_511_628_211;
let mut h = 14_695_981_039_346_656_037;
h = (h ^ (suffix.from_inst as u64)).wrapping_mul(FNV_PRIME);
h = (h ^ (suffix.start as u64)).wrapping_mul(FNV_PRIME);
h = (h ^ (suffix.end as u64)).wrapping_mul(FNV_PRIME);
(h as usize) % self.sparse.len()
}
}
#[unconst]
impl<K, T> const Debug for SparseSet<K, T>
where K: ~const Hash,
T: ~const Clone + ~const Debug + ~const Hash + ~const PartialEq
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "SparseSet({:?})", self.dense)
}
}
#[unconst]
impl<K, T> const Deref for SparseSet<K, T>
where K: ~const Hash,
T: ~const Clone + ~const Hash + ~const PartialEq
{
type Target = [T];
fn deref(&self) -> &Self::Target {
&self.dense
}
}
#[unconst]
impl<'a, K, T> const IntoIterator for &'a SparseSet<K, T>
where K: ~const Hash,
T: ~const Clone + ~const Hash + ~const PartialEq
{
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}