1use core::ops::Bound;
22use rand::rng as thread_rng;
23
24use crate::flatdir::layout::{ROOT_PATH_SEGMENT, data_region};
25use crate::flatdir::ops;
26use crate::key::validate_dir;
27use crate::rawkv::RawKv;
28use crate::stream::KvPair;
29
30pub use crate::flatdir::error::FlatError;
33
34pub struct FlatEngine<R: RawKv> {
44 raw: R,
45}
46
47impl<R: RawKv> FlatEngine<R> {
48 pub fn new(raw: R) -> Self {
50 Self { raw }
51 }
52
53 pub fn raw(&self) -> &R {
56 &self.raw
57 }
58
59 pub fn raw_mut(&mut self) -> &mut R {
61 &mut self.raw
62 }
63
64 fn layer_path<'a>(dir: &[&'a [u8]]) -> Vec<&'a [u8]> {
67 let mut v: Vec<&'a [u8]> = Vec::with_capacity(dir.len() + 1);
68 v.push(ROOT_PATH_SEGMENT.as_bytes());
69 v.extend_from_slice(dir);
70 v
71 }
72
73 pub fn prefix_of(&self, dir: &[&[u8]]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
83 validate_dir(dir).map_err(FlatError::Key)?;
84 ops::check_version_read(&self.raw)?;
85 ops::find(&self.raw, &Self::layer_path(dir))
86 }
87
88 pub fn allocate_dir(&mut self, dir: &[&[u8]]) -> Result<Vec<u8>, FlatError<R::Error>> {
99 validate_dir(dir).map_err(FlatError::Key)?;
100 let mut rng = thread_rng();
101 ops::create_or_open(&mut self.raw, &Self::layer_path(dir), true, &mut rng)
102 .map(|p| p.expect("create_or_open with creation returns Some"))
103 }
104
105 pub fn get(&self, dir: &[&[u8]], key: &[u8]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
109 let Some(prefix) = self.prefix_of(dir)? else {
110 return Ok(None);
111 };
112 let mut raw_key = prefix;
113 raw_key.extend_from_slice(key);
114 Ok(self.raw.get(&raw_key)?)
115 }
116
117 pub fn scan(
121 &self,
122 dir: &[&[u8]],
123 start: Bound<&[u8]>,
124 end: Bound<&[u8]>,
125 forward: bool,
126 ) -> Result<Vec<KvPair>, FlatError<R::Error>> {
127 let Some(prefix) = self.prefix_of(dir)? else {
128 return Ok(Vec::new());
129 };
130 let owned = map_bounds(&prefix, start, end);
131 if raw_range_empty(&owned.0, &owned.1) {
132 return Ok(Vec::new());
133 }
134 let (rs, re) = bounds_ref(&owned);
135 let rows = self.raw.scan(rs, re, forward)?;
136 let plen = prefix.len();
137 Ok(rows
138 .into_iter()
139 .map(|pair| KvPair {
140 key: pair.key[plen..].to_vec(),
141 value: pair.value,
142 })
143 .collect())
144 }
145
146 pub fn data_bounds(
158 &self,
159 dir: &[&[u8]],
160 start: Bound<&[u8]>,
161 end: Bound<&[u8]>,
162 ) -> Result<Option<DataBounds>, FlatError<R::Error>> {
163 let Some(prefix) = self.prefix_of(dir)? else {
164 return Ok(None);
165 };
166 let (rs, re) = map_bounds(&prefix, start, end);
167 if raw_range_empty(&rs, &re) {
168 return Ok(None);
169 }
170 Ok(Some(DataBounds {
171 prefix,
172 start: rs,
173 end: re,
174 }))
175 }
176
177 pub fn set(
180 &mut self,
181 dir: &[&[u8]],
182 key: &[u8],
183 value: &[u8],
184 ) -> Result<(), FlatError<R::Error>> {
185 let prefix = self.allocate_dir(dir)?;
186 let mut raw_key = prefix;
187 raw_key.extend_from_slice(key);
188 self.raw.insert(&raw_key, value)?;
189 Ok(())
190 }
191
192 pub fn delete(&mut self, dir: &[&[u8]], key: &[u8]) -> Result<(), FlatError<R::Error>> {
195 let Some(prefix) = self.prefix_of(dir)? else {
196 return Ok(());
197 };
198 let mut raw_key = prefix;
199 raw_key.extend_from_slice(key);
200 self.raw.delete(&raw_key)?;
201 Ok(())
202 }
203
204 pub fn clear_range(
207 &mut self,
208 dir: &[&[u8]],
209 start: Bound<&[u8]>,
210 end: Bound<&[u8]>,
211 ) -> Result<(), FlatError<R::Error>> {
212 let Some(prefix) = self.prefix_of(dir)? else {
213 return Ok(());
214 };
215 let owned = map_bounds(&prefix, start, end);
216 if raw_range_empty(&owned.0, &owned.1) {
217 return Ok(());
218 }
219 let (rs, re) = bounds_ref(&owned);
220 self.raw.clear_range(rs, re)?;
221 Ok(())
222 }
223
224 pub fn list_dirs(&self, dir: &[&[u8]]) -> Result<Vec<Vec<u8>>, FlatError<R::Error>> {
229 validate_dir(dir).map_err(FlatError::Key)?;
230 ops::check_version_read(&self.raw)?;
231 let Some(prefix) = ops::find(&self.raw, &Self::layer_path(dir))? else {
232 return Ok(Vec::new());
233 };
234 let names = ops::list_children(&self.raw, &prefix)?;
235 Ok(names.into_iter().map(|s| s.into_bytes()).collect())
236 }
237
238 pub fn dir_exists(&self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
243 validate_dir(dir).map_err(FlatError::Key)?;
244 ops::check_version_read(&self.raw)?;
245 Ok(ops::find(&self.raw, &Self::layer_path(dir))?.is_some())
246 }
247
248 pub fn remove_dir(&mut self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
252 validate_dir(dir).map_err(FlatError::Key)?;
253 if dir.is_empty() {
254 return Err(FlatError::Key(crate::key::KeyError::RootNotRemovable));
259 }
260 ops::check_version_read(&self.raw)?;
261 ops::remove_dir(&mut self.raw, &Self::layer_path(dir))
262 }
263}
264
265pub struct DataBounds {
271 pub prefix: Vec<u8>,
273 pub start: Bound<Vec<u8>>,
275 pub end: Bound<Vec<u8>>,
277}
278
279impl core::fmt::Debug for DataBounds {
280 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
281 f.debug_struct("DataBounds")
284 .field("prefix_len", &self.prefix.len())
285 .field("start", &bound_len(&self.start))
286 .field("end", &bound_len(&self.end))
287 .finish()
288 }
289}
290
291fn bound_len(b: &Bound<Vec<u8>>) -> String {
292 match b {
293 Bound::Unbounded => "unbounded".to_owned(),
294 Bound::Included(v) => format!("incl({} bytes)", v.len()),
295 Bound::Excluded(v) => format!("excl({} bytes)", v.len()),
296 }
297}
298
299fn bounds_ref(b: &(Bound<Vec<u8>>, Bound<Vec<u8>>)) -> (Bound<&[u8]>, Bound<&[u8]>) {
302 (bound_ref(&b.0), bound_ref(&b.1))
303}
304
305fn bound_ref(b: &Bound<Vec<u8>>) -> Bound<&[u8]> {
306 match b {
307 Bound::Unbounded => Bound::Unbounded,
308 Bound::Included(v) => Bound::Included(v.as_slice()),
309 Bound::Excluded(v) => Bound::Excluded(v.as_slice()),
310 }
311}
312
313fn data_end_exclusive(prefix: &[u8]) -> Vec<u8> {
318 match data_region(prefix).1 {
319 Bound::Excluded(b) => b,
320 _ => unreachable!("data_region end is always Excluded"),
321 }
322}
323
324fn map_bounds(
349 prefix: &[u8],
350 start: Bound<&[u8]>,
351 end: Bound<&[u8]>,
352) -> (Bound<Vec<u8>>, Bound<Vec<u8>>) {
353 let mk = |k: &[u8]| {
354 let mut raw = prefix.to_vec();
355 raw.extend_from_slice(k);
356 raw
357 };
358 let rs = match start {
359 Bound::Unbounded => Bound::Included(prefix.to_vec()),
360 Bound::Included(k) => Bound::Included(mk(k)),
361 Bound::Excluded(k) => Bound::Excluded(mk(k)),
362 };
363 let re = match end {
364 Bound::Unbounded => Bound::Excluded(data_end_exclusive(prefix)),
365 Bound::Excluded(k) => Bound::Excluded(mk(k)),
366 Bound::Included(k) => {
367 let mut raw = mk(k);
368 raw.push(0x00);
369 Bound::Excluded(raw)
370 }
371 };
372 (rs, re)
373}
374
375fn raw_range_empty(start: &Bound<Vec<u8>>, end: &Bound<Vec<u8>>) -> bool {
380 match (start, end) {
381 (Bound::Included(a), Bound::Excluded(b)) => a >= b,
382 (Bound::Excluded(a), Bound::Excluded(b)) => a >= b,
383 (Bound::Unbounded, _) => false,
384 (_, Bound::Unbounded) => false,
385 _ => unreachable!("end bounds are always Excluded"),
386 }
387}
388
389#[cfg(test)]
394pub(crate) struct Mem {
395 map: core::cell::RefCell<std::collections::BTreeMap<Vec<u8>, Vec<u8>>>,
396}
397
398#[cfg(test)]
399impl Default for Mem {
400 fn default() -> Self {
401 Self {
402 map: core::cell::RefCell::new(std::collections::BTreeMap::new()),
403 }
404 }
405}
406
407#[cfg(test)]
408impl RawKv for Mem {
409 type Error = std::convert::Infallible;
410
411 fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
412 Ok(self.map.borrow().get(key).cloned())
413 }
414
415 fn scan(
416 &self,
417 start: Bound<&[u8]>,
418 end: Bound<&[u8]>,
419 forward: bool,
420 ) -> Result<Vec<KvPair>, Self::Error> {
421 let map = self.map.borrow();
422 let rows: Vec<KvPair> = map
423 .iter()
424 .filter(|(k, _)| {
425 let k = &k[..];
426 let above = match start {
427 Bound::Unbounded => true,
428 Bound::Included(s) => k >= s,
429 Bound::Excluded(s) => k > s,
430 };
431 let below = match end {
432 Bound::Unbounded => true,
433 Bound::Excluded(e) => k < e,
434 Bound::Included(e) => k <= e,
435 };
436 above && below
437 })
438 .map(|(k, v)| KvPair {
439 key: k.clone(),
440 value: v.clone(),
441 })
442 .collect();
443 if forward {
444 Ok(rows)
445 } else {
446 Ok(rows.into_iter().rev().collect())
447 }
448 }
449
450 fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<(), Self::Error> {
451 self.map.borrow_mut().insert(key.to_vec(), value.to_vec());
452 Ok(())
453 }
454
455 fn delete(&mut self, key: &[u8]) -> Result<(), Self::Error> {
456 self.map.borrow_mut().remove(key);
457 Ok(())
458 }
459
460 fn clear_range(&mut self, start: Bound<&[u8]>, end: Bound<&[u8]>) -> Result<(), Self::Error> {
461 let mut map = self.map.borrow_mut();
462 let keys: Vec<Vec<u8>> = map
463 .keys()
464 .filter(|k| {
465 let k = &k[..];
466 let above = match start {
467 Bound::Unbounded => true,
468 Bound::Included(s) => k >= s,
469 Bound::Excluded(s) => k > s,
470 };
471 let below = match end {
472 Bound::Unbounded => true,
473 Bound::Excluded(e) => k < e,
474 Bound::Included(e) => k <= e,
475 };
476 above && below
477 })
478 .cloned()
479 .collect();
480 for k in keys {
481 map.remove(&k);
482 }
483 Ok(())
484 }
485}
486
487#[cfg(test)]
488mod tests {
489 use super::*;
490 use crate::key::KeyError;
491
492 fn engine() -> FlatEngine<Mem> {
493 FlatEngine::new(Mem::default())
494 }
495
496 fn ok<T>(r: Result<T, FlatError<std::convert::Infallible>>) -> T {
497 r.unwrap()
498 }
499
500 #[test]
503 fn fresh_reads_return_empty_and_first_write_initialises() {
504 let mut e = engine();
505 assert_eq!(ok(e.prefix_of(&[])), None);
506 assert_eq!(ok(e.get(&[], b"k")), None);
507 assert!(ok(e.scan(&[], Bound::Unbounded, Bound::Unbounded, true)).is_empty());
508 assert!(ok(e.list_dirs(&[])).is_empty());
509 assert!(!ok(e.dir_exists(&[])));
510 assert!(!ok(e.remove_dir(&[b"a"])));
512 ok(e.set(&[], b"k", b"v"));
515 assert!(ok(e.dir_exists(&[])));
516 assert_eq!(ok(e.get(&[], b"k")), Some(b"v".to_vec()));
517 let version = e
519 .raw()
520 .map
521 .borrow()
522 .get(crate::flatdir::layout::VERSION_KEY)
523 .cloned();
524 assert_eq!(
525 version,
526 Some(crate::flatdir::layout::LAYOUT_VERSION.to_vec())
527 );
528 }
529
530 #[test]
536 fn a_first_set_produces_exactly_nine_raw_rows() {
537 let mut e = engine();
538 ok(e.set(&[b"a"], b"k", b"v"));
539 let map = e.raw().map.borrow();
540 assert_eq!(map.len(), 9, "unexpected raw rows: {map:?}");
541 }
542
543 #[test]
546 fn reads_on_a_foreign_store_fail_closed() {
547 let mut e = engine();
551 let mut v = [0u8; 12];
552 v[0..4].copy_from_slice(&2u32.to_le_bytes());
553 e.raw_mut()
554 .insert(crate::flatdir::layout::VERSION_KEY, &v)
555 .unwrap();
556 assert_eq!(e.prefix_of(&[]), Err(FlatError::Foreign));
557 assert_eq!(e.get(&[], b"k"), Err(FlatError::Foreign));
558 assert_eq!(
559 e.scan(&[], Bound::Unbounded, Bound::Unbounded, true),
560 Err(FlatError::Foreign)
561 );
562 assert!(matches!(
563 e.data_bounds(&[], Bound::Unbounded, Bound::Unbounded),
564 Err(FlatError::Foreign)
565 ));
566 assert_eq!(e.dir_exists(&[]), Err(FlatError::Foreign));
567 assert_eq!(e.list_dirs(&[]), Err(FlatError::Foreign));
568 assert_eq!(e.set(&[], b"k", b"v"), Err(FlatError::Foreign));
569 assert_eq!(e.remove_dir(&[b"a"]), Err(FlatError::Foreign));
570 }
571
572 #[test]
573 fn a_malformed_version_row_fails_closed() {
574 let mut e = engine();
576 e.raw_mut()
577 .insert(crate::flatdir::layout::VERSION_KEY, &[1, 0])
578 .unwrap();
579 assert_eq!(e.dir_exists(&[]), Err(FlatError::Foreign));
580 }
581
582 #[test]
583 fn a_corrupt_node_value_is_corrupt_not_a_panic() {
584 let mut e = engine();
588 e.set(&[b"dir"], b"k", b"v").unwrap();
589 let child_tag = crate::flatdir::layout::ROOT_NODE
593 .iter()
594 .copied()
595 .chain(std::iter::once(0x14))
596 .collect::<Vec<u8>>();
597 let row_key = e
598 .raw()
599 .map
600 .borrow()
601 .iter()
602 .find(|(k, _)| k.starts_with(&child_tag))
603 .expect("the anchor child row")
604 .0
605 .clone();
606 e.raw_mut()
607 .map
608 .borrow_mut()
609 .insert(row_key, vec![0x99, 0x00]);
610 assert_eq!(e.get(&[b"dir"], b"k"), Err(FlatError::Corrupt));
611 assert_eq!(
612 e.scan(&[b"dir"], Bound::Unbounded, Bound::Unbounded, true),
613 Err(FlatError::Corrupt)
614 );
615 assert_eq!(e.remove_dir(&[b"dir"]), Err(FlatError::Corrupt));
616 }
617
618 #[test]
621 fn allocation_is_recursive_and_stable() {
622 let mut e = engine();
623 let p = ok(e.allocate_dir(&[b"a", b"b"]));
624 assert_eq!(ok(e.prefix_of(&[b"a", b"b"])), Some(p.clone()));
626 let q = ok(e.allocate_dir(&[b"a", b"c"]));
628 assert_ne!(p, q);
629 assert!(ok(e.prefix_of(&[b"a"])).is_some());
630 let dirs: [[&[u8]; 2]; 2] = [[b"a" as &[u8], b"b"], [b"a" as &[u8], b"c"]];
633 for dir in dirs {
634 let p = ok(e.prefix_of(&dir)).unwrap();
635 assert!((0x0c..=0x1c).contains(&p[0]), "prefix {p:?}");
636 }
637 }
638
639 #[test]
640 fn many_allocations_stay_in_the_data_region() {
641 let mut e = engine();
645 for i in 0..300u32 {
646 let d = format!("d{i:03}").into_bytes();
647 let d = [d.as_slice()];
648 let p = ok(e.allocate_dir(&d));
649 assert!((0x0c..=0x1c).contains(&p[0]), "prefix {p:?} at {i}");
650 }
651 }
652
653 #[test]
654 fn resolve_missing_dir_is_none() {
655 let mut e = engine();
656 ok(e.set(&[], b"k", b"v"));
657 assert_eq!(ok(e.prefix_of(&[b"nope"])), None);
658 assert_eq!(ok(e.prefix_of(&[b"nope", b"deeper"])), None);
659 }
660
661 #[test]
664 fn set_get_delete_round_trips_per_dir() {
665 let mut e = engine();
666 ok(e.set(&[b"asset", b"btc"], b"k", b"v"));
667 assert_eq!(ok(e.get(&[b"asset", b"btc"], b"k")), Some(b"v".to_vec()));
668 assert_eq!(ok(e.get(&[b"asset"], b"k")), None);
670 assert_eq!(ok(e.get(&[b"btc"], b"k")), None);
671 ok(e.delete(&[b"asset", b"btc"], b"k"));
672 assert_eq!(ok(e.get(&[b"asset", b"btc"], b"k")), None);
673 }
674
675 #[test]
676 fn scan_orders_within_dir_only() {
677 let mut e = engine();
678 for k in [b"b", b"a", b"c"] {
679 ok(e.set(&[b"d"], k, k));
680 ok(e.set(&[b"other"], k, k));
681 }
682 let rows = ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, true));
683 let keys: Vec<Vec<u8>> = rows.iter().map(|p| p.key.clone()).collect();
684 assert_eq!(keys, vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec()]);
685 let rows = ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, false));
686 assert_eq!(rows.first().unwrap().key, b"c".to_vec());
687 }
688
689 #[test]
690 fn scan_bound_matrix() {
691 let mut e = engine();
692 for k in [b"a", b"b", b"c", b"\xff"] {
693 ok(e.set(&[b"d"], k, b"v"));
694 }
695 let get = |s: core::ops::Bound<&[u8]>,
696 en: core::ops::Bound<&[u8]>,
697 e: &FlatEngine<Mem>|
698 -> Vec<Vec<u8>> {
699 ok(e.scan(&[b"d"], s, en, true))
700 .into_iter()
701 .map(|pair| pair.key)
702 .collect()
703 };
704 assert_eq!(
705 get(Bound::Included(b"b"), Bound::Excluded(b"c"), &e),
706 vec![b"b".to_vec()]
707 );
708 assert_eq!(
709 get(Bound::Excluded(b"b"), Bound::Included(b"c"), &e),
710 vec![b"c".to_vec()]
711 );
712 assert_eq!(
713 get(Bound::Excluded(&[0xFFu8]), Bound::Unbounded, &e),
714 Vec::<Vec<u8>>::new()
715 );
716 assert_eq!(
717 get(Bound::Unbounded, Bound::Included(&[0xFFu8]), &e),
718 vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec(), vec![0xFF]]
719 );
720 assert_eq!(
721 get(Bound::Included(&[0xFFu8]), Bound::Unbounded, &e),
722 vec![vec![0xFF]]
723 );
724 assert_eq!(
726 get(Bound::Excluded(&[0xFFu8]), Bound::Excluded(&[0xFFu8]), &e),
727 Vec::<Vec<u8>>::new()
728 );
729 }
730
731 #[test]
732 fn clear_range_clears_within_dir_only() {
733 let mut e = engine();
734 for k in [b"a", b"b", b"c"] {
735 ok(e.set(&[b"d"], k, b"v"));
736 ok(e.set(&[b"e"], k, b"v"));
737 }
738 ok(e.clear_range(&[b"d"], Bound::Included(b"b"), Bound::Excluded(b"c")));
739 assert_eq!(ok(e.get(&[b"d"], b"a")), Some(b"v".to_vec()));
740 assert_eq!(ok(e.get(&[b"d"], b"b")), None);
741 assert_eq!(ok(e.get(&[b"d"], b"c")), Some(b"v".to_vec()));
742 assert_eq!(ok(e.get(&[b"e"], b"b")), Some(b"v".to_vec()));
743 ok(e.clear_range(&[b"d"], Bound::Unbounded, Bound::Unbounded));
745 assert!(ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, true)).is_empty());
746 assert!(ok(e.dir_exists(&[b"d"])));
748 }
749
750 #[test]
753 fn nav_list_exists_remove() {
754 let mut e = engine();
755 ok(e.set(&[b"a", b"1"], b"k", b"v"));
756 ok(e.set(&[b"a", b"2"], b"k", b"v"));
757 ok(e.set(&[b"b"], b"k", b"v"));
758 assert_eq!(ok(e.list_dirs(&[])), vec![b"a".to_vec(), b"b".to_vec()]);
759 assert_eq!(ok(e.list_dirs(&[b"a"])), vec![b"1".to_vec(), b"2".to_vec()]);
760 assert!(ok(e.dir_exists(&[b"a"])));
761 assert!(ok(e.dir_exists(&[b"a", b"1"])));
762 assert!(!ok(e.dir_exists(&[b"a", b"3"])));
763 ok(e.allocate_dir(&[b"empty"]));
765 assert!(ok(e.dir_exists(&[b"empty"])));
766 assert!(ok(e.list_dirs(&[b"empty"])).is_empty());
767 assert!(ok(e.list_dirs(&[b"nope"])).is_empty());
769 assert!(!ok(e.dir_exists(&[b"nope"])));
770 }
771
772 #[test]
773 fn nav_remove_is_recursive() {
774 let mut e = engine();
775 ok(e.set(&[b"a", b"b", b"c"], b"k1", b"v1"));
776 ok(e.set(&[b"a", b"b"], b"k2", b"v2"));
777 ok(e.set(&[b"a", b"d"], b"k3", b"v3"));
778 ok(e.set(&[b"z"], b"k4", b"v4"));
779 assert!(ok(e.remove_dir(&[b"a", b"b"])));
781 assert_eq!(ok(e.get(&[b"a", b"b", b"c"], b"k1")), None);
782 assert_eq!(ok(e.get(&[b"a", b"b"], b"k2")), None);
783 assert_eq!(ok(e.get(&[b"a", b"d"], b"k3")), Some(b"v3".to_vec()));
784 assert!(ok(e.dir_exists(&[b"a"])));
785 assert!(!ok(e.dir_exists(&[b"a", b"b"])));
786 assert!(ok(e.remove_dir(&[b"a", b"d"])));
788 assert_eq!(ok(e.get(&[b"a", b"d"], b"k3")), None);
789 assert!(!ok(e.remove_dir(&[b"a", b"b"])));
791 assert_eq!(ok(e.get(&[b"z"], b"k4")), Some(b"v4".to_vec()));
793 }
794
795 #[test]
796 fn nav_root_is_not_removable() {
797 let mut e = engine();
798 ok(e.set(&[], b"k", b"v"));
799 assert_eq!(
800 e.remove_dir(&[]),
801 Err(FlatError::Key(KeyError::RootNotRemovable))
802 );
803 assert!(ok(e.dir_exists(&[])));
805 }
806
807 #[test]
808 fn nav_rejects_non_utf8() {
809 let mut e = engine();
810 let seg: &[u8] = b"\xFF\xFE";
811 let bad = [seg];
812 assert_eq!(
813 e.list_dirs(&bad),
814 Err(FlatError::Key(KeyError::DirSegmentNotUtf8 { segment: 0 }))
815 );
816 assert_eq!(
817 e.remove_dir(&bad),
818 Err(FlatError::Key(KeyError::DirSegmentNotUtf8 { segment: 0 }))
819 );
820 }
821
822 #[test]
823 fn remove_and_recreate_work() {
824 let mut e = engine();
830 ok(e.set(&[b"x"], b"k", b"v1"));
831 let p1 = ok(e.prefix_of(&[b"x"])).unwrap();
832 assert!(ok(e.remove_dir(&[b"x"])));
833 assert!(!ok(e.dir_exists(&[b"x"])));
834 assert_eq!(ok(e.get(&[b"x"], b"k")), None);
835 ok(e.set(&[b"x"], b"k", b"v2"));
836 let p2 = ok(e.prefix_of(&[b"x"])).unwrap();
837 assert_eq!(ok(e.get(&[b"x"], b"k")), Some(b"v2".to_vec()));
838 if p1 == p2 {
841 assert_eq!(
842 ok(e.scan(&[b"x"], Bound::Unbounded, Bound::Unbounded, true)).len(),
843 1
844 );
845 }
846 assert!(ops::validate(e.raw()).is_ok());
848 }
849}