mindb 0.1.2

Lightweight embedded key–value store with write-ahead log and zstd compression.
Documentation
//! Slug secondary index mapping human readable identifiers to keys.
#![allow(dead_code)]

use std::collections::HashMap;
use std::sync::Arc;

use parking_lot::RwLock;

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

#[derive(Clone, Default)]
pub struct SlugMap {
    inner: Arc<RwLock<HashMap<String, HashMap<Vec<u8>, VersionPointer>>>>,
}

impl SlugMap {
    /// Creates a new empty slug map.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Associates the slug to the provided key and pointer.
    pub fn insert(&self, slug: impl Into<String>, key: Vec<u8>, pointer: VersionPointer) {
        let slug = slug.into();
        let mut guard = self.inner.write();
        let entry = guard.entry(slug).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 the most recent pointer for the slug that is visible under the snapshot.
    pub fn get_latest(
        &self,
        slug: &str,
        snapshot: SequenceNumber,
    ) -> Option<(Vec<u8>, VersionPointer)> {
        let guard = self.inner.read();
        guard.get(slug).and_then(|mapping| {
            mapping
                .iter()
                .filter(|(_, pointer)| pointer.is_visible_at(snapshot))
                .max_by_key(|(_, pointer)| pointer.sequence)
                .map(|(key, pointer)| (key.clone(), pointer.clone()))
        })
    }
}