mindb 0.1.2

Lightweight embedded key–value store with write-ahead log and zstd compression.
Documentation
//! Time-fence index used for timestamp-bound scans.
#![allow(dead_code)]

use std::collections::BTreeMap;
use std::sync::Arc;

use parking_lot::RwLock;

use crate::index::{SequenceNumber, VersionPointer};

#[derive(Clone, Default)]
pub struct TimeFenceIndex {
    inner: Arc<RwLock<BTreeMap<i64, HashMapForTimestamp>>>,
}

type HashMapForTimestamp = std::collections::HashMap<Vec<u8>, VersionPointer>;

impl TimeFenceIndex {
    /// Creates a new empty time-fence index.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(RwLock::new(BTreeMap::new())),
        }
    }

    /// Adds a key-pointer pair for the provided timestamp.
    pub fn insert(&self, timestamp: i64, key: Vec<u8>, pointer: VersionPointer) {
        let mut guard = self.inner.write();
        let entry = guard.entry(timestamp).or_default();
        match entry.get_mut(&key) {
            Some(existing) if existing.sequence >= pointer.sequence => return,
            Some(existing) => *existing = pointer,
            None => {
                entry.insert(key, pointer);
            }
        }
    }

    /// Returns all keys visible within the inclusive timestamp range.
    pub fn scan_range(
        &self,
        start: i64,
        end: i64,
        snapshot: SequenceNumber,
    ) -> Vec<(Vec<u8>, VersionPointer)> {
        let guard = self.inner.read();
        guard
            .range(start..=end)
            .flat_map(|(_, mapping)| {
                mapping
                    .iter()
                    .filter(|(_, pointer)| pointer.is_visible_at(snapshot))
                    .map(|(key, pointer)| (key.clone(), pointer.clone()))
                    .collect::<Vec<_>>()
            })
            .collect()
    }
}