pub mod raw;
pub mod rawkey;
pub type DagMapId = [u8];
const DAG_ID_BATCH: u128 = 128;
pub fn gen_dag_map_id_num() -> u128 {
use parking_lot::Mutex;
use std::{fs, sync::LazyLock};
struct DagIdAllocator {
next: u128,
ceiling: u128,
path: std::path::PathBuf,
}
impl DagIdAllocator {
fn init() -> Self {
let base = vsdb_core::common::vsdb_get_system_dir().to_owned();
let path = base.join("dag_id_ceiling");
let ceiling = match fs::read(&path) {
Ok(bytes) if bytes.len() == 16 => {
u128::from_le_bytes(bytes.try_into().unwrap())
}
_ => 0,
};
DagIdAllocator {
next: ceiling,
ceiling,
path,
}
}
fn alloc(&mut self) -> u128 {
if self.next >= self.ceiling {
let new_ceiling = self.next + DAG_ID_BATCH;
self.persist_ceiling(new_ceiling);
self.ceiling = new_ceiling;
}
self.next += 1;
self.next
}
fn persist_ceiling(&self, ceiling: u128) {
use std::io::Write;
let tmp = self.path.with_extension("tmp");
let mut f =
fs::File::create(&tmp).expect("dag_id_ceiling: create tmp failed");
f.write_all(&ceiling.to_le_bytes())
.expect("dag_id_ceiling: write failed");
f.sync_all().expect("dag_id_ceiling: fsync failed");
fs::rename(&tmp, &self.path).expect("dag_id_ceiling: rename failed");
}
}
static ALLOC: LazyLock<Mutex<DagIdAllocator>> =
LazyLock::new(|| Mutex::new(DagIdAllocator::init()));
ALLOC.lock().alloc()
}