armdb 0.1.13

sharded bitcask key-value storage optimized for NVMe
Documentation
use std::sync::Arc;

use crate::{DbResult, FixedConfig, FixedMap};

/// Centralized sequential ID generator backed by a `FixedMap<[u8; 8], 8>`.
///
/// Shared via `Arc<SeqGen>` between [`Db`](super::tree_db::Db) and collections.
pub struct SeqGen {
    map: FixedMap<[u8; 8], 8>,
}

impl SeqGen {
    pub(crate) fn open(path: impl AsRef<std::path::Path>) -> DbResult<Arc<Self>> {
        Ok(Arc::new(Self {
            map: FixedMap::<[u8; 8], 8>::open(path, FixedConfig::default())?,
        }))
    }

    /// Generate the next sequential ID for a named collection.
    pub fn next_id(&self, name: &str) -> DbResult<u64> {
        let key = xxhash_rust::xxh3::xxh3_64(name.as_bytes()).to_le_bytes();
        let val = self.map.get(&key).unwrap_or([0u8; 8]);
        let id = u64::from_le_bytes(val);
        let next = id + 1;
        self.map.put(&key, &next.to_le_bytes())?;
        Ok(next)
    }

    /// Flush buffers to disk without consuming self.
    pub fn flush(&self) -> DbResult<()> {
        self.map.flush()
    }
}