use std::{convert::Infallible, marker, mem, num};
use crate::depot::{capacity, map};
mod flat;
mod layout;
mod table;
pub use flat::Flat;
pub use layout::Layout;
pub use table::Table;
pub(in crate::depot::map) fn scan<D: Directory, E, O: Copy, const SPARE: bool>(
owner: &D,
hash: u64,
matches: impl Fn(D::Occupied) -> Result<Option<O>, E>,
) -> Result<Option<map::Entry<O, Vacant>>, E> {
let width = owner.buckets();
if width == 0 {
return Ok(None);
}
let mask = width - 1;
if SPARE {
return unsafe { scan_spare(owner, hash, mask, matches) }.map(Some);
}
let start = hash as usize & mask;
let mut index = start;
loop {
if let Some(entry) = unsafe { at(owner, index, hash, &matches) }? {
return Ok(Some(entry));
}
index = (index + 1) & mask;
if index == start {
return Ok(None);
}
}
}
unsafe fn scan_spare<D: Directory, E, O: Copy>(
owner: &D,
hash: u64,
mask: usize,
matches: impl Fn(D::Occupied) -> Result<Option<O>, E>,
) -> Result<map::Entry<O, Vacant>, E> {
let mut index = hash as usize & mask;
loop {
if let Some(entry) = unsafe { at(owner, index, hash, &matches) }? {
return Ok(entry);
}
index = (index + 1) & mask;
}
}
unsafe fn at<D: Directory, E, O: Copy>(
owner: &D,
index: usize,
hash: u64,
matches: &impl Fn(D::Occupied) -> Result<Option<O>, E>,
) -> Result<Option<map::Entry<O, Vacant>>, E> {
Ok(match unsafe { owner.candidate(index, hash) } {
Candidate::Vacant => Some(map::Entry::Vacant(unsafe { Vacant::new(index) })),
Candidate::Occupied(slot) => matches(slot)?.map(map::Entry::Occupied),
Candidate::Skip => None,
})
}
pub(in crate::depot::map) unsafe fn member<D: Directory>(
owner: &D,
hash: u64,
matches: impl Fn(D::Occupied) -> bool,
) -> map::raw::Occupied {
let mask = owner.buckets() - 1;
let mut index = hash as usize & mask;
loop {
if let Candidate::Occupied(slot) = unsafe { owner.candidate(index, hash) }
&& matches(slot)
{
return unsafe { Occupied::new(index) };
}
index = (index + 1) & mask;
}
}
pub(in crate::depot::map) unsafe fn close<D: Shift>(owner: &mut D, mut hole: map::raw::Vacant) {
let mask = owner.directory().buckets() - 1;
let mut next = hole.index();
loop {
next = (next + 1) & mask;
let Some(hash) = (unsafe { owner.directory().hash(next) }) else {
return;
};
let home = hash as usize & mask;
if next.wrapping_sub(home) & mask > hole.index().wrapping_sub(home) & mask {
let occupied = unsafe { Occupied::new(next) };
unsafe { owner.shift(&hole, &occupied, hash) };
hole = unsafe { Vacant::new(next) };
}
}
}
pub unsafe trait Query: Sized {
const SPARE: bool = false;
const NONEMPTY: bool = false;
type Payload;
type Value;
type Occupied;
fn table(&self) -> &map::raw::Table<Self::Payload>;
fn value(entry: map::Found<&Self>) -> &Self::Value;
fn occupied(entry: map::Found<Self>) -> Self::Occupied;
fn find(self, hash: u64, matches: impl Fn(&Self::Value) -> bool) -> Option<Self::Occupied> {
self.try_find(hash, move |value| Ok::<_, Infallible>(matches(value)))
.unwrap_or_else(|never| match never {})
}
fn try_find<E>(
self,
hash: u64,
matches: impl Fn(&Self::Value) -> Result<bool, E>,
) -> Result<Option<Self::Occupied>, E> {
let Some(map::Entry::Occupied(bucket)) = query(&self, hash, &matches)? else {
return Ok(None);
};
Ok(Some(Self::occupied(map::Found {
owner: self,
bucket,
})))
}
}
pub unsafe trait Insertion: Query {
type Vacant;
fn vacant(entry: map::Vacancy<Self>, hash: u64) -> Option<Self::Vacant>;
fn entry(
self,
hash: u64,
matches: impl Fn(&Self::Value) -> bool,
) -> map::Entry<Self::Occupied, Option<Self::Vacant>> {
self.try_entry(hash, move |value| Ok::<_, Infallible>(matches(value)))
.unwrap_or_else(|never| match never {})
}
fn try_entry<E>(
self,
hash: u64,
matches: impl Fn(&Self::Value) -> Result<bool, E>,
) -> Result<map::Entry<Self::Occupied, Option<Self::Vacant>>, E> {
let entry = query(&self, hash, &matches)?;
drop(matches);
Ok(match entry {
Some(map::Entry::Occupied(bucket)) => {
map::Entry::Occupied(Self::occupied(map::Found {
owner: self,
bucket,
}))
}
Some(map::Entry::Vacant(bucket)) => map::Entry::Vacant(bucket.admit(self, hash)),
None => map::Entry::Vacant(None),
})
}
fn reserve(
self,
hash: u64,
matches: impl Fn(&Self::Value) -> bool,
) -> map::Entry<(), Option<Self::Vacant>> {
let entry = query(&self, hash, |value| Ok::<_, Infallible>(matches(value)))
.unwrap_or_else(|never| match never {});
match entry {
Some(map::Entry::Occupied(_)) => map::Entry::Occupied(()),
Some(map::Entry::Vacant(bucket)) => map::Entry::Vacant(bucket.admit(self, hash)),
None => map::Entry::Vacant(None),
}
}
}
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct Occupied(num::NonZero<u32>);
#[repr(transparent)]
pub struct Vacant(u32);
impl Occupied {
pub const unsafe fn new(index: usize) -> Self {
Self(unsafe { num::NonZero::<u32>::new_unchecked(index as u32 + 1) })
}
pub const fn index(&self) -> usize {
self.0.get() as usize - 1
}
}
impl Vacant {
pub const fn index(&self) -> usize {
self.0 as usize
}
pub(crate) const unsafe fn new(index: usize) -> Self {
Self(index as u32)
}
}
pub(in crate::depot::map) unsafe trait Directory {
type Occupied: Copy;
fn buckets(&self) -> usize;
unsafe fn hash(&self, index: usize) -> Option<u64>;
unsafe fn candidate(&self, index: usize, hash: u64) -> Candidate<Self::Occupied>;
}
pub(in crate::depot::map) enum Candidate<O> {
Occupied(O),
Vacant,
Skip,
}
pub(in crate::depot::map) unsafe trait Shift {
fn directory(&self) -> &impl Directory;
unsafe fn shift(&mut self, hole: &map::raw::Vacant, next: &map::raw::Occupied, hash: u64);
}
pub(crate) unsafe fn spare<Q: map::raw::Query>(
owner: Q,
hash: u64,
matches: impl Fn(&Q::Value) -> bool,
) -> map::Entry<Q::Occupied, map::Vacancy<Q>> {
let buckets = &owner.table().directory;
let Ok(entry) = unsafe {
scan_spare(buckets, hash, buckets.buckets() - 1, |bucket| {
let value = Q::value(map::Found {
owner: &owner,
bucket,
});
Ok::<_, Infallible>(matches(value).then_some(bucket))
})
};
match entry {
map::Entry::Occupied(bucket) => {
drop(matches);
map::Entry::Occupied(Q::occupied(map::Found { owner, bucket }))
}
map::Entry::Vacant(bucket) => map::Entry::Vacant(map::Vacancy {
owner,
bucket,
phase: (),
}),
}
}
fn query<Q: map::raw::Query, E>(
owner: &Q,
hash: u64,
matches: impl Fn(&Q::Value) -> Result<bool, E>,
) -> Result<Option<map::Entry<Occupied, Vacant>>, E> {
let buckets = &owner.table().directory;
let matches = |bucket| Ok(matches(Q::value(map::Found { owner, bucket }))?.then_some(bucket));
if Q::NONEMPTY && Q::SPARE {
return unsafe { scan_spare(buckets, hash, buckets.buckets() - 1, matches) }.map(Some);
}
if Q::SPARE {
scan::<_, _, _, true>(buckets, hash, matches)
} else {
scan::<_, _, _, false>(buckets, hash, matches)
}
}
impl Vacant {
fn admit<Q: map::raw::Insertion>(self, owner: Q, hash: u64) -> Option<Q::Vacant> {
Q::vacant(
map::Vacancy {
owner,
bucket: self,
phase: (),
},
hash,
)
}
}
const _: () = {
assert!(size_of::<map::raw::Occupied>() == size_of::<u32>());
assert!(size_of::<Option<map::raw::Occupied>>() == size_of::<map::raw::Occupied>());
assert!(size_of::<map::raw::Vacant>() == size_of::<u32>());
assert!(size_of::<Option<map::Entry<Occupied, Vacant>>>() == size_of::<u64>());
};
#[repr(transparent)]
pub struct Shape<P> {
plan: map::Plan,
value: marker::PhantomData<fn() -> P>,
}
impl<P> Shape<P> {
pub const fn capacity(self) -> capacity::Count {
self.plan.capacity()
}
pub fn layout(self) -> Layout<P> {
unsafe { Layout::restore(self.plan) }
}
}
impl<P> Clone for Shape<P> {
fn clone(&self) -> Self {
*self
}
}
impl<P> Copy for Shape<P> {}
pub unsafe trait Mutation: map::raw::Query {
unsafe fn table_mut(&mut self) -> &mut Table<Self::Payload>;
unsafe fn shift(&mut self, hole: &map::raw::Vacant, next: &map::raw::Occupied, hash: u64);
}
pub struct Hole<Q> {
owner: Q,
}
impl<Q: Mutation> Hole<Q> {
pub unsafe fn remove(mut owner: Q, bucket: map::raw::Occupied) -> Q::Payload {
let value = unsafe { owner.table_mut().take(bucket) };
Self::close(owner, bucket);
value
}
pub(crate) unsafe fn retire(owner: Q, bucket: map::raw::Occupied)
where
Q::Payload: Copy,
{
Self::close(owner, bucket);
}
fn close(mut owner: Q, bucket: map::raw::Occupied) {
let vacant = unsafe { owner.table_mut().directory.vacate(bucket) };
unsafe { close(&mut Self { owner }, vacant) };
}
}
unsafe impl<Q: Mutation> Shift for Hole<Q> {
fn directory(&self) -> &impl Directory {
&self.owner.table().directory
}
unsafe fn shift(&mut self, hole: &Vacant, next: &Occupied, hash: u64) {
unsafe { self.owner.shift(hole, next, hash) };
}
}
const _: () = {
assert!(mem::size_of::<Table<u64>>() == 4 * mem::size_of::<usize>());
assert!(mem::size_of::<Hole<&mut Flat<u64>>>() == mem::size_of::<usize>());
};