Skip to main content

b_tree/
tree.rs

1use std::borrow::Borrow;
2use std::mem;
3use std::pin::Pin;
4use std::sync::Arc;
5use std::{fmt, io};
6
7use collate::{Collate, OverlapsValue};
8#[cfg(feature = "stream")]
9use destream::de;
10use freqfs::{
11    DirDeref, DirLock, DirReadGuardOwned, DirWriteGuardOwned, FileLoad, FileReadGuard,
12    FileReadGuardOwned, FileSave, FileWriteGuardOwned,
13};
14use futures::TryFutureExt;
15use futures::future::{self, Future, FutureExt};
16use futures::stream::{self, Stream, StreamExt, TryStreamExt};
17use futures::try_join;
18use safecast::AsType;
19use smallvec::SmallVec;
20use uuid::Uuid;
21
22use super::group::GroupBy;
23use super::node::Block;
24use super::range::Range;
25use super::{Collator, Key, NODE_STACK_SIZE, Schema};
26
27type NodeStack<V> = SmallVec<[Key<V>; NODE_STACK_SIZE]>;
28
29/// A read guard acquired on a [`BTreeLock`]
30pub type BTreeReadGuard<S, C, FE> = BTree<S, C, Arc<DirReadGuardOwned<FE>>>;
31
32/// A write guard acquired on a [`BTreeLock`]
33pub type BTreeWriteGuard<S, C, FE> = BTree<S, C, DirWriteGuardOwned<FE>>;
34
35/// A stream of [`Key`]s in a [`BTree`]
36pub type Keys<V> = Pin<Box<dyn Stream<Item = Result<Key<V>, io::Error>> + Send>>;
37
38type Nodes<FE, V> = Pin<Box<dyn Stream<Item = Result<Leaf<FE, V>, io::Error>> + Send>>;
39
40type Node<V> = super::node::Node<Vec<Vec<V>>>;
41
42type ResultNodes<FE, V> = Result<Nodes<FE, V>, io::Error>;
43
44type ResultDelete<FE, V> = Result<Delete<FE, V>, io::Error>;
45
46type ResultMergeIndex<V> = Result<MergeIndexLeft<V>, io::Error>;
47
48type ResultMergeLeaf<V> = Result<MergeLeafLeft<V>, io::Error>;
49
50type ResultInsert<V> = Result<Insert<V>, io::Error>;
51
52const ROOT: Uuid = Uuid::from_fields(0, 0, 0, &[0u8; 8]);
53
54/// A read guard on the content of a leaf node
55pub struct Leaf<FE, V> {
56    node: FileReadGuardOwned<FE, Node<V>>,
57    range: (usize, usize),
58}
59
60impl<FE, V> Leaf<FE, V> {
61    fn new(node: FileReadGuardOwned<FE, Node<V>>, range: (usize, usize)) -> Self {
62        debug_assert!(node.is_leaf());
63        Self { node, range }
64    }
65}
66
67impl<FE, V> AsRef<[Vec<V>]> for Leaf<FE, V> {
68    fn as_ref(&self) -> &[Vec<V>] {
69        match &*self.node {
70            Node::Leaf(keys) => &keys[self.range.0..self.range.1],
71            _ => panic!("not a leaf!"),
72        }
73    }
74}
75
76/// A futures-aware read-write lock on a [`BTree`]
77pub struct BTreeLock<S, C, FE> {
78    schema: Arc<S>,
79    collator: Collator<C>,
80    dir: DirLock<FE>,
81}
82
83impl<S, C, FE> Clone for BTreeLock<S, C, FE>
84where
85    C: Clone,
86{
87    fn clone(&self) -> Self {
88        Self {
89            schema: self.schema.clone(),
90            collator: self.collator.clone(),
91            dir: self.dir.clone(),
92        }
93    }
94}
95
96impl<S, C, FE> BTreeLock<S, C, FE> {
97    /// Borrow the [`Collator`] used by this B+Tree.
98    pub fn collator(&self) -> &Collator<C> {
99        &self.collator
100    }
101
102    /// Borrow the schema of the source B+Tree.
103    pub fn schema(&self) -> &S {
104        &self.schema
105    }
106}
107
108impl<S, C, FE> BTreeLock<S, C, FE>
109where
110    S: Schema,
111    FE: AsType<Node<S::Value>> + Send + Sync,
112    Node<S::Value>: FileLoad,
113{
114    fn new(schema: S, collator: C, dir: DirLock<FE>) -> Self {
115        Self {
116            schema: Arc::new(schema),
117            collator: Collator::new(collator),
118            dir,
119        }
120    }
121
122    /// Create a new [`BTreeLock`] in `dir` with the given `collator`.
123    pub fn create(schema: S, collator: C, dir: DirLock<FE>) -> Result<Self, io::Error> {
124        let mut nodes = dir.try_write_owned()?;
125
126        if nodes.is_empty() {
127            nodes.create_file::<Node<S::Value>>(ROOT.to_string(), Node::Leaf(vec![]), 0)?;
128
129            debug_assert!(nodes.contains(&ROOT), "B+Tree failed to create a root node");
130
131            Ok(Self::new(schema, collator, dir))
132        } else {
133            Err(io::Error::new(
134                io::ErrorKind::AlreadyExists,
135                "creating a new B+Tree requires an empty file",
136            ))
137        }
138    }
139
140    /// Load a [`BTreeLock`] with the given `schema` and `collator` from `dir`.
141    pub fn load(schema: S, collator: C, dir: DirLock<FE>) -> Result<Self, io::Error> {
142        let mut nodes = dir.try_write_owned()?;
143
144        if !nodes.contains(&ROOT) {
145            nodes.create_file(ROOT.to_string(), Node::Leaf(vec![]), 0)?;
146        }
147
148        debug_assert!(nodes.contains(&ROOT), "B+Tree failed to create a root node");
149
150        Ok(Self::new(schema, collator, dir))
151    }
152
153    /// Write any modified blocks of thie [`BTree`] to the filesystem.
154    pub async fn sync(&self) -> Result<(), io::Error>
155    where
156        FE: FileSave + Clone,
157    {
158        self.dir.sync().await
159    }
160}
161
162impl<S, C, FE> BTreeLock<S, C, FE>
163where
164    C: Clone,
165    FE: Send + Sync,
166{
167    /// Lock this B+Tree for reading, without borrowing.
168    pub async fn into_read(self) -> BTreeReadGuard<S, C, FE> {
169        #[cfg(feature = "logging")]
170        log::debug!("lock B+Tree at {:?} for reading...", self.dir);
171
172        self.dir
173            .into_read()
174            .map(Arc::new)
175            .map(|dir| BTree {
176                schema: self.schema.clone(),
177                collator: self.collator.clone(),
178                dir,
179            })
180            .await
181    }
182
183    /// Lock this B+Tree for reading.
184    pub async fn read(&self) -> BTreeReadGuard<S, C, FE> {
185        #[cfg(feature = "logging")]
186        log::debug!("lock B+Tree at {:?} for reading...", self.dir);
187
188        self.dir
189            .read_owned()
190            .map(Arc::new)
191            .map(|dir| BTree {
192                schema: self.schema.clone(),
193                collator: self.collator.clone(),
194                dir,
195            })
196            .await
197    }
198
199    /// Lock this B+Tree for reading synchronously, if possible.
200    pub fn try_read(&self) -> Result<BTreeReadGuard<S, C, FE>, io::Error> {
201        self.dir.try_read_owned().map(Arc::new).map(|dir| BTree {
202            schema: self.schema.clone(),
203            collator: self.collator.clone(),
204            dir,
205        })
206    }
207
208    /// Lock this B+Tree for writing, without borrowing.
209    pub async fn into_write(self) -> BTreeWriteGuard<S, C, FE> {
210        #[cfg(feature = "logging")]
211        log::debug!("lock B+Tree at {:?} for writing...", self.dir);
212
213        self.dir
214            .into_write()
215            .map(|dir| BTree {
216                schema: self.schema.clone(),
217                collator: self.collator.clone(),
218                dir,
219            })
220            .await
221    }
222
223    /// Lock this B+Tree for writing.
224    pub async fn write(&self) -> BTreeWriteGuard<S, C, FE> {
225        #[cfg(feature = "logging")]
226        log::debug!("lock B+Tree at {:?} for writing...", self.dir);
227
228        self.dir
229            .write_owned()
230            .map(|dir| BTree {
231                schema: self.schema.clone(),
232                collator: self.collator.clone(),
233                dir,
234            })
235            .await
236    }
237
238    /// Lock this B+Tree for writing synchronously, if possible.
239    pub fn try_write(&self) -> Result<BTreeWriteGuard<S, C, FE>, io::Error> {
240        self.dir.try_write_owned().map(|dir| BTree {
241            schema: self.schema.clone(),
242            collator: self.collator.clone(),
243            dir,
244        })
245    }
246}
247
248#[cfg(feature = "stream")]
249struct BTreeVisitor<S, C, FE> {
250    btree: BTreeLock<S, C, FE>,
251}
252
253#[cfg(feature = "stream")]
254impl<S, C, FE> de::Visitor for BTreeVisitor<S, C, FE>
255where
256    S: Schema + Send + Sync,
257    C: Collate<Value = S::Value> + Clone + Send + Sync,
258    FE: AsType<Node<S::Value>> + Send + Sync,
259    S::Value: de::FromStream<Context = ()>,
260    Node<S::Value>: FileLoad,
261{
262    type Value = BTreeLock<S, C, FE>;
263
264    fn expecting() -> &'static str {
265        "a BTree"
266    }
267
268    async fn visit_seq<A: de::SeqAccess>(self, mut seq: A) -> Result<Self::Value, A::Error> {
269        let mut btree = self.btree.write().await;
270
271        while let Some(key) = seq.next_element(()).map_err(de::Error::custom).await? {
272            btree.insert(key).map_err(de::Error::custom).await?;
273        }
274
275        Ok(self.btree)
276    }
277}
278
279#[cfg(feature = "stream")]
280impl<S, C, FE> de::FromStream for BTreeLock<S, C, FE>
281where
282    S: Schema + Send + Sync,
283    C: Collate<Value = S::Value> + Clone + Send + Sync,
284    FE: AsType<Node<S::Value>> + Send + Sync,
285    S::Value: de::FromStream<Context = ()>,
286    Node<S::Value>: FileLoad,
287{
288    type Context = (S, C, DirLock<FE>);
289
290    async fn from_stream<D: de::Decoder>(
291        context: Self::Context,
292        decoder: &mut D,
293    ) -> Result<Self, D::Error> {
294        let (schema, collator, dir) = context;
295        let btree = BTreeLock::create(schema, collator, dir).map_err(de::Error::custom)?;
296        decoder.decode_seq(BTreeVisitor { btree }).await
297    }
298}
299
300/// A B+Tree
301pub struct BTree<S, C, G> {
302    schema: Arc<S>,
303    collator: Collator<C>,
304    dir: G,
305}
306
307impl<S, C, G> Clone for BTree<S, C, G>
308where
309    C: Clone,
310    G: Clone,
311{
312    fn clone(&self) -> Self {
313        Self {
314            schema: self.schema.clone(),
315            collator: self.collator.clone(),
316            dir: self.dir.clone(),
317        }
318    }
319}
320
321impl<S, C, G> BTree<S, C, G>
322where
323    S: Schema,
324    C: Collate<Value = S::Value>,
325{
326    /// Borrow the [`Schema`] of this [`BTree`].
327    pub fn schema(&self) -> &S {
328        &self.schema
329    }
330}
331
332impl<S, C, FE, G> BTree<S, C, G>
333where
334    S: Schema,
335    C: Collate<Value = S::Value>,
336    FE: AsType<Node<S::Value>> + Send + Sync,
337    G: DirDeref<Entry = FE>,
338    Node<S::Value>: FileLoad + fmt::Debug,
339{
340    /// Return `true` if this B+Tree contains the given `key`.
341    pub async fn contains(&self, key: &[S::Value]) -> Result<bool, io::Error> {
342        debug_assert!(
343            self.dir.as_dir().contains(&ROOT),
344            "B+Tree is missing its root node"
345        );
346
347        let mut node = self.dir.as_dir().read_file(&ROOT).await?;
348
349        loop {
350            match &*node {
351                Node::Leaf(keys) => {
352                    let i = keys.bisect_left(key, &self.collator);
353
354                    break Ok(if i < keys.len() {
355                        match keys.get(i) {
356                            Some(present) => present == key,
357                            _ => false,
358                        }
359                    } else {
360                        false
361                    });
362                }
363                Node::Index(bounds, children) => {
364                    let i = bounds.bisect_right(key, &self.collator);
365
366                    if i == 0 {
367                        return Ok(false);
368                    } else {
369                        node = self.dir.as_dir().read_file(&children[i - 1]).await?;
370                    }
371                }
372            }
373        }
374    }
375
376    /// Count how many keys lie within the given `range` of this B+Tree.
377    pub async fn count<BV>(&self, range: &Range<BV>) -> Result<u64, io::Error>
378    where
379        BV: Borrow<S::Value>,
380    {
381        debug_assert!(
382            self.dir.as_dir().contains(&ROOT),
383            "B+Tree is missing its root node"
384        );
385        let root = self.dir.as_dir().read_file(&ROOT).await?;
386        self.count_inner(range, root).await
387    }
388
389    fn count_inner<'a, BV>(
390        &'a self,
391        range: &'a Range<BV>,
392        node: FileReadGuard<'a, Node<S::Value>>,
393    ) -> Pin<Box<dyn Future<Output = Result<u64, io::Error>> + 'a>>
394    where
395        BV: Borrow<S::Value> + 'a,
396    {
397        Box::pin(async move {
398            match &*node {
399                Node::Leaf(keys) if range.is_empty() => Ok(keys.len() as u64),
400                Node::Leaf(keys) => {
401                    let (l, r) = keys.bisect(range, &self.collator);
402
403                    if l == keys.len() {
404                        Ok(0)
405                    } else if l == r {
406                        if range.contains_value(&keys[l], &self.collator) {
407                            Ok(1)
408                        } else {
409                            Ok(0)
410                        }
411                    } else {
412                        Ok((r - l) as u64)
413                    }
414                }
415                Node::Index(_bounds, children) if range.is_empty() => {
416                    stream::iter(children)
417                        .then(|node_id| self.dir.as_dir().read_file(node_id))
418                        .map_ok(|node| self.count_inner(range, node))
419                        .try_buffer_unordered(num_cpus::get())
420                        .try_fold(0, |sum, count| future::ready(Ok(sum + count)))
421                        .await
422                }
423                Node::Index(bounds, children) => {
424                    let (l, r) = bounds.bisect(range, &self.collator);
425                    let l = if l == 0 { l } else { l - 1 };
426
427                    if l == children.len() {
428                        let node = self
429                            .dir
430                            .as_dir()
431                            .read_file(children.last().expect("last"))
432                            .await?;
433
434                        self.count_inner(range, node).await
435                    } else if l == r || l + 1 == r {
436                        let node = self.dir.as_dir().read_file(&children[l]).await?;
437                        self.count_inner(range, node).await
438                    } else {
439                        let left = self
440                            .dir
441                            .as_dir()
442                            .read_file(&children[l])
443                            .and_then(|node| self.count_inner(range, node));
444
445                        let default_range = Range::<S::Value>::default();
446
447                        let middle = stream::iter(&children[(l + 1)..(r - 1)])
448                            .then(|node_id| self.dir.as_dir().read_file(node_id))
449                            .map_ok(|node| self.count_inner(&default_range, node))
450                            .try_buffer_unordered(num_cpus::get())
451                            .try_fold(0, |sum, count| future::ready(Ok(sum + count)));
452
453                        let right = self
454                            .dir
455                            .as_dir()
456                            .read_file(&children[r - 1])
457                            .and_then(|node| self.count_inner(range, node));
458
459                        let (left, middle, right) = try_join!(left, middle, right)?;
460
461                        Ok(left + middle + right)
462                    }
463                }
464            }
465        })
466    }
467
468    /// Return the first key in this B+Tree within the given `range`, if any.
469    pub async fn first<BV>(&self, range: Range<BV>) -> Result<Option<Key<S::Value>>, io::Error>
470    where
471        BV: Borrow<S::Value>,
472    {
473        debug_assert!(
474            self.dir.as_dir().contains(&ROOT),
475            "B+Tree is missing its root node"
476        );
477
478        let mut node = self.dir.as_dir().read_file(&ROOT).await?;
479
480        if let Node::Leaf(keys) = &*node
481            && keys.is_empty()
482        {
483            return Ok(None);
484        }
485
486        Ok(loop {
487            match &*node {
488                Node::Leaf(keys) => {
489                    let (l, _r) = keys.bisect(&range, &self.collator);
490
491                    break if l == keys.len() {
492                        None
493                    } else if range.contains_value(&keys[l], &self.collator) {
494                        Some(stack_key(&keys[l]))
495                    } else {
496                        None
497                    };
498                }
499                Node::Index(bounds, children) => {
500                    let (l, _r) = bounds.bisect(&range, &self.collator);
501
502                    if l == bounds.len() {
503                        node = self
504                            .dir
505                            .as_dir()
506                            .read_file(children.last().expect("last"))
507                            .await?;
508                    } else if range.contains_value(&bounds[l], &self.collator) {
509                        break Some(stack_key(&bounds[l]));
510                    } else {
511                        node = self.dir.as_dir().read_file(&children[l]).await?;
512                    }
513                }
514            }
515        })
516    }
517
518    /// Return the last key in this B+Tree with the given `prefix`, if any.
519    pub async fn last<BV>(&self, range: Range<BV>) -> Result<Option<Key<S::Value>>, io::Error>
520    where
521        BV: Borrow<S::Value>,
522    {
523        debug_assert!(
524            self.dir.as_dir().contains(&ROOT),
525            "B+Tree is missing its root node"
526        );
527
528        let mut node = self.dir.as_dir().read_file(&ROOT).await?;
529
530        if let Node::Leaf(keys) = &*node
531            && keys.is_empty()
532        {
533            return Ok(None);
534        }
535
536        Ok(loop {
537            match &*node {
538                Node::Leaf(keys) => {
539                    let (_l, r) = keys.bisect(&range, &self.collator);
540
541                    break if r == keys.len() {
542                        if range.contains_value(&keys[r - 1], &self.collator) {
543                            Some(stack_key(&keys[r - 1]))
544                        } else {
545                            None
546                        }
547                    } else if range.contains_value(&keys[r], &self.collator) {
548                        Some(stack_key(&keys[r]))
549                    } else {
550                        None
551                    };
552                }
553                Node::Index(bounds, children) => {
554                    let (_l, r) = bounds.bisect(&range, &self.collator);
555
556                    if r == 0 {
557                        break None;
558                    } else {
559                        node = self.dir.as_dir().read_file(&children[r - 1]).await?;
560                    }
561                }
562            }
563        })
564    }
565
566    /// Return `true` if the given `range` of this B+Tree contains zero keys.
567    pub async fn is_empty<R: Borrow<Range<S::Value>>>(&self, range: R) -> Result<bool, io::Error> {
568        let range = range.borrow();
569
570        debug_assert!(
571            self.dir.as_dir().contains(&ROOT),
572            "B+Tree is missing its root node"
573        );
574
575        let mut node = self.dir.as_dir().read_file(&ROOT).await?;
576
577        Ok(loop {
578            match &*node {
579                Node::Leaf(keys) => {
580                    let (l, r) = keys.bisect(range, &self.collator);
581                    break l == r;
582                }
583                Node::Index(bounds, children) => {
584                    let (l, r) = bounds.bisect(range, &self.collator);
585
586                    if l == children.len() {
587                        node = self.dir.as_dir().read_file(&children[l - 1]).await?;
588                    } else if l == r {
589                        node = self.dir.as_dir().read_file(&children[l]).await?;
590                    } else {
591                        break false;
592                    }
593                }
594            }
595        })
596    }
597
598    #[cfg(debug_assertions)]
599    fn is_valid_node<'a>(
600        &'a self,
601        node: &'a Node<S::Value>,
602    ) -> Pin<Box<dyn Future<Output = Result<bool, io::Error>> + 'a>> {
603        Box::pin(async move {
604            let order = self.schema.order();
605
606            match node {
607                Node::Leaf(keys) => {
608                    assert!(keys.len() >= (order / 2) - 1);
609                    assert!(keys.len() < order);
610                }
611                Node::Index(bounds, children) => {
612                    assert_eq!(bounds.len(), children.len());
613                    assert!(children.len() >= self.schema.order() / 2);
614                    assert!(children.len() <= order);
615
616                    for (left, node_id) in bounds.iter().zip(children) {
617                        let node = self.dir.as_dir().read_file(node_id).await?;
618
619                        match &*node {
620                            Node::Leaf(keys) => assert_eq!(left, &keys[0]),
621                            Node::Index(bounds, _) => assert_eq!(left, &bounds[0]),
622                        }
623
624                        assert!(self.is_valid_node(&*node).await?);
625                    }
626                }
627            }
628
629            Ok(true)
630        })
631    }
632}
633
634impl<S, C, FE, G> BTree<S, C, G>
635where
636    S: Schema,
637    C: Collate<Value = S::Value> + Clone + Send + Sync + 'static,
638    FE: AsType<Node<S::Value>> + Send + Sync + 'static,
639    G: DirDeref<Entry = FE> + Clone + Send + Sync + 'static,
640    Node<S::Value>: FileLoad + fmt::Debug,
641{
642    /// Construct a [`Stream`] of all the keys in the given `range` of this B+Tree.
643    pub async fn keys<BV>(self, range: Range<BV>) -> Result<Keys<S::Value>, io::Error>
644    where
645        BV: Borrow<S::Value> + Clone + Send + Sync + 'static,
646    {
647        debug_assert!(
648            self.dir.as_dir().contains(&ROOT),
649            "B+Tree is missing its root node"
650        );
651
652        let nodes = nodes_forward(self.dir, self.collator, range, ROOT).await?;
653
654        let keys = nodes
655            .map_ok(move |leaf| async move {
656                let mut keys = NodeStack::with_capacity(leaf.as_ref().len());
657
658                for key in leaf.as_ref() {
659                    keys.push(key.iter().cloned().collect())
660                }
661
662                Ok(stream::iter(keys).map(Ok))
663            })
664            .try_buffered(num_cpus::get())
665            .try_flatten();
666
667        Ok(Box::pin(keys))
668    }
669
670    pub async fn keys_rev<BV>(self, range: Range<BV>) -> Result<Keys<S::Value>, io::Error>
671    where
672        BV: Borrow<S::Value> + Clone + Send + Sync + 'static,
673    {
674        debug_assert!(
675            self.dir.as_dir().contains(&ROOT),
676            "B+Tree is missing its root node"
677        );
678
679        let nodes = nodes_reverse(self.dir, self.collator, range, ROOT).await?;
680
681        let keys = nodes
682            .map_ok(|leaf| async move {
683                let mut keys = NodeStack::with_capacity(leaf.as_ref().len());
684
685                for key in leaf.as_ref().iter().rev() {
686                    keys.push(key.iter().cloned().collect());
687                }
688
689                Ok(stream::iter(keys).map(Ok))
690            })
691            .try_buffered(num_cpus::get())
692            .try_flatten();
693
694        Ok(Box::pin(keys))
695    }
696
697    /// Construct a [`Stream`] of unique length-`n` prefixes within the given `range`.
698    pub async fn groups<BV>(
699        self,
700        range: Range<BV>,
701        n: usize,
702        reverse: bool,
703    ) -> Result<Keys<S::Value>, io::Error>
704    where
705        BV: Borrow<S::Value> + Clone + Send + Sync + 'static,
706    {
707        if n <= self.schema.len() {
708            let collator = self.collator.clone();
709
710            debug_assert!(
711                self.dir.as_dir().contains(&ROOT),
712                "B+Tree is missing its root node"
713            );
714
715            let nodes = if reverse {
716                nodes_reverse(self.dir, self.collator, range, ROOT).await?
717            } else {
718                nodes_forward(self.dir, self.collator, range, ROOT).await?
719            };
720
721            let groups = GroupBy::new(collator, nodes, n, reverse);
722            Ok(Box::pin(groups))
723        } else {
724            Err(io::Error::new(
725                io::ErrorKind::InvalidInput,
726                format!(
727                    "a table with {} columns does not have prefix groups of length {n}",
728                    self.schema.len()
729                ),
730            ))
731        }
732    }
733
734    #[cfg(debug_assertions)]
735    pub async fn is_valid(self) -> Result<bool, io::Error> {
736        {
737            debug_assert!(
738                self.dir.as_dir().contains(&ROOT),
739                "B+Tree is missing its root node"
740            );
741
742            let root = self.dir.as_dir().read_file(&ROOT).await?;
743
744            match &*root {
745                Node::Leaf(keys) => {
746                    assert!(keys.len() <= self.schema.order());
747                }
748                Node::Index(bounds, children) => {
749                    assert_eq!(bounds.len(), children.len());
750
751                    for (left, node_id) in bounds.iter().zip(children) {
752                        let node = self.dir.as_dir().read_file(node_id).await?;
753
754                        match &*node {
755                            Node::Leaf(keys) => assert_eq!(left, &keys[0]),
756                            Node::Index(bounds, _) => assert_eq!(left, &bounds[0]),
757                        }
758
759                        assert!(self.is_valid_node(&*node).await?);
760                    }
761                }
762            }
763        }
764
765        let default_range = Range::<S::Value>::default();
766        let count = self.count(&default_range).await? as usize;
767        let mut contents = Vec::with_capacity(count);
768        let mut stream = self.keys(default_range).await?;
769        while let Some(key) = stream.try_next().await? {
770            contents.push(key);
771        }
772
773        assert_eq!(count, contents.len());
774
775        Ok(true)
776    }
777}
778
779enum NodeRead {
780    Excluded,
781    Child(Uuid),
782    Children(Box<SmallVec<[Uuid; NODE_STACK_SIZE]>>),
783    Leaf((usize, usize)),
784}
785
786impl fmt::Debug for NodeRead {
787    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
788        match self {
789            Self::Excluded => f.write_str("(none)"),
790            Self::Child(id) => write!(f, "child {id}"),
791            Self::Children(ids) => write!(f, "children {:?}", *ids),
792            Self::Leaf((start, end)) => write!(f, "leaf records [{start}..{end})"),
793        }
794    }
795}
796
797fn nodes_forward<C, V, BV, FE, G>(
798    dir: G,
799    collator: Collator<C>,
800    range: Range<BV>,
801    node_id: Uuid,
802) -> Pin<Box<dyn Future<Output = ResultNodes<FE, V>> + Send>>
803where
804    C: Collate<Value = V> + Clone + Send + Sync + 'static,
805    V: Clone + PartialEq + fmt::Debug + Send + Sync + 'static,
806    BV: Borrow<V> + Clone + Send + Sync + 'static,
807    FE: AsType<Node<V>> + Send + Sync + 'static,
808    G: DirDeref<Entry = FE> + Clone + Send + Sync + 'static,
809    Node<V>: FileLoad,
810{
811    #[cfg(feature = "logging")]
812    log::debug!("reading BTree keys in forward order");
813
814    let file = dir.as_dir().get_file(&node_id).expect("node").clone();
815    let fut = file.into_read().map_ok(move |node| {
816        let read = match &*node {
817            Node::Leaf(keys) if range.is_empty() => NodeRead::Leaf((0, keys.len())),
818            Node::Leaf(keys) => {
819                let (l, r) = keys.bisect(&range, &collator);
820
821                if r == 0 || l == keys.len() {
822                    NodeRead::Excluded
823                } else if l == r {
824                    if range.contains_value(&keys[l], &collator) {
825                        NodeRead::Leaf((l, l + 1))
826                    } else {
827                        NodeRead::Excluded
828                    }
829                } else {
830                    NodeRead::Leaf((l, r))
831                }
832            }
833            Node::Index(_bounds, children) if range.is_empty() => {
834                debug_assert!(!children.is_empty());
835
836                if children.len() == 1 {
837                    NodeRead::Child(children[0])
838                } else {
839                    NodeRead::Children(Box::new(SmallVec::from_slice(children)))
840                }
841            }
842            Node::Index(bounds, children) => {
843                let (l, r) = bounds.bisect(&range, &collator);
844                let l = if l == 0 { l } else { l - 1 };
845
846                if r == 0 {
847                    NodeRead::Excluded
848                } else if l == children.len() {
849                    NodeRead::Child(children[l - 1])
850                } else if l == r || l + 1 == r {
851                    NodeRead::Child(children[l])
852                } else {
853                    NodeRead::Children(Box::new(SmallVec::from_slice(&children[l..r])))
854                }
855            }
856        };
857
858        #[cfg(feature = "logging")]
859        log::trace!("read {read:?}");
860
861        let nodes: Nodes<FE, V> = match read {
862            NodeRead::Excluded => {
863                let nodes = stream::empty();
864                Box::pin(nodes)
865            }
866            NodeRead::Child(node_id) => {
867                let nodes =
868                    stream::once(nodes_forward(dir, collator, range, node_id)).try_flatten();
869
870                Box::pin(nodes)
871            }
872            NodeRead::Children(children) => {
873                let last_child = children.len() - 1;
874                let nodes = stream::iter(children.into_iter().enumerate())
875                    .map(move |(i, node_id)| {
876                        if i == 0 || i == last_child {
877                            nodes_forward(dir.clone(), collator.clone(), range.clone(), node_id)
878                        } else {
879                            nodes_forward(
880                                dir.clone(),
881                                collator.clone(),
882                                Range::<V>::default(),
883                                node_id,
884                            )
885                        }
886                    })
887                    .buffered(2)
888                    .try_flatten();
889
890                Box::pin(nodes)
891            }
892            NodeRead::Leaf(range) => {
893                let nodes = stream::once(future::ready(Ok(Leaf::new(node, range))));
894                Box::pin(nodes)
895            }
896        };
897
898        nodes
899    });
900
901    Box::pin(fut)
902}
903
904fn nodes_reverse<C, V, BV, FE, G>(
905    dir: G,
906    collator: Collator<C>,
907    range: Range<BV>,
908    node_id: Uuid,
909) -> Pin<Box<dyn Future<Output = ResultNodes<FE, V>> + Send>>
910where
911    C: Collate<Value = V> + Clone + Send + Sync + 'static,
912    V: Clone + PartialEq + fmt::Debug + Send + Sync + 'static,
913    BV: Borrow<V> + Clone + Send + Sync + 'static,
914    FE: AsType<Node<V>> + Send + Sync + 'static,
915    G: DirDeref<Entry = FE> + Clone + Send + Sync + 'static,
916    Node<V>: FileLoad,
917{
918    let file = dir.as_dir().get_file(&node_id).expect("node").clone();
919    let fut = file.into_read().map_ok(move |node| {
920        let read = match &*node {
921            Node::Leaf(keys) if range.is_empty() => NodeRead::Leaf((0, keys.len())),
922            Node::Leaf(keys) => {
923                let (l, r) = keys.bisect(&range, &collator);
924
925                if l == keys.len() || r == 0 {
926                    NodeRead::Excluded
927                } else if l == r {
928                    if range.contains_value(&keys[l], &collator) {
929                        NodeRead::Leaf((l, l + 1))
930                    } else {
931                        NodeRead::Excluded
932                    }
933                } else {
934                    NodeRead::Leaf((l, r))
935                }
936            }
937            Node::Index(_bounds, children) if range.is_empty() => {
938                debug_assert!(!children.is_empty());
939
940                if children.len() == 1 {
941                    NodeRead::Child(children[0])
942                } else {
943                    NodeRead::Children(Box::new(SmallVec::from_slice(children)))
944                }
945            }
946            Node::Index(bounds, children) => {
947                debug_assert!(!children.is_empty());
948
949                let (l, r) = bounds.bisect(&range, &collator);
950                let l = if l == 0 { l } else { l - 1 };
951
952                if r == 0 {
953                    NodeRead::Excluded
954                } else if l == children.len() {
955                    NodeRead::Child(children[l - 1])
956                } else if l == r || l + 1 == r {
957                    NodeRead::Child(children[l])
958                } else {
959                    NodeRead::Children(Box::new(SmallVec::from_slice(&children[l..r])))
960                }
961            }
962        };
963
964        let nodes: Nodes<FE, V> = match read {
965            NodeRead::Excluded => {
966                let nodes = stream::empty();
967                Box::pin(nodes)
968            }
969            NodeRead::Child(node_id) => {
970                let nodes =
971                    stream::once(nodes_reverse(dir, collator, range, node_id)).try_flatten();
972
973                Box::pin(nodes)
974            }
975            NodeRead::Children(children) => {
976                let last_child = children.len() - 1;
977                let nodes = stream::iter(children.into_iter().enumerate().rev())
978                    .map(move |(i, node_id)| {
979                        if i == 0 || i == last_child {
980                            nodes_reverse(dir.clone(), collator.clone(), range.clone(), node_id)
981                        } else {
982                            nodes_reverse(
983                                dir.clone(),
984                                collator.clone(),
985                                Range::<V>::default(),
986                                node_id,
987                            )
988                        }
989                    })
990                    .buffered(2)
991                    .try_flatten();
992
993                Box::pin(nodes)
994            }
995            NodeRead::Leaf(range) => {
996                let nodes = stream::once(future::ready(Ok(Leaf::new(node, range))));
997                Box::pin(nodes)
998            }
999        };
1000
1001        nodes
1002    });
1003
1004    Box::pin(fut)
1005}
1006
1007enum MergeIndexLeft<V> {
1008    Borrow(Vec<V>),
1009    Merge(Vec<V>),
1010}
1011
1012enum MergeIndexRight {
1013    Borrow,
1014    Merge,
1015}
1016
1017enum MergeLeafLeft<V> {
1018    Borrow(Vec<V>),
1019    Merge(Vec<V>),
1020}
1021
1022enum MergeLeafRight {
1023    Borrow,
1024    Merge,
1025}
1026
1027enum Delete<FE, V> {
1028    None,
1029    Left(Vec<V>),
1030    Right,
1031    Underflow(FileWriteGuardOwned<FE, Node<V>>),
1032}
1033
1034enum Insert<V> {
1035    None,
1036    Left(Vec<V>),
1037    Right,
1038    OverflowLeft(Vec<V>, Vec<V>, Uuid),
1039    Overflow(Vec<V>, Uuid),
1040}
1041
1042impl<S, C, FE> BTree<S, C, DirWriteGuardOwned<FE>> {
1043    /// Downgrade this [`BTreeWriteGuard`] into a [`BTreeReadGuard`].
1044    pub fn downgrade(self) -> BTreeReadGuard<S, C, FE> {
1045        BTreeReadGuard {
1046            schema: self.schema,
1047            collator: self.collator,
1048            dir: Arc::new(self.dir.downgrade()),
1049        }
1050    }
1051}
1052
1053impl<S, C, FE> BTree<S, C, DirWriteGuardOwned<FE>>
1054where
1055    S: Schema + Send + Sync,
1056    C: Collate<Value = S::Value> + Send + Sync,
1057    FE: AsType<Node<S::Value>> + Send + Sync,
1058    Node<S::Value>: FileLoad,
1059{
1060    /// Delete the given `key` from this B+Tree.
1061    pub async fn delete<V>(&mut self, key: &[V]) -> Result<bool, io::Error>
1062    where
1063        V: Borrow<S::Value> + Send + Sync,
1064    {
1065        debug_assert!(self.dir.contains(&ROOT), "B+Tree is missing its root node");
1066        let mut root = self.dir.write_file_owned(&ROOT).await?;
1067
1068        let new_root = match &mut *root {
1069            Node::Leaf(keys) => {
1070                let i = keys.bisect_left(key, &self.collator);
1071                if i < keys.len() && keys[i].iter().zip(key).all(|(l, r)| l == r.borrow()) {
1072                    keys.remove(i);
1073                    return Ok(true);
1074                } else {
1075                    return Ok(false);
1076                }
1077            }
1078            Node::Index(bounds, children) => {
1079                let i = match bounds.bisect_right(key, &self.collator) {
1080                    0 => return Ok(false),
1081                    i => i - 1,
1082                };
1083
1084                let node = self.dir.write_file_owned(&children[i]).await?;
1085                match self.delete_inner(node, key).await? {
1086                    Delete::None => return Ok(false),
1087                    Delete::Right => return Ok(true),
1088                    Delete::Left(bound) => {
1089                        bounds[i] = bound;
1090                        return Ok(true);
1091                    }
1092                    Delete::Underflow(mut node) => match &mut *node {
1093                        Node::Leaf(new_keys) => {
1094                            self.merge_leaf(new_keys, i, bounds, children).await?
1095                        }
1096                        Node::Index(new_bounds, new_children) => {
1097                            self.merge_index(new_bounds, new_children, i, bounds, children)
1098                                .await?
1099                        }
1100                    },
1101                }
1102
1103                if children.len() == 1 {
1104                    bounds.pop();
1105                    children.pop()
1106                } else {
1107                    None
1108                }
1109            }
1110        };
1111
1112        if let Some(only_child) = new_root {
1113            let new_root = {
1114                let mut child = self.dir.write_file(&only_child).await?;
1115                match &mut *child {
1116                    Node::Leaf(keys) => Node::Leaf(mem::take(keys)),
1117                    Node::Index(bounds, children) => {
1118                        Node::Index(mem::take(bounds), mem::take(children))
1119                    }
1120                }
1121            };
1122
1123            self.dir.delete(&only_child).await;
1124
1125            *root = new_root;
1126        }
1127
1128        Ok(true)
1129    }
1130
1131    fn delete_inner<'a, V>(
1132        &'a mut self,
1133        mut node: FileWriteGuardOwned<FE, Node<S::Value>>,
1134        key: &'a [V],
1135    ) -> Pin<Box<dyn Future<Output = ResultDelete<FE, S::Value>> + Send + 'a>>
1136    where
1137        V: Borrow<S::Value> + Send + Sync,
1138    {
1139        Box::pin(async move {
1140            match &mut *node {
1141                Node::Leaf(keys) => {
1142                    let i = keys.bisect_left(key, &self.collator);
1143
1144                    if i < keys.len() && keys[i].iter().zip(key).all(|(l, r)| l == r.borrow()) {
1145                        keys.remove(i);
1146
1147                        if keys.len() < (self.schema.order() / 2) {
1148                            Ok(Delete::Underflow(node))
1149                        } else if i == 0 {
1150                            Ok(Delete::Left(keys[0].to_vec()))
1151                        } else {
1152                            Ok(Delete::Right)
1153                        }
1154                    } else {
1155                        Ok(Delete::None)
1156                    }
1157                }
1158                Node::Index(bounds, children) => {
1159                    let i = match bounds.bisect_right(key, &self.collator) {
1160                        0 => return Ok(Delete::None),
1161                        i => i - 1,
1162                    };
1163
1164                    let child = self.dir.write_file_owned(&children[i]).await?;
1165                    match self.delete_inner(child, key).await? {
1166                        Delete::None => return Ok(Delete::None),
1167                        Delete::Right => return Ok(Delete::Right),
1168                        Delete::Left(bound) => {
1169                            bounds[i] = bound;
1170
1171                            return if i == 0 {
1172                                Ok(Delete::Left(bounds[0].to_vec()))
1173                            } else {
1174                                Ok(Delete::Right)
1175                            };
1176                        }
1177                        Delete::Underflow(mut node) => match &mut *node {
1178                            Node::Leaf(new_keys) => {
1179                                self.merge_leaf(new_keys, i, bounds, children).await?
1180                            }
1181                            Node::Index(new_bounds, new_children) => {
1182                                self.merge_index(new_bounds, new_children, i, bounds, children)
1183                                    .await?
1184                            }
1185                        },
1186                    }
1187
1188                    if children.len() > (self.schema.order() / 2) {
1189                        if i == 0 {
1190                            Ok(Delete::Left(bounds[0].to_vec()))
1191                        } else {
1192                            Ok(Delete::Right)
1193                        }
1194                    } else {
1195                        Ok(Delete::Underflow(node))
1196                    }
1197                }
1198            }
1199        })
1200    }
1201
1202    fn merge_index<'a>(
1203        &'a mut self,
1204        new_bounds: &'a mut Vec<Vec<S::Value>>,
1205        new_children: &'a mut Vec<Uuid>,
1206        i: usize,
1207        bounds: &'a mut Vec<Vec<S::Value>>,
1208        children: &'a mut Vec<Uuid>,
1209    ) -> Pin<Box<dyn Future<Output = Result<(), io::Error>> + Send + 'a>> {
1210        Box::pin(async move {
1211            if i == 0 {
1212                match self
1213                    .merge_index_left(new_bounds, new_children, &children[i + 1])
1214                    .await?
1215                {
1216                    MergeIndexLeft::Borrow(bound) => {
1217                        bounds[i] = new_bounds[0].to_vec();
1218                        bounds[i + 1] = bound;
1219                    }
1220                    MergeIndexLeft::Merge(bound) => {
1221                        self.dir.delete(&children[0]).await;
1222                        children.remove(0);
1223                        bounds.remove(0);
1224                        bounds[0] = bound;
1225                    }
1226                }
1227            } else {
1228                match self
1229                    .merge_index_right(new_bounds, new_children, &children[i - 1])
1230                    .await?
1231                {
1232                    MergeIndexRight::Borrow => {
1233                        bounds[i] = new_bounds[0].to_vec();
1234                    }
1235                    MergeIndexRight::Merge => {
1236                        self.dir.delete(&children[i]).await;
1237                        children.remove(i);
1238                        bounds.remove(i);
1239                    }
1240                }
1241            }
1242
1243            Ok(())
1244        })
1245    }
1246
1247    fn merge_index_left<'a>(
1248        &'a self,
1249        left_bounds: &'a mut Vec<Vec<S::Value>>,
1250        left_children: &'a mut Vec<Uuid>,
1251        node_id: &'a Uuid,
1252    ) -> Pin<Box<dyn Future<Output = ResultMergeIndex<S::Value>> + Send + 'a>> {
1253        Box::pin(async move {
1254            let mut node = self.dir.write_file(node_id).await?;
1255
1256            match &mut *node {
1257                Node::Leaf(_right_keys) => unreachable!("merge a leaf node with an index node"),
1258                Node::Index(right_bounds, right_children) => {
1259                    if right_bounds.len() > (self.schema.order() / 2) {
1260                        left_bounds.push(right_bounds.remove(0));
1261                        left_children.push(right_children.remove(0));
1262                        Ok(MergeIndexLeft::Borrow(right_bounds[0].to_vec()))
1263                    } else {
1264                        let mut new_bounds =
1265                            Vec::with_capacity(left_bounds.len() + right_bounds.len());
1266
1267                        new_bounds.append(left_bounds);
1268                        new_bounds.append(right_bounds);
1269                        *right_bounds = new_bounds;
1270
1271                        let mut new_children = Vec::with_capacity(right_bounds.len());
1272
1273                        new_children.append(left_children);
1274                        new_children.append(right_children);
1275                        *right_children = new_children;
1276
1277                        Ok(MergeIndexLeft::Merge(right_bounds[0].to_vec()))
1278                    }
1279                }
1280            }
1281        })
1282    }
1283
1284    fn merge_index_right<'a>(
1285        &'a self,
1286        right_bounds: &'a mut Vec<Vec<S::Value>>,
1287        right_children: &'a mut Vec<Uuid>,
1288        node_id: &'a Uuid,
1289    ) -> Pin<Box<dyn Future<Output = Result<MergeIndexRight, io::Error>> + Send + 'a>> {
1290        Box::pin(async move {
1291            let mut node = self.dir.write_file(node_id).await?;
1292
1293            match &mut *node {
1294                Node::Leaf(_left_keys) => unreachable!("merge a leaf node with an index node"),
1295                Node::Index(left_bounds, left_children) => {
1296                    if left_children.len() > (self.schema.order() / 2) {
1297                        let right = left_bounds.pop().expect("right");
1298                        right_bounds.insert(0, right);
1299
1300                        let right = left_children.pop().expect("right");
1301                        right_children.insert(0, right);
1302
1303                        Ok(MergeIndexRight::Borrow)
1304                    } else {
1305                        left_bounds.append(right_bounds);
1306                        left_children.append(right_children);
1307                        Ok(MergeIndexRight::Merge)
1308                    }
1309                }
1310            }
1311        })
1312    }
1313
1314    fn merge_leaf<'a>(
1315        &'a mut self,
1316        new_keys: &'a mut Vec<Vec<S::Value>>,
1317        i: usize,
1318        bounds: &'a mut Vec<Vec<S::Value>>,
1319        children: &'a mut Vec<Uuid>,
1320    ) -> Pin<Box<dyn Future<Output = Result<(), io::Error>> + Send + 'a>> {
1321        Box::pin(async move {
1322            if i == 0 {
1323                match self.merge_leaf_left(new_keys, &children[i + 1]).await? {
1324                    MergeLeafLeft::Borrow(bound) => {
1325                        bounds[i] = new_keys[0].to_vec();
1326                        bounds[i + 1] = bound;
1327                    }
1328                    MergeLeafLeft::Merge(bound) => {
1329                        self.dir.delete(&children[0]).await;
1330                        children.remove(0);
1331                        bounds.remove(0);
1332                        bounds[0] = bound;
1333                    }
1334                }
1335            } else {
1336                match self.merge_leaf_right(new_keys, &children[i - 1]).await? {
1337                    MergeLeafRight::Borrow => {
1338                        bounds[i] = new_keys[0].to_vec();
1339                    }
1340                    MergeLeafRight::Merge => {
1341                        self.dir.delete(&children[i]).await;
1342                        children.remove(i);
1343                        bounds.remove(i);
1344                    }
1345                }
1346            }
1347
1348            Ok(())
1349        })
1350    }
1351
1352    fn merge_leaf_left<'a>(
1353        &'a self,
1354        left_keys: &'a mut Vec<Vec<S::Value>>,
1355        node_id: &'a Uuid,
1356    ) -> Pin<Box<dyn Future<Output = ResultMergeLeaf<S::Value>> + Send + 'a>> {
1357        Box::pin(async move {
1358            let mut node = self.dir.write_file(node_id).await?;
1359
1360            match &mut *node {
1361                Node::Leaf(right_keys) => {
1362                    if right_keys.len() > (self.schema.order() / 2) {
1363                        left_keys.push(right_keys.remove(0));
1364                        Ok(MergeLeafLeft::Borrow(right_keys[0].to_vec()))
1365                    } else {
1366                        let mut new_keys = Vec::with_capacity(left_keys.len() + right_keys.len());
1367                        new_keys.append(left_keys);
1368                        new_keys.append(right_keys);
1369                        *right_keys = new_keys;
1370
1371                        Ok(MergeLeafLeft::Merge(right_keys[0].to_vec()))
1372                    }
1373                }
1374                Node::Index(bounds, children) => {
1375                    match self.merge_leaf_left(left_keys, &children[0]).await? {
1376                        MergeLeafLeft::Borrow(left) => {
1377                            bounds[0] = left.to_vec();
1378                            Ok(MergeLeafLeft::Borrow(left))
1379                        }
1380                        MergeLeafLeft::Merge(left) => {
1381                            bounds[0] = left.to_vec();
1382                            Ok(MergeLeafLeft::Merge(left))
1383                        }
1384                    }
1385                }
1386            }
1387        })
1388    }
1389
1390    fn merge_leaf_right<'a>(
1391        &'a self,
1392        right_keys: &'a mut Vec<Vec<S::Value>>,
1393        node_id: &'a Uuid,
1394    ) -> Pin<Box<dyn Future<Output = Result<MergeLeafRight, io::Error>> + Send + 'a>> {
1395        Box::pin(async move {
1396            let mut node = self.dir.write_file(node_id).await?;
1397
1398            match &mut *node {
1399                Node::Leaf(left_keys) => {
1400                    if left_keys.len() > (self.schema.order() / 2) {
1401                        let right = left_keys.pop().expect("right");
1402                        right_keys.insert(0, right);
1403                        Ok(MergeLeafRight::Borrow)
1404                    } else {
1405                        left_keys.append(right_keys);
1406                        Ok(MergeLeafRight::Merge)
1407                    }
1408                }
1409                Node::Index(_bounds, _children) => unreachable!("merge with the rightmost leaf"),
1410            }
1411        })
1412    }
1413
1414    /// Insert the given `key` into this B+Tree.
1415    /// Return `false` if te given `key` is already present.
1416    pub async fn insert(&mut self, key: Vec<S::Value>) -> Result<bool, io::Error> {
1417        let key = validate_key(&*self.schema, key)?;
1418        self.insert_root(key).await
1419    }
1420
1421    async fn insert_root(&mut self, key: Vec<S::Value>) -> Result<bool, io::Error> {
1422        let order = self.schema.order();
1423
1424        debug_assert!(self.dir.contains(&ROOT), "B+Tree is missing its root node");
1425        let mut root = self.dir.write_file_owned(&ROOT).await?;
1426
1427        let new_root = match &mut *root {
1428            Node::Leaf(keys) => {
1429                let i = keys.bisect_left(&key, &self.collator);
1430
1431                if keys.get(i) == Some(&key) {
1432                    // no-op
1433                    return Ok(false);
1434                }
1435
1436                keys.insert(i, key);
1437
1438                if keys.len() > order {
1439                    let mid = div_ceil(order, 2);
1440                    let size = self.schema.block_size() / 2;
1441
1442                    let right: Vec<_> = keys.drain(mid..).collect();
1443                    debug_assert!(right.len() >= mid);
1444
1445                    let right_key = right[0].clone();
1446                    let (right, _) = self.dir.create_file_unique(Node::Leaf(right), size)?;
1447
1448                    let left: Vec<_> = mem::take(keys);
1449                    debug_assert!(left.len() >= mid);
1450
1451                    let left_key = left[0].clone();
1452                    let (left, _) = self.dir.create_file_unique(Node::Leaf(left), size)?;
1453
1454                    Some(Node::Index(vec![left_key, right_key], vec![left, right]))
1455                } else {
1456                    None
1457                }
1458            }
1459            Node::Index(bounds, children) => {
1460                debug_assert_eq!(bounds.len(), children.len());
1461
1462                let i = match bounds.bisect_left(&key, &self.collator) {
1463                    0 => 0,
1464                    i => i - 1,
1465                };
1466
1467                let mut child = self.dir.write_file_owned(&children[i]).await?;
1468                let result = self.insert_inner(&mut child, key).await?;
1469
1470                match result {
1471                    Insert::None => return Ok(false),
1472                    Insert::Right => {}
1473                    Insert::Left(key) => {
1474                        bounds[i] = key;
1475                    }
1476                    Insert::OverflowLeft(left, middle, child_id) => {
1477                        bounds[i] = left;
1478                        bounds.insert(i + 1, middle);
1479                        children.insert(i + 1, child_id);
1480                    }
1481                    Insert::Overflow(bound, child_id) => {
1482                        bounds.insert(i + 1, bound);
1483                        children.insert(i + 1, child_id);
1484                    }
1485                }
1486
1487                // debug_assert!(self.collator.is_sorted(&bounds));
1488                debug_assert_eq!(bounds.len(), children.len());
1489
1490                if children.len() > order {
1491                    let size = self.schema.block_size() / 2;
1492                    let right_bounds: Vec<_> = bounds.drain(div_ceil(order, 2)..).collect();
1493                    let right_children: Vec<_> = children.drain(div_ceil(order, 2)..).collect();
1494                    let right_bound = right_bounds[0].clone();
1495                    let (right_node_id, _) = self
1496                        .dir
1497                        .create_file_unique(Node::Index(right_bounds, right_children), size)?;
1498
1499                    let left_bounds: Vec<_> = mem::take(bounds);
1500                    let left_children: Vec<_> = mem::take(children);
1501                    let left_bound = left_bounds[0].clone();
1502                    let (left_node_id, _) = self
1503                        .dir
1504                        .create_file_unique(Node::Index(left_bounds, left_children), size)?;
1505
1506                    Some(Node::Index(
1507                        vec![left_bound, right_bound],
1508                        vec![left_node_id, right_node_id],
1509                    ))
1510                } else {
1511                    None
1512                }
1513            }
1514        };
1515
1516        if let Some(new_root) = new_root {
1517            *root = new_root;
1518        }
1519
1520        Ok(true)
1521    }
1522
1523    fn insert_inner<'a>(
1524        &'a mut self,
1525        node: &'a mut Node<S::Value>,
1526        key: Vec<S::Value>,
1527    ) -> Pin<Box<dyn Future<Output = ResultInsert<S::Value>> + Send + 'a>> {
1528        Box::pin(async move {
1529            let order = self.schema.order();
1530
1531            match node {
1532                Node::Leaf(keys) => {
1533                    let i = keys.bisect_left(&key, &self.collator);
1534
1535                    if i < keys.len() && keys[i] == key {
1536                        // no-op
1537                        return Ok(Insert::None);
1538                    }
1539
1540                    keys.insert(i, key);
1541
1542                    let mid = order / 2;
1543
1544                    if keys.len() >= order {
1545                        let size = self.schema.block_size() / 2;
1546                        let new_leaf: Vec<_> = keys.drain(mid..).collect();
1547
1548                        debug_assert!(new_leaf.len() >= mid);
1549                        debug_assert!(keys.len() >= mid);
1550
1551                        let middle_key = new_leaf[0].to_vec();
1552                        let node = Node::Leaf(new_leaf);
1553                        let (new_node_id, _) = self.dir.create_file_unique(node, size)?;
1554
1555                        if i == 0 {
1556                            Ok(Insert::OverflowLeft(
1557                                keys[0].to_vec(),
1558                                middle_key,
1559                                new_node_id,
1560                            ))
1561                        } else {
1562                            Ok(Insert::Overflow(middle_key, new_node_id))
1563                        }
1564                    } else {
1565                        debug_assert!(keys.len() > mid);
1566
1567                        if i == 0 {
1568                            Ok(Insert::Left(keys[0].to_vec()))
1569                        } else {
1570                            Ok(Insert::Right)
1571                        }
1572                    }
1573                }
1574                Node::Index(bounds, children) => {
1575                    debug_assert_eq!(bounds.len(), children.len());
1576                    let size = self.schema.block_size() >> 1;
1577
1578                    let i = match bounds.bisect_left(&key, &self.collator) {
1579                        0 => 0,
1580                        i => i - 1,
1581                    };
1582
1583                    let mut child = self.dir.write_file_owned(&children[i]).await?;
1584
1585                    let overflow_left = match self.insert_inner(&mut child, key).await? {
1586                        Insert::None => return Ok(Insert::None),
1587                        Insert::Right => return Ok(Insert::Right),
1588                        Insert::Left(key) => {
1589                            bounds[i] = key;
1590
1591                            return if i == 0 {
1592                                Ok(Insert::Left(bounds[i].to_vec()))
1593                            } else {
1594                                Ok(Insert::Right)
1595                            };
1596                        }
1597                        Insert::OverflowLeft(left, middle, child_id) => {
1598                            bounds[i] = left;
1599                            bounds.insert(i + 1, middle);
1600                            children.insert(i + 1, child_id);
1601                            i == 0
1602                        }
1603                        Insert::Overflow(bound, child_id) => {
1604                            bounds.insert(i + 1, bound);
1605                            children.insert(i + 1, child_id);
1606                            false
1607                        }
1608                    };
1609
1610                    // debug_assert!(self.collator.is_sorted(bounds));
1611
1612                    if children.len() > order {
1613                        let mid = div_ceil(self.schema.order(), 2);
1614                        let new_bounds: Vec<_> = bounds.drain(mid..).collect();
1615                        let new_children: Vec<_> = children.drain(mid..).collect();
1616
1617                        let left_bound = new_bounds[0].to_vec();
1618                        let node = Node::Index(new_bounds, new_children);
1619                        let (node_id, _) = self.dir.create_file_unique(node, size)?;
1620
1621                        if overflow_left {
1622                            Ok(Insert::OverflowLeft(
1623                                bounds[0].to_vec(),
1624                                left_bound,
1625                                node_id,
1626                            ))
1627                        } else {
1628                            Ok(Insert::Overflow(left_bound, node_id))
1629                        }
1630                    } else if i == 0 {
1631                        Ok(Insert::Left(bounds[0].to_vec()))
1632                    } else {
1633                        Ok(Insert::Right)
1634                    }
1635                }
1636            }
1637        })
1638    }
1639
1640    /// Delete all the keys in this [`BTree`].
1641    pub async fn truncate(&mut self) -> Result<(), io::Error> {
1642        self.dir.truncate().await;
1643
1644        self.dir
1645            .create_file(ROOT.to_string(), Node::Leaf(vec![]), 0)?;
1646
1647        debug_assert!(
1648            self.dir.contains(&ROOT),
1649            "B+Tree failed to re-create its root node"
1650        );
1651
1652        Ok(())
1653    }
1654}
1655
1656impl<S, C, FE> BTree<S, C, DirWriteGuardOwned<FE>>
1657where
1658    S: Schema + Send + Sync,
1659    C: Collate<Value = S::Value> + Clone + Send + Sync + 'static,
1660    FE: AsType<Node<S::Value>> + Send + Sync + 'static,
1661    Node<S::Value>: FileLoad,
1662{
1663    /// Merge the keys from the `other` B+Tree range into this one.
1664    ///
1665    /// The source B+Tree **must** have an identical schema and collation.
1666    pub async fn merge<G>(&mut self, other: BTree<S, C, G>) -> Result<(), io::Error>
1667    where
1668        G: DirDeref<Entry = FE> + Clone + Send + Sync + 'static,
1669    {
1670        validate_collator_eq(&self.collator, &other.collator)?;
1671        validate_schema_eq(&self.schema, &other.schema)?;
1672
1673        let mut keys = other.keys(Range::<S::Value>::default()).await?;
1674        while let Some(key) = keys.try_next().await? {
1675            self.insert_root(key.into_vec()).await?;
1676        }
1677
1678        Ok(())
1679    }
1680
1681    /// Delete the keys in the `other` B+Tree from this one.
1682    ///
1683    /// The source B+Tree **must** have an identical schema and collation.
1684    pub async fn delete_all<G>(&mut self, other: BTree<S, C, G>) -> Result<(), io::Error>
1685    where
1686        G: DirDeref<Entry = FE> + Clone + Send + Sync + 'static,
1687    {
1688        validate_collator_eq(&self.collator, &other.collator)?;
1689        validate_schema_eq(&self.schema, &other.schema)?;
1690
1691        let mut keys = other.keys(Range::<S::Value>::default()).await?;
1692        while let Some(key) = keys.try_next().await? {
1693            self.delete(&key).await?;
1694        }
1695
1696        Ok(())
1697    }
1698}
1699
1700impl<S: fmt::Debug, C, G> fmt::Debug for BTree<S, C, G> {
1701    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1702        write!(f, "B+Tree index with schema {:?}", self.schema)
1703    }
1704}
1705
1706#[inline]
1707fn validate_key<S: Schema>(schema: &S, key: Vec<S::Value>) -> Result<Vec<S::Value>, io::Error> {
1708    schema
1709        .validate_key(key)
1710        .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))
1711}
1712
1713#[inline]
1714fn validate_collator_eq<S>(this: &S, that: &S) -> Result<(), io::Error>
1715where
1716    S: PartialEq,
1717{
1718    if this == that {
1719        Ok(())
1720    } else {
1721        Err(io::Error::new(
1722            io::ErrorKind::InvalidData,
1723            "B+Tree to merge must have the same collation",
1724        ))
1725    }
1726}
1727
1728#[inline]
1729fn validate_schema_eq<S>(this: &S, that: &S) -> Result<(), io::Error>
1730where
1731    S: PartialEq + fmt::Debug,
1732{
1733    if this == that {
1734        Ok(())
1735    } else {
1736        Err(io::Error::new(
1737            io::ErrorKind::InvalidData,
1738            format!(
1739                "cannot merge a B+Tree with schema {:?} into one with schema {:?}",
1740                that, this
1741            ),
1742        ))
1743    }
1744}
1745
1746#[inline]
1747fn div_ceil(num: usize, denom: usize) -> usize {
1748    match num % denom {
1749        0 => num / denom,
1750        _ => (num / denom) + 1,
1751    }
1752}
1753
1754#[inline]
1755fn stack_key<'a, T, A>(iter: A) -> SmallVec<[T; NODE_STACK_SIZE]>
1756where
1757    T: Clone + 'a,
1758    A: IntoIterator<Item = &'a T>,
1759{
1760    iter.into_iter().cloned().collect()
1761}