btree_vec/
lib.rs

1/*
2 * Copyright (C) 2021-2023, 2025 taylor.fish <contact@taylor.fish>
3 *
4 * This file is part of btree-vec.
5 *
6 * btree-vec is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * btree-vec is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with btree-vec. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20#![cfg_attr(not(all(test, btree_vec_debug)), no_std)]
21#![cfg_attr(
22    any(feature = "allocator_api", has_allocator_api),
23    feature(allocator_api)
24)]
25#![cfg_attr(feature = "dropck_eyepatch", feature(dropck_eyepatch))]
26#![deny(unsafe_op_in_unsafe_fn)]
27
28//! This crate provides a growable array (vector) implemented using a B-tree
29//! (more specifically, a B+ tree). It provides non-amortized O(log *n*) random
30//! accesses, insertions, and removals, as well as O(*n*) iteration. The
31//! branching factor is also customizable.
32//!
33//! The design is similar to [unsorted counted B-trees][cb] as described by
34//! Simon Tatham.
35//!
36//! [cb]: https://www.chiark.greenend.org.uk/~sgtatham/algorithms/cbtree.html
37//!
38//! For now, the vector supports insertions and removals only of single
39//! elements, but bulk operations, including implementations of [`Extend`]
40//! and [`FromIterator`], may be added in the future.
41//!
42//! Example
43//! -------
44//!
45//! ```rust
46//! # use btree_vec::BTreeVec;
47//! let mut vec = BTreeVec::new();
48//! for i in 0..20 {
49//!     vec.push(i);
50//! }
51//! for i in 0..10 {
52//!     assert!(vec.remove(i) == i * 2);
53//! }
54//! for i in 0..10 {
55//!     assert!(vec[i] == i * 2 + 1);
56//! }
57//! for i in 0..10 {
58//!     vec.insert(i * 2, i * 2);
59//! }
60//! assert!(vec.len() == 20);
61//! for (i, n) in vec.iter().copied().enumerate() {
62//!     assert!(i == n);
63//! }
64//! ```
65//!
66//! Crate features
67//! --------------
68//!
69//! If the crate feature `dropck_eyepatch` is enabled, items in a [`BTreeVec`]
70//! can contain references with the same life as the vector itself. This
71//! requires Rust nightly, as the unstable language feature [`dropck_eyepatch`]
72//! must be used.
73//!
74//! If the crate feature `allocator_api` is enabled, you can configure
75//! [`BTreeVec`] with the unstable [`Allocator`] trait. Alternatively, if the
76//! feature `allocator-fallback` is enabled, this crate will use the allocator
77//! API provided by [allocator-fallback] instead of the standard library’s.
78//!
79//! [`dropck_eyepatch`]: https://github.com/rust-lang/rust/issues/34761
80//! [allocator-fallback]: https://docs.rs/allocator-fallback
81//!
82//! [`Extend`]: core::iter::Extend
83//! [`FromIterator`]: core::iter::FromIterator
84//! [`Allocator`]: alloc::alloc::Allocator
85
86extern crate alloc;
87
88#[cfg(feature = "allocator_api")]
89use alloc::alloc as allocator;
90
91#[cfg(not(feature = "allocator_api"))]
92#[cfg(feature = "allocator-fallback")]
93use allocator_fallback as allocator;
94
95#[cfg(not(any_allocator_api))]
96#[path = "alloc_fallback.rs"]
97mod allocator;
98
99use alloc::boxed::Box;
100use allocator::{Allocator, Global};
101use core::fmt::{self, Debug, Formatter};
102use core::iter::{ExactSizeIterator, FusedIterator};
103use core::marker::PhantomData;
104use core::ops::{Index, IndexMut};
105use core::ptr::NonNull;
106
107#[cfg(btree_vec_debug)]
108pub mod debug;
109mod insert;
110mod node;
111mod remove;
112#[cfg(test)]
113mod tests;
114mod verified_alloc;
115
116use insert::{ItemInsertion, insert};
117use node::{LeafRef, Mutable, Node, NodeRef};
118use node::{PrefixCast, PrefixPtr, PrefixRef};
119use remove::remove;
120use verified_alloc::VerifiedAlloc;
121
122/// A growable array (vector) implemented as a B+ tree.
123///
124/// Provides non-amortized O(log n) random accesses, insertions, and removals,
125/// and O(n) iteration.
126///
127/// `B` is the branching factor. It must be at least 3. The standard library
128/// uses a value of 6 for its B-tree structures. Larger values are better when
129/// `T` is smaller.
130///
131/// # Mathematical variables
132///
133/// For the purposes of specifying the time complexity of various operations,
134/// *n* refers to the number of items in the vector.
135pub struct BTreeVec<T, const B: usize = 12, A: Allocator = Global> {
136    root: Option<PrefixPtr<T, B>>,
137    size: usize,
138    alloc: VerifiedAlloc<A>,
139    /// Lets dropck know that `T` may be dropped.
140    phantom: PhantomData<Box<T>>,
141}
142
143// SAFETY: `BTreeVec` owns its data, so it can be sent to another thread.
144unsafe impl<T, const B: usize, A> Send for BTreeVec<T, B, A>
145where
146    T: Send,
147    A: Allocator,
148{
149}
150
151// SAFETY: `BTreeVec` owns its data and provides access to it only through
152// standard borrows.
153unsafe impl<T, const B: usize, A> Sync for BTreeVec<T, B, A>
154where
155    T: Sync,
156    A: Allocator,
157{
158}
159
160fn leaf_for<T, const B: usize, R>(
161    mut root: PrefixRef<T, B, R>,
162    mut index: usize,
163) -> (LeafRef<T, B, R>, usize) {
164    loop {
165        let node = match root.cast() {
166            PrefixCast::Leaf(node) => return (node, index),
167            PrefixCast::Internal(node) => node,
168        };
169        let last = node.length() - 1;
170        let mut sizes = node.sizes.iter().copied().take(last);
171        let index = sizes
172            .position(|size| {
173                if let Some(n) = index.checked_sub(size) {
174                    index = n;
175                    false
176                } else {
177                    true
178                }
179            })
180            .unwrap_or(last);
181        root = node.into_child(index);
182    }
183}
184
185impl<T> BTreeVec<T> {
186    /// Creates a new [`BTreeVec`]. Note that this function is implemented
187    /// only for the default value of `B`; see [`Self::create`] for an
188    /// equivalent that works with all values of `B`.
189    pub fn new() -> Self {
190        Self::create()
191    }
192}
193
194impl<T, A: Allocator> BTreeVec<T, 12, A> {
195    #[cfg_attr(
196        not(any(feature = "allocator_api", feature = "allocator-fallback")),
197        doc(hidden)
198    )]
199    /// Creates a new [`BTreeVec`] with the given allocator. Note that this
200    /// function is implemented only for the default value of `B`; see
201    /// [`Self::create_in`] for an equivalent that works with all values of
202    /// `B`.
203    pub fn new_in(alloc: A) -> Self {
204        Self::create_in(alloc)
205    }
206}
207
208impl<T, const B: usize> BTreeVec<T, B> {
209    /// Creates a new [`BTreeVec`]. This function exists because
210    /// [`BTreeVec::new`] is implemented only for the default value of `B`.
211    pub fn create() -> Self {
212        Self::create_in(Global)
213    }
214}
215
216impl<T, const B: usize, A: Allocator> BTreeVec<T, B, A> {
217    #[cfg_attr(
218        not(any(feature = "allocator_api", feature = "allocator-fallback")),
219        doc(hidden)
220    )]
221    /// Creates a new [`BTreeVec`] with the given allocator. This function
222    /// exists because [`BTreeVec::new_in`] is implemented only for the default
223    /// value of `B`.
224    pub fn create_in(alloc: A) -> Self {
225        assert!(B >= 3);
226        // SAFETY:
227        //
228        // * All nodes are allocated by `alloc`, either via the calls to
229        //  `insert` and `LeafRef::alloc` in `Self::insert`. Nodes are
230        //  deallocated in two places: via the call to `remove` in
231        //  `Self::remove`, and via the call to `NodeRef::destroy` in
232        //  `Self::drop`. In both of these cases, `alloc` is provided as the
233        //  allocator with which to deallocate the nodes.
234        //
235        // * When `alloc` (`Self.alloc`) is dropped, `Self::drop` will have
236        //   run, which destroys all nodes. If `alloc`'s memory is reused
237        //   (e.g., via `mem::forget`), the only way this can happen is if the
238        //   operation that made its memory able to be reused applied to the
239        //   entire `BTreeVec`. Thus, all allocated nodes will become
240        //   inaccessible as they are not exposed via any public APIs,
241        //   guaranteeing that they will never be accessed.
242        let alloc = unsafe { VerifiedAlloc::new(alloc) };
243        Self {
244            root: None,
245            size: 0,
246            alloc,
247            phantom: PhantomData,
248        }
249    }
250
251    /// # Safety
252    ///
253    /// * There must not be any mutable references, including other
254    ///   [`NodeRef`]s where `R` is [`Mutable`], to any data accessible via the
255    ///   returned [`NodeRef`].
256    ///
257    /// [`Mutable`]: node::Mutable
258    unsafe fn leaf_for(&self, index: usize) -> (LeafRef<T, B>, usize) {
259        // SAFETY: Caller guarantees safety.
260        leaf_for(unsafe { NodeRef::new(self.root.unwrap()) }, index)
261    }
262
263    /// # Safety
264    ///
265    /// There must be no other references, including [`NodeRef`]s, to any data
266    /// accessible via the returned [`NodeRef`].
267    unsafe fn leaf_for_mut(
268        &mut self,
269        index: usize,
270    ) -> (LeafRef<T, B, Mutable>, usize) {
271        // SAFETY: Caller guarantees safety.
272        leaf_for(unsafe { NodeRef::new_mutable(self.root.unwrap()) }, index)
273    }
274
275    /// Gets the length of the vector.
276    ///
277    /// # Time complexity
278    ///
279    /// Constant.
280    pub fn len(&self) -> usize {
281        self.size
282    }
283
284    /// Checks whether the vector is empty.
285    ///
286    /// # Time complexity
287    ///
288    /// Constant.
289    pub fn is_empty(&self) -> bool {
290        self.size == 0
291    }
292
293    /// Gets the item at `index`, or [`None`] if no such item exists.
294    ///
295    /// # Time complexity
296    ///
297    /// Θ(log *n*).
298    pub fn get(&self, index: usize) -> Option<&T> {
299        (index < self.size).then(|| {
300            // SAFETY: `BTreeVec` uses `NodeRef`s in accordance with
301            // standard borrowing rules, so there are no existing mutable
302            // references.
303            let (leaf, index) = unsafe { self.leaf_for(index) };
304            &leaf.into_children()[index]
305        })
306    }
307
308    /// Gets a mutable reference to the item at `index`, or [`None`] if no such
309    /// item exists.
310    ///
311    /// # Time complexity
312    ///
313    /// Θ(log *n*).
314    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
315        (index < self.size).then(|| {
316            // SAFETY: `BTreeVec` uses `NodeRef`s in accordance with
317            // standard borrowing rules, so there are no existing references.
318            let (leaf, index) = unsafe { self.leaf_for_mut(index) };
319            &mut leaf.into_children_mut()[index]
320        })
321    }
322
323    /// Gets the first item in the vector, or [`None`] if the vector is empty.
324    ///
325    /// # Time complexity
326    ///
327    /// Θ(log *n*).
328    pub fn first(&self) -> Option<&T> {
329        self.get(0)
330    }
331
332    /// Gets a mutable reference to the first item in the vector, or [`None`]
333    /// if the vector is empty.
334    ///
335    /// # Time complexity
336    ///
337    /// Θ(log *n*).
338    pub fn first_mut(&mut self) -> Option<&mut T> {
339        self.get_mut(0)
340    }
341
342    /// Gets the last item in the vector, or [`None`] if the vector is empty.
343    ///
344    /// # Time complexity
345    ///
346    /// Θ(log *n*).
347    pub fn last(&self) -> Option<&T> {
348        self.size.checked_sub(1).and_then(|s| self.get(s))
349    }
350
351    /// Gets a mutable reference to the last item in the vector, or [`None`] if
352    /// the vector is empty.
353    ///
354    /// # Time complexity
355    ///
356    /// Θ(log *n*).
357    pub fn last_mut(&mut self) -> Option<&mut T> {
358        self.size.checked_sub(1).and_then(move |s| self.get_mut(s))
359    }
360
361    /// Inserts `item` at `index`.
362    ///
363    /// # Panics
364    ///
365    /// Panics if `index` is greater than [`self.len()`](Self::len).
366    ///
367    /// # Time complexity
368    ///
369    /// Θ(log *n*).
370    pub fn insert(&mut self, index: usize, item: T) {
371        assert!(index <= self.size);
372        self.root.get_or_insert_with(|| {
373            LeafRef::alloc(&self.alloc).into_prefix().as_ptr()
374        });
375        // SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
376        // borrowing rules, so there are no existing references.
377        let (leaf, index) = unsafe { self.leaf_for_mut(index) };
378        let root = insert(
379            ItemInsertion {
380                node: leaf,
381                index,
382                item,
383                root_size: self.size,
384            },
385            &self.alloc,
386        );
387        self.root = Some(root.as_ptr());
388        self.size += 1;
389    }
390
391    /// Inserts `item` at the end of the vector.
392    ///
393    /// # Time complexity
394    ///
395    /// Θ(log *n*).
396    pub fn push(&mut self, item: T) {
397        self.insert(self.size, item);
398    }
399
400    /// Removes and returns the item at `index`.
401    ///
402    /// # Panics
403    ///
404    /// Panics if `index` is not less than [`self.len()`](Self::len).
405    ///
406    /// # Time complexity
407    ///
408    /// Θ(log *n*).
409    pub fn remove(&mut self, index: usize) -> T {
410        assert!(index < self.size);
411        // SAFETY: `BTreeVec` uses `NodeRef`s in accordance with
412        // standard borrowing rules, so there are no existing references.
413        let (leaf, index) = unsafe { self.leaf_for_mut(index) };
414        let (root, item) = remove(leaf, index, &self.alloc);
415        self.root = Some(root.as_ptr());
416        self.size -= 1;
417        item
418    }
419
420    /// Removes and returns the last item in the vector, or [`None`] if the
421    /// vector is empty.
422    ///
423    /// # Time complexity
424    ///
425    /// Θ(log *n*).
426    pub fn pop(&mut self) -> Option<T> {
427        self.size.checked_sub(1).map(|s| self.remove(s))
428    }
429
430    /// Gets an iterator that returns references to each item in the vector.
431    ///
432    /// # Time complexity
433    ///
434    /// Iteration over the entire vector is Θ(*n*).
435    pub fn iter(&self) -> Iter<'_, T, B> {
436        // SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
437        // borrowing rules, so there are no existing mutable references.
438        Iter {
439            leaf: self.root.map(|_| unsafe { self.leaf_for(0) }.0),
440            index: 0,
441            remaining: self.len(),
442            phantom: PhantomData,
443        }
444    }
445
446    /// Gets an iterator that returns mutable references to each item in the
447    /// vector.
448    ///
449    /// # Time complexity
450    ///
451    /// Iteration over the entire vector is Θ(*n*).
452    pub fn iter_mut(&mut self) -> IterMut<'_, T, B> {
453        // SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
454        // borrowing rules, so there are no existing references.
455        IterMut {
456            leaf: self.root.map(|_| unsafe { self.leaf_for_mut(0) }.0),
457            index: 0,
458            remaining: self.len(),
459            phantom: PhantomData,
460        }
461    }
462}
463
464impl<T, const B: usize, A> Default for BTreeVec<T, B, A>
465where
466    A: Allocator + Default,
467{
468    fn default() -> Self {
469        Self::create_in(A::default())
470    }
471}
472
473impl<T, const B: usize, A: Allocator> Index<usize> for BTreeVec<T, B, A> {
474    type Output = T;
475
476    fn index(&self, index: usize) -> &T {
477        self.get(index).unwrap()
478    }
479}
480
481impl<T, const B: usize, A: Allocator> IndexMut<usize> for BTreeVec<T, B, A> {
482    fn index_mut(&mut self, index: usize) -> &mut T {
483        self.get_mut(index).unwrap()
484    }
485}
486
487impl<T: Debug, const B: usize, A: Allocator> Debug for BTreeVec<T, B, A> {
488    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
489        f.debug_list().entries(self.iter()).finish()
490    }
491}
492
493// SAFETY: This `Drop` impl does not directly or indirectly access any data in
494// any `T`, except for calling its destructor (see [1]), and `Self` contains a
495// `PhantomData<Box<T>>` so dropck knows that `T` may be dropped (see [2]).
496//
497// [1]: https://doc.rust-lang.org/nomicon/dropck.html
498// [2]: https://forge.rust-lang.org/libs/maintaining-std.html
499//      #is-there-a-manual-drop-implementation
500#[cfg_attr(feature = "dropck_eyepatch", add_syntax::prepend(unsafe))]
501impl<#[cfg_attr(feature = "dropck_eyepatch", may_dangle)] T, const B: usize, A>
502    Drop for BTreeVec<T, B, A>
503where
504    A: Allocator,
505{
506    fn drop(&mut self) {
507        if let Some(root) = self.root {
508            // SAFETY: `BTreeVec` uses `NodeRef`s in accordance with
509            // standard borrowing rules, so there are no existing
510            // references.
511            unsafe { NodeRef::new_mutable(root) }.destroy(&self.alloc);
512        }
513    }
514}
515
516impl<T, const B: usize, A> Clone for BTreeVec<T, B, A>
517where
518    T: Clone,
519    A: Clone + Allocator,
520{
521    fn clone(&self) -> Self {
522        let root = self.root.map(|root| {
523            // SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
524            // borrowing rules, so there are no existing references.
525            unsafe { NodeRef::new(root) }
526                .clone_node(None, &self.alloc)
527                .0
528                .as_ptr()
529        });
530        Self {
531            root,
532            size: self.size,
533            alloc: self.alloc.clone(),
534            phantom: self.phantom,
535        }
536    }
537}
538
539fn nth<T, const B: usize, R>(
540    leaf: LeafRef<T, B, R>,
541    index: usize,
542    mut n: usize,
543) -> Option<(LeafRef<T, B, R>, usize)> {
544    if let Some(new) = n.checked_sub(leaf.length() - index) {
545        n = new;
546    } else {
547        return Some((leaf, index + n));
548    };
549    let mut child_index = leaf.index();
550    let mut parent = leaf.into_parent().ok()?;
551    loop {
552        let sizes = parent.sizes[..parent.length()].iter().copied();
553        for (i, size) in sizes.enumerate().skip(child_index + 1) {
554            if let Some(new) = n.checked_sub(size) {
555                n = new;
556            } else {
557                return Some(leaf_for(parent.into_child(i), n));
558            }
559        }
560        child_index = parent.index();
561        parent = parent.into_parent().ok()?;
562    }
563}
564
565/// An iterator over the items in a [`BTreeVec`].
566pub struct Iter<'a, T, const B: usize> {
567    leaf: Option<LeafRef<T, B>>,
568    index: usize,
569    remaining: usize,
570    phantom: PhantomData<&'a T>,
571}
572
573impl<'a, T, const B: usize> Iterator for Iter<'a, T, B> {
574    type Item = &'a T;
575
576    fn next(&mut self) -> Option<Self::Item> {
577        let mut leaf = self.leaf?;
578        if self.index == leaf.length() {
579            self.leaf = self.leaf.take().unwrap().into_next().ok();
580            leaf = self.leaf?;
581            self.index = 0;
582        }
583        let index = self.index;
584        self.index += 1;
585        self.remaining -= 1;
586        Some(&leaf.into_children()[index])
587    }
588
589    fn nth(&mut self, n: usize) -> Option<Self::Item> {
590        let remaining = core::mem::replace(&mut self.remaining, 0);
591        let (leaf, i) = nth(self.leaf.take()?, self.index, n)?;
592        self.index = i + 1;
593        self.remaining = remaining - n - 1;
594        Some(&self.leaf.insert(leaf).into_children()[i])
595    }
596
597    fn size_hint(&self) -> (usize, Option<usize>) {
598        (self.remaining, Some(self.remaining))
599    }
600}
601
602impl<T, const B: usize> FusedIterator for Iter<'_, T, B> {}
603
604impl<T, const B: usize> ExactSizeIterator for Iter<'_, T, B> {
605    fn len(&self) -> usize {
606        let (lower, upper) = self.size_hint();
607        debug_assert_eq!(Some(lower), upper);
608        lower
609    }
610}
611
612impl<T, const B: usize> Clone for Iter<'_, T, B> {
613    fn clone(&self) -> Self {
614        Self {
615            leaf: self.leaf,
616            index: self.index,
617            remaining: self.remaining,
618            phantom: self.phantom,
619        }
620    }
621}
622
623// SAFETY: This type yields immutable references to items in the vector, so it
624// can be `Send` as long as `T` is `Sync` (which means `&T` is `Send`).
625unsafe impl<T: Sync, const B: usize> Send for Iter<'_, T, B> {}
626
627// SAFETY: This type has no `&self` methods that access shared data or fields
628// with non-`Sync` interior mutability, but `T` must be `Sync` to match the
629// `Send` impl, since this type implements `Clone`, effectively allowing it to
630// be sent.
631unsafe impl<T: Sync, const B: usize> Sync for Iter<'_, T, B> {}
632
633impl<'a, T, const B: usize, A> IntoIterator for &'a BTreeVec<T, B, A>
634where
635    A: Allocator,
636{
637    type Item = &'a T;
638    type IntoIter = Iter<'a, T, B>;
639
640    fn into_iter(self) -> Self::IntoIter {
641        self.iter()
642    }
643}
644
645/// A mutable iterator over the items in a [`BTreeVec`].
646pub struct IterMut<'a, T, const B: usize> {
647    leaf: Option<LeafRef<T, B, Mutable>>,
648    index: usize,
649    remaining: usize,
650    phantom: PhantomData<&'a mut T>,
651}
652
653impl<'a, T, const B: usize> Iterator for IterMut<'a, T, B> {
654    type Item = &'a mut T;
655
656    fn next(&mut self) -> Option<Self::Item> {
657        let mut leaf = self.leaf.as_mut()?;
658        if self.index == leaf.length() {
659            self.leaf = self.leaf.take().unwrap().into_next().ok();
660            leaf = self.leaf.as_mut()?;
661            self.index = 0;
662        }
663        let index = self.index;
664        self.index += 1;
665        self.remaining -= 1;
666        let item = &mut leaf.children_mut()[index];
667        // SAFETY: Extending the lifetime to `'a` is okay because `'a` doesn't
668        // outlive the `BTreeVec` and we won't access this index again for the
669        // life of the iterator.
670        Some(unsafe { NonNull::from(item).as_mut() })
671    }
672
673    fn nth(&mut self, n: usize) -> Option<Self::Item> {
674        let remaining = core::mem::replace(&mut self.remaining, 0);
675        let (leaf, i) = nth(self.leaf.take()?, self.index, n)?;
676        self.index = i + 1;
677        self.remaining = remaining - n - 1;
678        let item = &mut self.leaf.insert(leaf).children_mut()[i];
679        // SAFETY: Extending the lifetime to `'a` is okay because `'a` doesn't
680        // outlive the `BTreeVec` and we won't access this index again for the
681        // life of the iterator.
682        Some(unsafe { NonNull::from(item).as_mut() })
683    }
684
685    fn size_hint(&self) -> (usize, Option<usize>) {
686        (self.remaining, Some(self.remaining))
687    }
688}
689
690impl<T, const B: usize> FusedIterator for IterMut<'_, T, B> {}
691
692impl<T, const B: usize> ExactSizeIterator for IterMut<'_, T, B> {
693    fn len(&self) -> usize {
694        let (lower, upper) = self.size_hint();
695        debug_assert_eq!(Some(lower), upper);
696        lower
697    }
698}
699
700// SAFETY: This type yields mutable references to items in the vector, so it
701// can be `Send` as long as `T` is `Send`. `T` doesn't need to be `Sync`
702// because no other iterator that yields items from the vector can exist at the
703// same time as this iterator.
704unsafe impl<T: Send, const B: usize> Send for IterMut<'_, T, B> {}
705
706// SAFETY: This type has no `&self` methods that access any fields.
707unsafe impl<T, const B: usize> Sync for IterMut<'_, T, B> {}
708
709impl<'a, T, const B: usize, A> IntoIterator for &'a mut BTreeVec<T, B, A>
710where
711    A: Allocator,
712{
713    type Item = &'a mut T;
714    type IntoIter = IterMut<'a, T, B>;
715
716    fn into_iter(self) -> Self::IntoIter {
717        self.iter_mut()
718    }
719}
720
721/// An owning iterator over the items in a [`BTreeVec`].
722pub struct IntoIter<T, const B: usize, A: Allocator = Global> {
723    leaf: Option<LeafRef<T, B, Mutable>>,
724    length: usize,
725    index: usize,
726    remaining: usize,
727    _tree: BTreeVec<T, B, A>,
728}
729
730impl<T, const B: usize, A: Allocator> Iterator for IntoIter<T, B, A> {
731    type Item = T;
732
733    fn next(&mut self) -> Option<Self::Item> {
734        let mut leaf = self.leaf.as_mut()?;
735        if self.index == self.length {
736            self.leaf = self.leaf.take().unwrap().into_next().ok();
737            leaf = self.leaf.as_mut()?;
738            self.index = 0;
739            self.length = leaf.length();
740            leaf.set_zero_length();
741        }
742        let index = self.index;
743        self.index += 1;
744        self.remaining -= 1;
745        // SAFETY: We haven't taken the item at `index` yet.
746        Some(unsafe { leaf.take_raw_child(index).assume_init() })
747    }
748
749    fn size_hint(&self) -> (usize, Option<usize>) {
750        (self.remaining, Some(self.remaining))
751    }
752}
753
754impl<T, const B: usize, A: Allocator> FusedIterator for IntoIter<T, B, A> {}
755
756impl<T, const B: usize> ExactSizeIterator for IntoIter<T, B> {
757    fn len(&self) -> usize {
758        let (lower, upper) = self.size_hint();
759        debug_assert_eq!(Some(lower), upper);
760        lower
761    }
762}
763
764// SAFETY: This type owns the items in the vector, so it can be `Send` as long
765// as `T` is `Send`.
766unsafe impl<T, const B: usize, A> Send for IntoIter<T, B, A>
767where
768    T: Send,
769    A: Allocator,
770{
771}
772
773// SAFETY: This type has no `&self` methods that access any fields.
774unsafe impl<T, const B: usize, A: Allocator> Sync for IntoIter<T, B, A> {}
775
776impl<T, const B: usize, A: Allocator> Drop for IntoIter<T, B, A> {
777    fn drop(&mut self) {
778        let mut leaf = if let Some(leaf) = self.leaf.take() {
779            leaf
780        } else {
781            return;
782        };
783        for i in self.index..self.length {
784            // SAFETY: We haven't taken the item at `index` yet.
785            unsafe {
786                leaf.take_raw_child(i).assume_init();
787            }
788        }
789    }
790}
791
792impl<T, const B: usize, A: Allocator> IntoIterator for BTreeVec<T, B, A> {
793    type Item = T;
794    type IntoIter = IntoIter<T, B, A>;
795
796    fn into_iter(mut self) -> Self::IntoIter {
797        // SAFETY: `BTreeVec` uses `NodeRef`s in accordance with standard
798        // borrowing rules, so because we own the `BTreeVec`, there are no
799        // existing references.
800        let leaf = self.root.map(|_| unsafe { self.leaf_for_mut(0) }.0);
801        IntoIter {
802            index: 0,
803            length: leaf.as_ref().map_or(0, |leaf| leaf.length()),
804            leaf,
805            remaining: self.len(),
806            _tree: self,
807        }
808    }
809}