use std::marker::PhantomData;
use std::rc::Rc;
use super::*;
pub(crate) struct GenerationLocks<K: Key + Hash + Eq + Send + Sync + 'static> {
guards: Vec<(usize, MutexGuard<'static, ShardIndex<K, GenLoc>>)>,
generation: Arc<Generation<K>>,
_local: PhantomData<Rc<()>>,
}
impl<K: Key + Hash + Eq + Send + Sync + 'static> Generation<K> {
pub(crate) fn lock_owned(self: &Arc<Self>, shards: &[usize]) -> DbResult<GenerationLocks<K>> {
let mut shards = shards.to_vec();
if shards.iter().any(|&shard| shard >= self.shard_count) {
return Err(DbError::Internal("segmented index shard is out of range"));
}
shards.sort_unstable();
shards.dedup();
let mut held = GenerationLocks {
guards: Vec::with_capacity(shards.len()),
generation: self.clone(),
_local: PhantomData,
};
for shard in shards {
let guard = sync::lock(&held.generation.indexes[shard]);
let guard = unsafe {
std::mem::transmute::<
MutexGuard<'_, ShardIndex<K, GenLoc>>,
MutexGuard<'static, ShardIndex<K, GenLoc>>,
>(guard)
};
held.guards.push((shard, guard));
}
Ok(held)
}
}
impl<K: Key + Hash + Eq + Send + Sync + 'static> GenerationLocks<K> {
pub(crate) fn generation(&self) -> &Arc<Generation<K>> {
&self.generation
}
fn position(&self, h: u64) -> DbResult<usize> {
let shard = self.generation.shard_of(h);
self.guards
.binary_search_by_key(&shard, |(s, _)| *s)
.map_err(|_| DbError::Internal("segmented key belongs to an unlocked shard"))
}
pub(crate) fn probe(&self, h: u64, key: &K) -> DbResult<GenProbe> {
let index = &self.guards[self.position(h)?].1;
Ok(match index.get(key) {
None => GenProbe::Absent,
Some(found) if found.tombstone => GenProbe::Tombstone,
Some(_) => GenProbe::Live,
})
}
pub(crate) fn lookup(&self, h: u64, key: &K) -> DbResult<GenLookup> {
let index = &self.guards[self.position(h)?].1;
Ok(match index.get(key) {
None => GenLookup::Absent,
Some(found) if found.tombstone => GenLookup::Tombstone,
Some(found) => GenLookup::Live(self.generation.read_value(h, &found.loc)?),
})
}
pub(crate) fn append(
&mut self,
h: u64,
key: &K,
value: Option<&[u8]>,
limits: Limits,
) -> DbResult<()> {
let pos = self.position(h)?;
let (shard, index) = &mut self.guards[pos];
let (_, should_sync) = self
.generation
.append_locked(*shard, index, key, value, limits)?;
self.generation.sync_if_asked(*shard, should_sync)
}
}