use std::num;
use crate::{
alloc::{self, tail},
depot,
depot::map::compact::{self, Found, Layout, Removed, Value},
};
cfg_select! {
all(target_arch = "aarch64", target_feature = "neon") => {
mod aarch64;
use aarch64::group_masks;
}
all(target_arch = "x86_64", target_feature = "sse2") => {
mod x86_64;
use x86_64::group_masks;
}
_ => {
mod scalar;
use scalar::group_masks;
}
}
pub unsafe trait Read: Sized {
fn layout(&self) -> Layout;
fn bytes(&self) -> &[u8];
}
pub unsafe trait Source: Read {
fn hash(value: Value<'_, Self>) -> u64;
}
pub unsafe trait Query: Source {
type Item;
fn get(value: Value<'_, Self>) -> Self::Item;
}
pub unsafe trait Write: Read {
unsafe fn owner_mut(entry: &mut Found<Self>) -> &mut Self {
&mut entry.owner
}
unsafe fn bytes_mut(&mut self) -> &mut [u8];
unsafe fn clear(&mut self) {
let layout = self.layout();
unsafe { init(layout, self.bytes_mut()) };
}
}
pub unsafe trait Member: Remove {
fn input(&self) -> Value<'_, Self>;
}
pub unsafe trait Remove: Write + Source {
unsafe fn into_owner(removed: Removed<Self>) -> Self {
removed.owner
}
type Output;
fn removed(removed: Removed<Self>) -> Self::Output;
}
pub unsafe trait Insert: Write + Source {
type Output;
fn input(&self) -> Value<'_, Self>;
unsafe fn inserted(self) -> Self::Output;
}
pub struct Plan<H> {
layout: compact::Layout,
memory: tail::Plan<H, u8>,
}
impl<H> Plan<H> {
pub fn new(layout: compact::Layout) -> Result<Self, alloc::Overflow> {
Ok(Self {
layout,
memory: tail::Plan::try_new(layout.end())?,
})
}
pub fn try_allocate(self, header: H) -> Result<tail::raw::Block<H, u8>, alloc::Exhausted> {
let mut block = self.memory.try_allocate()?.repeat(header, 0);
unsafe { init(self.layout, block.as_mut_slice()) };
Ok(block)
}
}
impl<H> Clone for Plan<H> {
fn clone(&self) -> Self {
*self
}
}
impl<H> Copy for Plan<H> {}
unsafe fn init(layout: Layout, bytes: &mut [u8]) {
if layout.buckets != 0 {
unsafe {
bytes
.as_mut_ptr()
.add(layout.start as usize)
.write_bytes(compact::EMPTY, layout.control_len());
}
}
}
pub(in crate::depot::map::compact) struct Store<Q: compact::raw::Read> {
owner: Q,
layout: compact::Layout,
}
impl<Q: compact::raw::Read> Store<Q> {
pub(in crate::depot::map::compact) fn new(owner: Q) -> Self {
let layout = owner.layout();
Self { owner, layout }
}
}
impl<Q: compact::raw::Read> Store<Q> {
fn bucket(&self, index: usize) -> Bucket {
Bucket {
index: index & (self.layout.buckets as usize - 1),
}
}
fn control(&self, bucket: Bucket) -> Control {
let value = unsafe {
*self
.owner
.bytes()
.as_ptr()
.add(self.layout.start as usize + bucket.index)
};
Control { bucket, value }
}
fn read(&self, resident: Resident) -> Entry {
let bucket = resident.0.bucket;
let width = compact::Width::new(self.layout.domain);
let start = self.layout.plane() + bucket.index * width as usize;
let bytes = unsafe { self.owner.bytes().as_ptr().add(start) };
let index = unsafe {
match width {
compact::Width::One => u32::from(bytes.read()),
compact::Width::Two => {
u32::from(u16::from_le(bytes.cast::<u16>().read_unaligned()))
}
compact::Width::Four => u32::from_le(bytes.cast::<u32>().read_unaligned()),
}
};
Entry {
bucket,
payload: Payload { index },
}
}
fn value(&self, payload: Payload) -> compact::Value<'_, Q> {
compact::Value::new(unsafe { depot::raw::Proof::new((&self.owner, payload.index)) })
}
}
impl<Q: compact::raw::Write> Store<Q> {
fn write(&mut self, bucket: Bucket, control: u8, payload: Payload) {
self.mark(bucket, control);
let width = compact::Width::new(self.layout.domain);
let start = self.layout.plane() + bucket.index * width as usize;
let bytes = unsafe { self.owner.bytes_mut().as_mut_ptr().add(start) };
unsafe {
match width {
compact::Width::One => bytes.write(payload.index as u8),
compact::Width::Two => bytes
.cast::<u16>()
.write_unaligned((payload.index as u16).to_le()),
compact::Width::Four => bytes.cast::<u32>().write_unaligned(payload.index.to_le()),
}
}
}
fn mark(&mut self, bucket: Bucket, value: u8) {
let index = self.layout.start as usize + bucket.index;
let bytes = unsafe { self.owner.bytes_mut().as_mut_ptr() };
unsafe { bytes.add(index).write(value) };
if bucket.index < 32 {
unsafe { bytes.add(index + self.layout.buckets as usize).write(value) };
}
}
}
impl<Q: compact::raw::Insert> Store<Q> {
pub(in crate::depot::map::compact) fn insert(mut self) -> Q::Output {
let mut payload = Payload {
index: self.owner.input().index,
};
let hash = Q::hash(self.value(payload));
let mut bucket = self.bucket(hash as usize);
let mut home = bucket;
let mut control = (hash >> 57) as u8;
loop {
let Some(resident) = self.control(bucket).occupied() else {
self.write(bucket, control, payload);
return unsafe { self.owner.inserted() };
};
let current = resident.0.value;
let stored = self.read(resident).payload;
let origin = self.bucket(Q::hash(self.value(stored)) as usize);
if (bucket.index.wrapping_sub(home.index) & (self.layout.buckets as usize - 1))
> (bucket.index.wrapping_sub(origin.index) & (self.layout.buckets as usize - 1))
{
self.write(bucket, control, payload);
control = current;
payload = stored;
home = origin;
}
bucket = self.bucket(bucket.index + 1);
}
}
}
impl<Q: compact::raw::Member> Store<Q> {
pub(in crate::depot::map::compact) fn locate(self) -> compact::Found<Q> {
let payload = Payload {
index: self.owner.input().index,
};
let hash = Q::hash(self.value(payload));
let mut bucket = self.bucket(hash as usize);
loop {
if let Some(resident) = self.control(bucket).matching(hash) {
let entry = self.read(resident);
if entry.payload == payload {
return entry.finish(self);
}
}
bucket = self.bucket(bucket.index + 1);
}
}
}
impl<Q: compact::raw::Remove> Store<Q> {
pub(in crate::depot::map::compact) fn remove(occupied: compact::Found<Q>) -> Q::Output {
let mut store = Self::new(occupied.owner);
let mut hole = Bucket {
index: occupied.bucket.get() as usize - 1,
};
while let Some(resident) = store.control(store.bucket(hole.index + 1)).occupied() {
let control = resident.0.value;
let entry = store.read(resident);
let home = store.bucket(Q::hash(store.value(entry.payload)) as usize);
if entry.bucket.index == home.index {
break;
}
store.write(hole, control, entry.payload);
hole = entry.bucket;
}
store.mark(hole, compact::EMPTY);
Q::removed(compact::Removed {
owner: store.owner,
payload: occupied.payload,
})
}
}
#[derive(Clone, Copy)]
struct Bucket {
index: usize,
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct Payload {
index: u32,
}
struct Resident(Control);
struct Control {
bucket: Bucket,
value: u8,
}
impl Control {
fn occupied(self) -> Option<Resident> {
if self.value == compact::EMPTY {
return None;
}
Some(Resident(self))
}
fn matching(self, hash: u64) -> Option<Resident> {
if self.value != (hash >> 57) as u8 {
return None;
}
Some(Resident(self))
}
}
struct Entry {
bucket: Bucket,
payload: Payload,
}
impl Entry {
fn finish<Q: compact::raw::Read>(self, store: Store<Q>) -> compact::Found<Q> {
let bucket = unsafe { num::NonZero::new_unchecked(self.bucket.index as u32 + 1) };
compact::Found {
owner: store.owner,
bucket,
payload: self.payload.index,
}
}
}
pub struct Iter<Q: compact::raw::Read> {
store: Store<Q>,
hash: u64,
start: usize,
bits: u32,
done: bool,
}
impl<Q: compact::raw::Read> Iter<Q> {
pub fn empty(owner: Q, hash: u64) -> Self {
Self {
store: Store::new(owner),
hash,
start: 0,
bits: 0,
done: true,
}
}
pub(in crate::depot::map::compact) fn new(owner: Q, hash: u64) -> Self {
let mut iter = Self::empty(owner, hash);
let buckets = iter.store.layout.buckets;
if buckets != 0 {
iter.start = hash as usize & (buckets as usize - 1);
iter.load();
}
iter
}
fn load(&mut self) {
let start = self.store.layout.start as usize + self.start;
let bytes = unsafe {
&*self
.store
.owner
.bytes()
.as_ptr()
.add(start)
.cast::<[u8; 32]>()
};
let (vacant, matched) = group_masks(bytes, (self.hash >> 57) as u8);
self.bits = matched & (vacant.wrapping_sub(1) & !vacant);
self.done = vacant != 0;
}
pub fn into_owner(self) -> Q {
self.store.owner
}
}
impl<Q: compact::raw::Source> Iter<Q> {
fn next_entry(&mut self) -> Option<Entry> {
loop {
let Some(bits) = num::NonZero::new(self.bits) else {
if self.done {
return None;
}
self.start = self.store.bucket(self.start + 32).index;
self.load();
continue;
};
self.bits = bits.get() & (bits.get() - 1);
let bucket = self
.store
.bucket(self.start + bits.trailing_zeros() as usize);
let width = compact::Width::new(self.store.layout.domain) as usize;
let offset = bucket.index * width;
let start = self.store.layout.plane() + (offset & !3);
let bytes = unsafe { self.store.owner.bytes().as_ptr().add(start) };
let word = u32::from_le(unsafe { bytes.cast::<u32>().read_unaligned() });
let mask = u32::MAX >> (32 - width * 8);
let entry = Entry {
bucket,
payload: Payload {
index: (word >> ((offset & 3) * 8)) & mask,
},
};
if Q::hash(self.store.value(entry.payload)) == self.hash {
return Some(entry);
}
}
}
}
impl<Q: compact::raw::Query> Iterator for Iter<Q> {
type Item = Q::Item;
fn next(&mut self) -> Option<Self::Item> {
let entry = self.next_entry()?;
Some(Q::get(self.store.value(entry.payload)))
}
}
const _: () = assert!(size_of::<Payload>() == size_of::<u32>());
impl<Q: compact::raw::Query> Store<Q> {
pub(in crate::depot::map::compact) fn find(
self,
hash: u64,
key: &Q::Item,
) -> Option<compact::Found<Q>>
where
Q: compact::raw::Remove,
Q::Item: Eq,
{
if self.layout.buckets == 0 {
return None;
}
let store = self;
let tag = (hash >> 57) as u8;
let mut bucket = store.bucket(hash as usize);
loop {
let resident = store.control(bucket).occupied()?;
if resident.0.value == tag {
let entry = store.read(resident);
let payload = entry.payload;
if Q::hash(store.value(payload)) == hash && Q::get(store.value(payload)) == *key {
return Some(entry.finish(store));
}
}
bucket = store.bucket(bucket.index + 1);
}
}
}
impl<Q: compact::raw::Query> Iter<Q> {
pub(in crate::depot::map::compact) fn entry(mut self, key: &Q::Item) -> compact::Entry<Q>
where
Q::Item: Eq,
{
while let Some(entry) = self.next_entry() {
if Q::get(self.store.value(entry.payload)) == *key {
return compact::Entry::Occupied(entry.finish(self.store));
}
}
compact::Entry::Vacant(self.into_owner())
}
}