use crate::{
snapshot_double_index_heap::{SnapshotDoubleIndexHeap, SnapshotDoubleIndexHeapDebugStats},
snapshot_id_set::{SnapshotId, SnapshotIdSet},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PinHandle(usize);
impl PinHandle {
pub const INVALID: PinHandle = PinHandle(0);
pub fn is_valid(&self) -> bool {
self.0 != 0
}
}
pub(crate) struct PinningTable {
heap: SnapshotDoubleIndexHeap,
}
impl PinningTable {
pub(crate) const fn new() -> Self {
Self {
heap: SnapshotDoubleIndexHeap::new(),
}
}
fn add(&mut self, snapshot_id: SnapshotId) -> PinHandle {
let heap_handle = self.heap.add(snapshot_id);
PinHandle(heap_handle + 1)
}
fn remove(&mut self, handle: PinHandle) -> bool {
if !handle.is_valid() {
return false;
}
let heap_handle = handle.0 - 1;
if heap_handle < usize::MAX {
self.heap.remove(heap_handle);
true
} else {
false
}
}
fn lowest_pinned(&self) -> Option<SnapshotId> {
if self.heap.is_empty() {
None
} else {
Some(self.heap.lowest_or_default(0))
}
}
fn pin_count(&self) -> usize {
self.heap.len()
}
fn debug_stats(&self) -> SnapshotPinningDebugStats {
SnapshotPinningDebugStats {
pin_count: self.pin_count(),
lowest_pinned_snapshot: self.lowest_pinned(),
heap: self.heap.debug_stats(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SnapshotPinningDebugStats {
pub pin_count: usize,
pub lowest_pinned_snapshot: Option<SnapshotId>,
pub heap: SnapshotDoubleIndexHeapDebugStats,
}
pub fn track_pinning(snapshot_id: SnapshotId, invalid: &SnapshotIdSet) -> PinHandle {
let pinned_id = invalid.lowest(snapshot_id);
crate::thread_state::snapshots(|state| state.pinning.borrow_mut().add(pinned_id))
}
pub fn release_pinning(handle: PinHandle) {
if !handle.is_valid() {
return;
}
crate::thread_state::snapshots(|state| {
state.pinning.borrow_mut().remove(handle);
});
}
pub fn lowest_pinned_snapshot() -> Option<SnapshotId> {
crate::thread_state::snapshots(|state| state.pinning.borrow().lowest_pinned())
}
pub fn pin_count() -> usize {
crate::thread_state::snapshots(|state| state.pinning.borrow().pin_count())
}
pub fn debug_snapshot_pinning_stats() -> SnapshotPinningDebugStats {
crate::thread_state::snapshots(|state| state.pinning.borrow().debug_stats())
}
#[cfg(test)]
pub fn reset_pinning_table() {
crate::thread_state::snapshots(|state| {
state.pinning.borrow_mut().heap = SnapshotDoubleIndexHeap::new();
});
}
#[cfg(test)]
#[path = "tests/snapshot_pinning_tests.rs"]
mod tests;