use core::ops::Bound;
use rand::rng as thread_rng;
use crate::flatdir::layout::{ROOT_PATH_SEGMENT, data_region};
use crate::flatdir::ops;
use crate::key::validate_dir;
use crate::rawkv::RawKv;
use crate::stream::KvPair;
pub use crate::flatdir::error::FlatError;
pub struct FlatEngine<R: RawKv> {
raw: R,
}
impl<R: RawKv> FlatEngine<R> {
pub fn new(raw: R) -> Self {
Self { raw }
}
pub fn raw(&self) -> &R {
&self.raw
}
pub fn raw_mut(&mut self) -> &mut R {
&mut self.raw
}
fn layer_path<'a>(dir: &[&'a [u8]]) -> Vec<&'a [u8]> {
let mut v: Vec<&'a [u8]> = Vec::with_capacity(dir.len() + 1);
v.push(ROOT_PATH_SEGMENT.as_bytes());
v.extend_from_slice(dir);
v
}
pub fn prefix_of(&self, dir: &[&[u8]]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
ops::check_version_read(&self.raw)?;
ops::find(&self.raw, &Self::layer_path(dir))
}
pub fn allocate_dir(&mut self, dir: &[&[u8]]) -> Result<Vec<u8>, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
let mut rng = thread_rng();
ops::create_or_open(&mut self.raw, &Self::layer_path(dir), true, &mut rng)
.map(|p| p.expect("create_or_open with creation returns Some"))
}
pub fn get(&self, dir: &[&[u8]], key: &[u8]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir)? else {
return Ok(None);
};
let mut raw_key = prefix;
raw_key.extend_from_slice(key);
Ok(self.raw.get(&raw_key)?)
}
pub fn scan(
&self,
dir: &[&[u8]],
start: Bound<&[u8]>,
end: Bound<&[u8]>,
forward: bool,
) -> Result<Vec<KvPair>, FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir)? else {
return Ok(Vec::new());
};
let owned = map_bounds(&prefix, start, end);
if raw_range_empty(&owned.0, &owned.1) {
return Ok(Vec::new());
}
let (rs, re) = bounds_ref(&owned);
let rows = self.raw.scan(rs, re, forward)?;
let plen = prefix.len();
Ok(rows
.into_iter()
.map(|pair| KvPair {
key: pair.key[plen..].to_vec(),
value: pair.value,
})
.collect())
}
pub fn data_bounds(
&self,
dir: &[&[u8]],
start: Bound<&[u8]>,
end: Bound<&[u8]>,
) -> Result<Option<DataBounds>, FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir)? else {
return Ok(None);
};
let (rs, re) = map_bounds(&prefix, start, end);
if raw_range_empty(&rs, &re) {
return Ok(None);
}
Ok(Some(DataBounds {
prefix,
start: rs,
end: re,
}))
}
pub fn set(
&mut self,
dir: &[&[u8]],
key: &[u8],
value: &[u8],
) -> Result<(), FlatError<R::Error>> {
let prefix = self.allocate_dir(dir)?;
let mut raw_key = prefix;
raw_key.extend_from_slice(key);
self.raw.insert(&raw_key, value)?;
Ok(())
}
pub fn delete(&mut self, dir: &[&[u8]], key: &[u8]) -> Result<(), FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir)? else {
return Ok(());
};
let mut raw_key = prefix;
raw_key.extend_from_slice(key);
self.raw.delete(&raw_key)?;
Ok(())
}
pub fn clear_range(
&mut self,
dir: &[&[u8]],
start: Bound<&[u8]>,
end: Bound<&[u8]>,
) -> Result<(), FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir)? else {
return Ok(());
};
let owned = map_bounds(&prefix, start, end);
if raw_range_empty(&owned.0, &owned.1) {
return Ok(());
}
let (rs, re) = bounds_ref(&owned);
self.raw.clear_range(rs, re)?;
Ok(())
}
pub fn list_dirs(&self, dir: &[&[u8]]) -> Result<Vec<Vec<u8>>, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
ops::check_version_read(&self.raw)?;
let Some(prefix) = ops::find(&self.raw, &Self::layer_path(dir))? else {
return Ok(Vec::new());
};
let names = ops::list_children(&self.raw, &prefix)?;
Ok(names.into_iter().map(|s| s.into_bytes()).collect())
}
pub fn dir_exists(&self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
ops::check_version_read(&self.raw)?;
Ok(ops::find(&self.raw, &Self::layer_path(dir))?.is_some())
}
pub fn remove_dir(&mut self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
if dir.is_empty() {
return Err(FlatError::Key(crate::key::KeyError::RootNotRemovable));
}
ops::check_version_read(&self.raw)?;
ops::remove_dir(&mut self.raw, &Self::layer_path(dir))
}
}
pub struct DataBounds {
pub prefix: Vec<u8>,
pub start: Bound<Vec<u8>>,
pub end: Bound<Vec<u8>>,
}
impl core::fmt::Debug for DataBounds {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("DataBounds")
.field("prefix_len", &self.prefix.len())
.field("start", &bound_len(&self.start))
.field("end", &bound_len(&self.end))
.finish()
}
}
fn bound_len(b: &Bound<Vec<u8>>) -> String {
match b {
Bound::Unbounded => "unbounded".to_owned(),
Bound::Included(v) => format!("incl({} bytes)", v.len()),
Bound::Excluded(v) => format!("excl({} bytes)", v.len()),
}
}
fn bounds_ref(b: &(Bound<Vec<u8>>, Bound<Vec<u8>>)) -> (Bound<&[u8]>, Bound<&[u8]>) {
(bound_ref(&b.0), bound_ref(&b.1))
}
fn bound_ref(b: &Bound<Vec<u8>>) -> Bound<&[u8]> {
match b {
Bound::Unbounded => Bound::Unbounded,
Bound::Included(v) => Bound::Included(v.as_slice()),
Bound::Excluded(v) => Bound::Excluded(v.as_slice()),
}
}
fn data_end_exclusive(prefix: &[u8]) -> Vec<u8> {
match data_region(prefix).1 {
Bound::Excluded(b) => b,
_ => unreachable!("data_region end is always Excluded"),
}
}
fn map_bounds(
prefix: &[u8],
start: Bound<&[u8]>,
end: Bound<&[u8]>,
) -> (Bound<Vec<u8>>, Bound<Vec<u8>>) {
let mk = |k: &[u8]| {
let mut raw = prefix.to_vec();
raw.extend_from_slice(k);
raw
};
let rs = match start {
Bound::Unbounded => Bound::Included(prefix.to_vec()),
Bound::Included(k) => Bound::Included(mk(k)),
Bound::Excluded(k) => Bound::Excluded(mk(k)),
};
let re = match end {
Bound::Unbounded => Bound::Excluded(data_end_exclusive(prefix)),
Bound::Excluded(k) => Bound::Excluded(mk(k)),
Bound::Included(k) => {
let mut raw = mk(k);
raw.push(0x00);
Bound::Excluded(raw)
}
};
(rs, re)
}
fn raw_range_empty(start: &Bound<Vec<u8>>, end: &Bound<Vec<u8>>) -> bool {
match (start, end) {
(Bound::Included(a), Bound::Excluded(b)) => a >= b,
(Bound::Excluded(a), Bound::Excluded(b)) => a >= b,
(Bound::Unbounded, _) => false,
(_, Bound::Unbounded) => false,
_ => unreachable!("end bounds are always Excluded"),
}
}
#[cfg(test)]
pub(crate) struct Mem {
map: core::cell::RefCell<std::collections::BTreeMap<Vec<u8>, Vec<u8>>>,
}
#[cfg(test)]
impl Default for Mem {
fn default() -> Self {
Self {
map: core::cell::RefCell::new(std::collections::BTreeMap::new()),
}
}
}
#[cfg(test)]
impl RawKv for Mem {
type Error = std::convert::Infallible;
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
Ok(self.map.borrow().get(key).cloned())
}
fn scan(
&self,
start: Bound<&[u8]>,
end: Bound<&[u8]>,
forward: bool,
) -> Result<Vec<KvPair>, Self::Error> {
let map = self.map.borrow();
let rows: Vec<KvPair> = map
.iter()
.filter(|(k, _)| {
let k = &k[..];
let above = match start {
Bound::Unbounded => true,
Bound::Included(s) => k >= s,
Bound::Excluded(s) => k > s,
};
let below = match end {
Bound::Unbounded => true,
Bound::Excluded(e) => k < e,
Bound::Included(e) => k <= e,
};
above && below
})
.map(|(k, v)| KvPair {
key: k.clone(),
value: v.clone(),
})
.collect();
if forward {
Ok(rows)
} else {
Ok(rows.into_iter().rev().collect())
}
}
fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<(), Self::Error> {
self.map.borrow_mut().insert(key.to_vec(), value.to_vec());
Ok(())
}
fn delete(&mut self, key: &[u8]) -> Result<(), Self::Error> {
self.map.borrow_mut().remove(key);
Ok(())
}
fn clear_range(&mut self, start: Bound<&[u8]>, end: Bound<&[u8]>) -> Result<(), Self::Error> {
let mut map = self.map.borrow_mut();
let keys: Vec<Vec<u8>> = map
.keys()
.filter(|k| {
let k = &k[..];
let above = match start {
Bound::Unbounded => true,
Bound::Included(s) => k >= s,
Bound::Excluded(s) => k > s,
};
let below = match end {
Bound::Unbounded => true,
Bound::Excluded(e) => k < e,
Bound::Included(e) => k <= e,
};
above && below
})
.cloned()
.collect();
for k in keys {
map.remove(&k);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::key::KeyError;
fn engine() -> FlatEngine<Mem> {
FlatEngine::new(Mem::default())
}
fn ok<T>(r: Result<T, FlatError<std::convert::Infallible>>) -> T {
r.unwrap()
}
#[test]
fn fresh_reads_return_empty_and_first_write_initialises() {
let mut e = engine();
assert_eq!(ok(e.prefix_of(&[])), None);
assert_eq!(ok(e.get(&[], b"k")), None);
assert!(ok(e.scan(&[], Bound::Unbounded, Bound::Unbounded, true)).is_empty());
assert!(ok(e.list_dirs(&[])).is_empty());
assert!(!ok(e.dir_exists(&[])));
assert!(!ok(e.remove_dir(&[b"a"])));
ok(e.set(&[], b"k", b"v"));
assert!(ok(e.dir_exists(&[])));
assert_eq!(ok(e.get(&[], b"k")), Some(b"v".to_vec()));
let version = e
.raw()
.map
.borrow()
.get(crate::flatdir::layout::VERSION_KEY)
.cloned();
assert_eq!(
version,
Some(crate::flatdir::layout::LAYOUT_VERSION.to_vec())
);
}
#[test]
fn a_first_set_produces_exactly_nine_raw_rows() {
let mut e = engine();
ok(e.set(&[b"a"], b"k", b"v"));
let map = e.raw().map.borrow();
assert_eq!(map.len(), 9, "unexpected raw rows: {map:?}");
}
#[test]
fn reads_on_a_foreign_store_fail_closed() {
let mut e = engine();
let mut v = [0u8; 12];
v[0..4].copy_from_slice(&2u32.to_le_bytes());
e.raw_mut()
.insert(crate::flatdir::layout::VERSION_KEY, &v)
.unwrap();
assert_eq!(e.prefix_of(&[]), Err(FlatError::Foreign));
assert_eq!(e.get(&[], b"k"), Err(FlatError::Foreign));
assert_eq!(
e.scan(&[], Bound::Unbounded, Bound::Unbounded, true),
Err(FlatError::Foreign)
);
assert!(matches!(
e.data_bounds(&[], Bound::Unbounded, Bound::Unbounded),
Err(FlatError::Foreign)
));
assert_eq!(e.dir_exists(&[]), Err(FlatError::Foreign));
assert_eq!(e.list_dirs(&[]), Err(FlatError::Foreign));
assert_eq!(e.set(&[], b"k", b"v"), Err(FlatError::Foreign));
assert_eq!(e.remove_dir(&[b"a"]), Err(FlatError::Foreign));
}
#[test]
fn a_malformed_version_row_fails_closed() {
let mut e = engine();
e.raw_mut()
.insert(crate::flatdir::layout::VERSION_KEY, &[1, 0])
.unwrap();
assert_eq!(e.dir_exists(&[]), Err(FlatError::Foreign));
}
#[test]
fn a_corrupt_node_value_is_corrupt_not_a_panic() {
let mut e = engine();
e.set(&[b"dir"], b"k", b"v").unwrap();
let child_tag = crate::flatdir::layout::ROOT_NODE
.iter()
.copied()
.chain(std::iter::once(0x14))
.collect::<Vec<u8>>();
let row_key = e
.raw()
.map
.borrow()
.iter()
.find(|(k, _)| k.starts_with(&child_tag))
.expect("the anchor child row")
.0
.clone();
e.raw_mut()
.map
.borrow_mut()
.insert(row_key, vec![0x99, 0x00]);
assert_eq!(e.get(&[b"dir"], b"k"), Err(FlatError::Corrupt));
assert_eq!(
e.scan(&[b"dir"], Bound::Unbounded, Bound::Unbounded, true),
Err(FlatError::Corrupt)
);
assert_eq!(e.remove_dir(&[b"dir"]), Err(FlatError::Corrupt));
}
#[test]
fn allocation_is_recursive_and_stable() {
let mut e = engine();
let p = ok(e.allocate_dir(&[b"a", b"b"]));
assert_eq!(ok(e.prefix_of(&[b"a", b"b"])), Some(p.clone()));
let q = ok(e.allocate_dir(&[b"a", b"c"]));
assert_ne!(p, q);
assert!(ok(e.prefix_of(&[b"a"])).is_some());
let dirs: [[&[u8]; 2]; 2] = [[b"a" as &[u8], b"b"], [b"a" as &[u8], b"c"]];
for dir in dirs {
let p = ok(e.prefix_of(&dir)).unwrap();
assert!((0x0c..=0x1c).contains(&p[0]), "prefix {p:?}");
}
}
#[test]
fn many_allocations_stay_in_the_data_region() {
let mut e = engine();
for i in 0..300u32 {
let d = format!("d{i:03}").into_bytes();
let d = [d.as_slice()];
let p = ok(e.allocate_dir(&d));
assert!((0x0c..=0x1c).contains(&p[0]), "prefix {p:?} at {i}");
}
}
#[test]
fn resolve_missing_dir_is_none() {
let mut e = engine();
ok(e.set(&[], b"k", b"v"));
assert_eq!(ok(e.prefix_of(&[b"nope"])), None);
assert_eq!(ok(e.prefix_of(&[b"nope", b"deeper"])), None);
}
#[test]
fn set_get_delete_round_trips_per_dir() {
let mut e = engine();
ok(e.set(&[b"asset", b"btc"], b"k", b"v"));
assert_eq!(ok(e.get(&[b"asset", b"btc"], b"k")), Some(b"v".to_vec()));
assert_eq!(ok(e.get(&[b"asset"], b"k")), None);
assert_eq!(ok(e.get(&[b"btc"], b"k")), None);
ok(e.delete(&[b"asset", b"btc"], b"k"));
assert_eq!(ok(e.get(&[b"asset", b"btc"], b"k")), None);
}
#[test]
fn scan_orders_within_dir_only() {
let mut e = engine();
for k in [b"b", b"a", b"c"] {
ok(e.set(&[b"d"], k, k));
ok(e.set(&[b"other"], k, k));
}
let rows = ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, true));
let keys: Vec<Vec<u8>> = rows.iter().map(|p| p.key.clone()).collect();
assert_eq!(keys, vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec()]);
let rows = ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, false));
assert_eq!(rows.first().unwrap().key, b"c".to_vec());
}
#[test]
fn scan_bound_matrix() {
let mut e = engine();
for k in [b"a", b"b", b"c", b"\xff"] {
ok(e.set(&[b"d"], k, b"v"));
}
let get = |s: core::ops::Bound<&[u8]>,
en: core::ops::Bound<&[u8]>,
e: &FlatEngine<Mem>|
-> Vec<Vec<u8>> {
ok(e.scan(&[b"d"], s, en, true))
.into_iter()
.map(|pair| pair.key)
.collect()
};
assert_eq!(
get(Bound::Included(b"b"), Bound::Excluded(b"c"), &e),
vec![b"b".to_vec()]
);
assert_eq!(
get(Bound::Excluded(b"b"), Bound::Included(b"c"), &e),
vec![b"c".to_vec()]
);
assert_eq!(
get(Bound::Excluded(&[0xFFu8]), Bound::Unbounded, &e),
Vec::<Vec<u8>>::new()
);
assert_eq!(
get(Bound::Unbounded, Bound::Included(&[0xFFu8]), &e),
vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec(), vec![0xFF]]
);
assert_eq!(
get(Bound::Included(&[0xFFu8]), Bound::Unbounded, &e),
vec![vec![0xFF]]
);
assert_eq!(
get(Bound::Excluded(&[0xFFu8]), Bound::Excluded(&[0xFFu8]), &e),
Vec::<Vec<u8>>::new()
);
}
#[test]
fn clear_range_clears_within_dir_only() {
let mut e = engine();
for k in [b"a", b"b", b"c"] {
ok(e.set(&[b"d"], k, b"v"));
ok(e.set(&[b"e"], k, b"v"));
}
ok(e.clear_range(&[b"d"], Bound::Included(b"b"), Bound::Excluded(b"c")));
assert_eq!(ok(e.get(&[b"d"], b"a")), Some(b"v".to_vec()));
assert_eq!(ok(e.get(&[b"d"], b"b")), None);
assert_eq!(ok(e.get(&[b"d"], b"c")), Some(b"v".to_vec()));
assert_eq!(ok(e.get(&[b"e"], b"b")), Some(b"v".to_vec()));
ok(e.clear_range(&[b"d"], Bound::Unbounded, Bound::Unbounded));
assert!(ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, true)).is_empty());
assert!(ok(e.dir_exists(&[b"d"])));
}
#[test]
fn nav_list_exists_remove() {
let mut e = engine();
ok(e.set(&[b"a", b"1"], b"k", b"v"));
ok(e.set(&[b"a", b"2"], b"k", b"v"));
ok(e.set(&[b"b"], b"k", b"v"));
assert_eq!(ok(e.list_dirs(&[])), vec![b"a".to_vec(), b"b".to_vec()]);
assert_eq!(ok(e.list_dirs(&[b"a"])), vec![b"1".to_vec(), b"2".to_vec()]);
assert!(ok(e.dir_exists(&[b"a"])));
assert!(ok(e.dir_exists(&[b"a", b"1"])));
assert!(!ok(e.dir_exists(&[b"a", b"3"])));
ok(e.allocate_dir(&[b"empty"]));
assert!(ok(e.dir_exists(&[b"empty"])));
assert!(ok(e.list_dirs(&[b"empty"])).is_empty());
assert!(ok(e.list_dirs(&[b"nope"])).is_empty());
assert!(!ok(e.dir_exists(&[b"nope"])));
}
#[test]
fn nav_remove_is_recursive() {
let mut e = engine();
ok(e.set(&[b"a", b"b", b"c"], b"k1", b"v1"));
ok(e.set(&[b"a", b"b"], b"k2", b"v2"));
ok(e.set(&[b"a", b"d"], b"k3", b"v3"));
ok(e.set(&[b"z"], b"k4", b"v4"));
assert!(ok(e.remove_dir(&[b"a", b"b"])));
assert_eq!(ok(e.get(&[b"a", b"b", b"c"], b"k1")), None);
assert_eq!(ok(e.get(&[b"a", b"b"], b"k2")), None);
assert_eq!(ok(e.get(&[b"a", b"d"], b"k3")), Some(b"v3".to_vec()));
assert!(ok(e.dir_exists(&[b"a"])));
assert!(!ok(e.dir_exists(&[b"a", b"b"])));
assert!(ok(e.remove_dir(&[b"a", b"d"])));
assert_eq!(ok(e.get(&[b"a", b"d"], b"k3")), None);
assert!(!ok(e.remove_dir(&[b"a", b"b"])));
assert_eq!(ok(e.get(&[b"z"], b"k4")), Some(b"v4".to_vec()));
}
#[test]
fn nav_root_is_not_removable() {
let mut e = engine();
ok(e.set(&[], b"k", b"v"));
assert_eq!(
e.remove_dir(&[]),
Err(FlatError::Key(KeyError::RootNotRemovable))
);
assert!(ok(e.dir_exists(&[])));
}
#[test]
fn nav_rejects_non_utf8() {
let mut e = engine();
let seg: &[u8] = b"\xFF\xFE";
let bad = [seg];
assert_eq!(
e.list_dirs(&bad),
Err(FlatError::Key(KeyError::DirSegmentNotUtf8 { segment: 0 }))
);
assert_eq!(
e.remove_dir(&bad),
Err(FlatError::Key(KeyError::DirSegmentNotUtf8 { segment: 0 }))
);
}
#[test]
fn remove_and_recreate_work() {
let mut e = engine();
ok(e.set(&[b"x"], b"k", b"v1"));
let p1 = ok(e.prefix_of(&[b"x"])).unwrap();
assert!(ok(e.remove_dir(&[b"x"])));
assert!(!ok(e.dir_exists(&[b"x"])));
assert_eq!(ok(e.get(&[b"x"], b"k")), None);
ok(e.set(&[b"x"], b"k", b"v2"));
let p2 = ok(e.prefix_of(&[b"x"])).unwrap();
assert_eq!(ok(e.get(&[b"x"], b"k")), Some(b"v2".to_vec()));
if p1 == p2 {
assert_eq!(
ok(e.scan(&[b"x"], Bound::Unbounded, Bound::Unbounded, true)).len(),
1
);
}
assert!(ops::validate(e.raw()).is_ok());
}
}