use std::cell::RefCell;
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
}
}
struct PinningTable {
heap: SnapshotDoubleIndexHeap,
}
impl PinningTable {
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(),
}
}
}
thread_local! {
static PINNING_TABLE: RefCell<PinningTable> = RefCell::new(PinningTable::new());
}
#[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);
PINNING_TABLE.with(|cell| cell.borrow_mut().add(pinned_id))
}
pub fn release_pinning(handle: PinHandle) {
if !handle.is_valid() {
return;
}
PINNING_TABLE.with(|cell| {
cell.borrow_mut().remove(handle);
});
}
pub fn lowest_pinned_snapshot() -> Option<SnapshotId> {
PINNING_TABLE.with(|cell| cell.borrow().lowest_pinned())
}
pub fn pin_count() -> usize {
PINNING_TABLE.with(|cell| cell.borrow().pin_count())
}
pub fn debug_snapshot_pinning_stats() -> SnapshotPinningDebugStats {
PINNING_TABLE.with(|cell| cell.borrow().debug_stats())
}
#[cfg(test)]
pub fn reset_pinning_table() {
PINNING_TABLE.with(|cell| {
let mut table = cell.borrow_mut();
table.heap = SnapshotDoubleIndexHeap::new();
});
}
#[cfg(test)]
#[path = "tests/snapshot_pinning_tests.rs"]
mod tests;