• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

jneem / imbl / 9651244952

24 Jun 2024 07:26PM UTC coverage: 84.143% (-0.1%) from 84.245%
9651244952

Pull #81

github

web-flow
Merge 79f1aceca into 38699a7b7
Pull Request #81: Update proptest-derive requirement from 0.4 to 0.5

5784 of 6874 relevant lines covered (84.14%)

6592875.25 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.66
/src/nodes/btree.rs
1
// This Source Code Form is subject to the terms of the Mozilla Public
2
// License, v. 2.0. If a copy of the MPL was not distributed with this
3
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4

5
use std::borrow::Borrow;
6
use std::cmp::Ordering;
7
use std::mem;
8
use std::ops::{Bound, RangeBounds};
9

10
use imbl_sized_chunks::Chunk;
11

12
pub(crate) use crate::config::ORD_CHUNK_SIZE as NODE_SIZE;
13
use crate::util::{Pool, PoolClone, PoolDefault, PoolRef};
14

15
use self::Insert::*;
16
use self::InsertAction::*;
17

18
const MEDIAN: usize = (NODE_SIZE + 1) >> 1;
19
const NUM_CHILDREN: usize = NODE_SIZE + 1;
20

21
pub trait BTreeValue {
22
    type Key;
23
    fn ptr_eq(&self, other: &Self) -> bool;
24
    fn search_key<BK>(slice: &[Self], key: &BK) -> Result<usize, usize>
25
    where
26
        BK: Ord + ?Sized,
27
        Self: Sized,
28
        Self::Key: Borrow<BK>;
29
    fn search_value(slice: &[Self], value: &Self) -> Result<usize, usize>
30
    where
31
        Self: Sized;
32
    fn cmp_keys<BK>(&self, other: &BK) -> Ordering
33
    where
34
        BK: Ord + ?Sized,
35
        Self::Key: Borrow<BK>;
36
    fn cmp_values(&self, other: &Self) -> Ordering;
37
}
38

39
/// A node in a `BTree`.
40
///
41
/// A node is either internal, or a leaf. Leaf nodes have `None` for every child, and internal
42
/// nodes have `Some(_)` for every child. There will never be a mixture of `None`s and `Some`s.
43
///
44
/// The `children` array is never empty, and always has exactly one more element than `keys`. The
45
/// empty tree has no keys, and a single `None` child.
46
pub(crate) struct Node<A> {
47
    keys: Chunk<A, NODE_SIZE>,
48
    children: Chunk<Option<PoolRef<Node<A>>>, NUM_CHILDREN>,
49
}
50

51
#[cfg(feature = "pool")]
52
unsafe fn cast_uninit<A>(target: &mut A) -> &mut mem::MaybeUninit<A> {
53
    &mut *(target as *mut A as *mut mem::MaybeUninit<A>)
54
}
55

56
impl<A> PoolDefault for Node<A> {
57
    #[cfg(feature = "pool")]
58
    unsafe fn default_uninit(target: &mut mem::MaybeUninit<Self>) {
59
        let ptr: *mut Self = target.as_mut_ptr();
60
        Chunk::default_uninit(cast_uninit(&mut (*ptr).keys));
61
        Chunk::default_uninit(cast_uninit(&mut (*ptr).children));
62
        (*ptr).children.push_back(None);
63
    }
64
}
65

66
impl<A> PoolClone for Node<A>
67
where
68
    A: Clone,
69
{
70
    #[cfg(feature = "pool")]
71
    unsafe fn clone_uninit(&self, target: &mut mem::MaybeUninit<Self>) {
72
        self.keys
73
            .clone_uninit(cast_uninit(&mut (*target.as_mut_ptr()).keys));
74
        self.children
75
            .clone_uninit(cast_uninit(&mut (*target.as_mut_ptr()).children));
76
    }
77
}
78

79
pub(crate) enum Insert<A> {
80
    Added,
81
    Replaced(A),
82
    Split(Node<A>, A, Node<A>),
83
}
84

85
enum InsertAction<A> {
86
    AddedAction,
87
    ReplacedAction(A),
88
    InsertAt,
89
    InsertSplit(Node<A>, A, Node<A>),
90
}
91

92
/// The result of a remove operation.
93
pub(crate) enum Remove<A> {
94
    /// The key to remove was not found in the tree; nothing changed.
95
    NoChange,
96
    /// The key was found and removed: here it is.
97
    Removed(A),
98
    /// The key was found, and the root node of the tree was modified: here is the found key, and
99
    /// the new root node.
100
    Update(A, Node<A>),
101
}
102

103
enum Boundary {
104
    Lowest,
105
    Highest,
106
}
107

108
enum RemoveAction {
109
    DeleteAt(usize),
110
    PullUp(Boundary, usize, usize),
111
    Merge(usize),
112
    StealFromLeft(usize),
113
    StealFromRight(usize),
114
    MergeFirst(usize),
115
    ContinueDown(usize),
116
}
117

118
impl<A> Clone for Node<A>
119
where
120
    A: Clone,
121
{
122
    fn clone(&self) -> Self {
3,653,673✔
123
        Node {
3,653,673✔
124
            keys: self.keys.clone(),
3,653,673✔
125
            children: self.children.clone(),
3,653,673✔
126
        }
127
    }
3,653,673✔
128
}
129

130
impl<A> Default for Node<A> {
131
    fn default() -> Self {
49,940✔
132
        Node {
49,940✔
133
            keys: Chunk::new(),
49,940✔
134
            children: Chunk::unit(None),
49,940✔
135
        }
136
    }
49,940✔
137
}
138

139
impl<A> Node<A> {
140
    #[inline]
141
    fn has_room(&self) -> bool {
27,703,370✔
142
        self.keys.len() < NODE_SIZE
27,703,370✔
143
    }
27,703,370✔
144

145
    /// This name is slightly misleading, because we actually check whether this node is the
146
    /// minimum allowed size (for a non-root node).
147
    #[inline]
148
    fn too_small(&self) -> bool {
2,455,128✔
149
        self.keys.len() < MEDIAN
2,455,128✔
150
    }
2,455,128✔
151

152
    #[inline]
153
    pub(crate) fn unit(value: A) -> Self {
6✔
154
        Node {
6✔
155
            keys: Chunk::unit(value),
6✔
156
            children: Chunk::pair(None, None),
6✔
157
        }
158
    }
6✔
159

160
    #[inline]
161
    pub(crate) fn new_from_split(
63,566✔
162
        pool: &Pool<Node<A>>,
163
        left: Node<A>,
164
        median: A,
165
        right: Node<A>,
166
    ) -> Self {
167
        Node {
63,566✔
168
            keys: Chunk::unit(median),
63,566✔
169
            children: Chunk::pair(
63,566✔
170
                Some(PoolRef::new(pool, left)),
63,566✔
171
                Some(PoolRef::new(pool, right)),
63,566✔
172
            ),
173
        }
174
    }
63,566✔
175

176
    pub(crate) fn min(&self) -> Option<&A> {
177
        match self.children.first().unwrap() {
178
            None => self.keys.first(),
179
            Some(ref child) => child.min(),
180
        }
181
    }
182

183
    pub(crate) fn max(&self) -> Option<&A> {
184
        match self.children.last().unwrap() {
185
            None => self.keys.last(),
186
            Some(ref child) => child.max(),
187
        }
188
    }
189
}
190

191
impl<A: BTreeValue> Node<A> {
192
    // Checks that this tree is balanced, and returns its depth.
193
    #[cfg(test)]
194
    pub(crate) fn check_depth(&self) -> usize {
130,544✔
195
        if self.children.is_empty() {
130,544✔
196
            // This is an empty tree.
197
            0
×
198
        } else if self.children[0].is_none() {
130,544✔
199
            // This is a leaf node.
200
            1
90,452✔
201
        } else {
202
            let mut depth = None;
40,092✔
203
            for c in self.children.iter() {
169,094✔
204
                let d = c.as_ref().unwrap().check_depth();
129,002✔
205
                assert!(depth.is_none() || depth == Some(d));
129,002✔
206
                depth = Some(d);
129,002✔
207
            }
208
            depth.unwrap()
40,092✔
209
        }
210
    }
130,544✔
211

212
    // Checks that the keys are in the right order.
213
    #[cfg(test)]
214
    pub(crate) fn check_order(&self) {
1,542✔
215
        fn recurse<A: BTreeValue>(node: &Node<A>) -> (&A, &A) {
2,617,982✔
216
            for window in node.keys.windows(2) {
5,782,379✔
217
                assert!(window[0].cmp_values(&window[1]) == Ordering::Less);
3,164,397✔
218
            }
219
            if node.is_leaf() {
3,048,071✔
220
                (node.keys.first().unwrap(), node.keys.last().unwrap())
2,187,893✔
221
            } else {
222
                for i in 0..node.keys.len() {
1,308,220✔
223
                    let left_max = recurse(node.children[i].as_ref().unwrap()).1;
878,131✔
224
                    let right_min = recurse(node.children[i + 1].as_ref().unwrap()).0;
878,131✔
225
                    assert!(node.keys[i].cmp_values(left_max) == Ordering::Greater);
878,131✔
226
                    assert!(node.keys[i].cmp_values(right_min) == Ordering::Less);
878,131✔
227
                }
228
                (
430,089✔
229
                    recurse(node.children.first().unwrap().as_ref().unwrap()).0,
430,089✔
230
                    recurse(node.children.last().unwrap().as_ref().unwrap()).1,
430,089✔
231
                )
232
            }
233
        }
2,617,982✔
234
        if !self.keys.is_empty() {
1,542✔
235
            recurse(self);
1,542✔
236
        }
237
    }
1,542✔
238

239
    #[cfg(test)]
240
    pub(crate) fn check_size(&self) {
1,542✔
241
        fn recurse<A: BTreeValue>(node: &Node<A>) {
129,002✔
242
            assert!(node.keys.len() + 1 == node.children.len());
129,002✔
243
            assert!(node.keys.len() + 1 >= MEDIAN);
129,002✔
244
            if !node.is_leaf() {
129,002✔
245
                for c in &node.children {
157,401✔
246
                    recurse(c.as_ref().unwrap());
118,636✔
247
                }
248
            }
249
        }
129,002✔
250
        if !self.is_leaf() {
1,542✔
251
            for c in &self.children {
11,693✔
252
                recurse(c.as_ref().unwrap());
10,366✔
253
            }
254
        }
255
    }
1,542✔
256

257
    #[cfg(test)]
258
    pub(crate) fn check_sane(&self) {
1,542✔
259
        self.check_depth();
1,542✔
260
        self.check_order();
1,542✔
261
        self.check_size();
1,542✔
262
    }
1,542✔
263

264
    fn child_contains<BK>(&self, index: usize, key: &BK) -> bool
137,449✔
265
    where
266
        BK: Ord + ?Sized,
267
        A::Key: Borrow<BK>,
268
    {
269
        if let Some(Some(ref child)) = self.children.get(index) {
137,449✔
270
            child.lookup(key).is_some()
137,449✔
271
        } else {
272
            false
×
273
        }
274
    }
137,449✔
275

276
    pub(crate) fn lookup<BK>(&self, key: &BK) -> Option<&A>
12,566,254✔
277
    where
278
        BK: Ord + ?Sized,
279
        A::Key: Borrow<BK>,
280
    {
281
        if self.keys.is_empty() {
12,566,254✔
282
            return None;
1,794✔
283
        }
284
        // Perform a binary search, resulting in either a match or
285
        // the index of the first higher key, meaning we search the
286
        // child to the left of it.
287
        match A::search_key(&self.keys, key) {
12,564,460✔
288
            Ok(index) => Some(&self.keys[index]),
2,524,359✔
289
            Err(index) => match self.children[index] {
10,040,101✔
290
                None => None,
1,394,099✔
291
                Some(ref node) => node.lookup(key),
8,646,002✔
292
            },
293
        }
294
    }
12,566,254✔
295

296
    pub(crate) fn lookup_mut<BK>(&mut self, pool: &Pool<Node<A>>, key: &BK) -> Option<&mut A>
377,428✔
297
    where
298
        A: Clone,
299
        BK: Ord + ?Sized,
300
        A::Key: Borrow<BK>,
301
    {
302
        if self.keys.is_empty() {
377,428✔
303
            return None;
×
304
        }
305
        // Perform a binary search, resulting in either a match or
306
        // the index of the first higher key, meaning we search the
307
        // child to the left of it.
308
        match A::search_key(&self.keys, key) {
377,428✔
309
            Ok(index) => Some(&mut self.keys[index]),
101,308✔
310
            Err(index) => match self.children[index] {
276,120✔
311
                None => None,
×
312
                Some(ref mut child_ref) => {
276,120✔
313
                    let child = PoolRef::make_mut(pool, child_ref);
276,120✔
314
                    child.lookup_mut(pool, key)
276,120✔
315
                }
316
            },
317
        }
318
    }
377,428✔
319

320
    pub(crate) fn lookup_prev<BK>(&self, key: &BK) -> Option<&A>
2,037✔
321
    where
322
        BK: Ord + ?Sized,
323
        A::Key: Borrow<BK>,
324
    {
325
        if self.keys.is_empty() {
2,037✔
326
            return None;
×
327
        }
328
        match A::search_key(&self.keys, key) {
2,037✔
329
            Ok(index) => Some(&self.keys[index]),
338✔
330
            Err(index) => self.children[index]
1,699✔
331
                .as_ref()
332
                .and_then(|node| node.lookup_prev(key))
1,353✔
333
                // If we haven't found our search key yet, it isn't in any child subtree of ours.
334
                // That means that if index == 0 then we have no predecessor for the search key,
335
                // and if index > 0 then the predecessor is our key at index - 1.
336
                .or_else(|| index.checked_sub(1).and_then(|i| self.keys.get(i))),
711✔
337
        }
338
    }
2,037✔
339

340
    pub(crate) fn lookup_next<BK>(&self, key: &BK) -> Option<&A>
2,037✔
341
    where
342
        BK: Ord + ?Sized,
343
        A::Key: Borrow<BK>,
344
    {
345
        if self.keys.is_empty() {
2,037✔
346
            return None;
×
347
        }
348
        match A::search_key(&self.keys, key) {
2,037✔
349
            Ok(index) => Some(&self.keys[index]),
338✔
350
            Err(index) => self.children[index]
1,699✔
351
                .as_ref()
352
                .and_then(|node| node.lookup_next(key))
1,353✔
353
                // If we don't find the search key in the child subtree, then either our next key
354
                // is the search key's successor, or else we don't have a successor in our subtree.
355
                .or_else(|| self.keys.get(index)),
372✔
356
        }
357
    }
2,037✔
358

359
    pub(crate) fn lookup_prev_mut<BK>(&mut self, pool: &Pool<Node<A>>, key: &BK) -> Option<&mut A>
360
    where
361
        A: Clone,
362
        BK: Ord + ?Sized,
363
        A::Key: Borrow<BK>,
364
    {
365
        if self.keys.is_empty() {
366
            return None;
367
        }
368
        let keys = &mut self.keys;
369
        match A::search_key(keys, key) {
370
            Ok(index) => Some(&mut keys[index]),
371
            Err(index) => self.children[index]
372
                .as_mut()
373
                .and_then(|node| PoolRef::make_mut(pool, node).lookup_prev_mut(pool, key))
374
                .or_else(|| index.checked_sub(1).and_then(move |i| keys.get_mut(i))),
375
        }
376
    }
377

378
    pub(crate) fn lookup_next_mut<BK>(&mut self, pool: &Pool<Node<A>>, key: &BK) -> Option<&mut A>
379
    where
380
        A: Clone,
381
        BK: Ord + ?Sized,
382
        A::Key: Borrow<BK>,
383
    {
384
        if self.keys.is_empty() {
385
            return None;
386
        }
387
        let keys = &mut self.keys;
388
        match A::search_key(keys, key) {
389
            Ok(index) => Some(&mut keys[index]),
390
            Err(index) => self.children[index]
391
                .as_mut()
392
                .and_then(|node| PoolRef::make_mut(pool, node).lookup_next_mut(pool, key))
393
                .or_else(move || keys.get_mut(index)),
394
        }
395
    }
396

397
    pub(crate) fn path_first<'a, BK>(
79,551✔
398
        &'a self,
399
        mut path: Vec<(&'a Node<A>, usize)>,
400
    ) -> Vec<(&'a Node<A>, usize)>
401
    where
402
        A: 'a,
403
        BK: Ord + ?Sized,
404
        A::Key: Borrow<BK>,
405
    {
406
        if self.keys.is_empty() {
79,551✔
407
            return Vec::new();
533✔
408
        }
409
        match self.children[0] {
79,018✔
410
            None => {
411
                path.push((self, 0));
37,861✔
412
                path
37,861✔
413
            }
414
            Some(ref node) => {
41,157✔
415
                path.push((self, 0));
41,157✔
416
                node.path_first(path)
41,157✔
417
            }
418
        }
419
    }
79,551✔
420

421
    pub(crate) fn path_last<'a, BK>(
79,533✔
422
        &'a self,
423
        mut path: Vec<(&'a Node<A>, usize)>,
424
    ) -> Vec<(&'a Node<A>, usize)>
425
    where
426
        A: 'a,
427
        BK: Ord + ?Sized,
428
        A::Key: Borrow<BK>,
429
    {
430
        if self.keys.is_empty() {
79,533✔
431
            return Vec::new();
533✔
432
        }
433
        let end = self.children.len() - 1;
79,000✔
434
        match self.children[end] {
79,000✔
435
            None => {
436
                path.push((self, end - 1));
37,849✔
437
                path
37,849✔
438
            }
439
            Some(ref node) => {
41,151✔
440
                path.push((self, end));
41,151✔
441
                node.path_last(path)
41,151✔
442
            }
443
        }
444
    }
79,533✔
445

446
    pub(crate) fn path_next<'a, BK>(
10,205✔
447
        &'a self,
448
        key: &BK,
449
        mut path: Vec<(&'a Node<A>, usize)>,
450
    ) -> Vec<(&'a Node<A>, usize)>
451
    where
452
        A: 'a,
453
        BK: Ord + ?Sized,
454
        A::Key: Borrow<BK>,
455
    {
456
        if self.keys.is_empty() {
10,205✔
457
            return Vec::new();
×
458
        }
459
        match A::search_key(&self.keys, key) {
10,205✔
460
            Ok(index) => {
1,706✔
461
                path.push((self, index));
1,706✔
462
                path
1,706✔
463
            }
1,706✔
464
            Err(index) => match self.children[index] {
8,499✔
465
                None => match self.keys.get(index) {
1,730✔
466
                    Some(_) => {
467
                        path.push((self, index));
1,635✔
468
                        path
1,635✔
469
                    }
470
                    None => {
471
                        // go back up to find next
472
                        while let Some((node, idx)) = path.last() {
160✔
473
                            if node.keys.len() == *idx {
130✔
474
                                path.pop();
65✔
475
                            } else {
476
                                break;
477
                            }
478
                        }
479
                        path
95✔
480
                    }
481
                },
482
                Some(ref node) => {
6,769✔
483
                    path.push((self, index));
6,769✔
484
                    node.path_next(key, path)
6,769✔
485
                }
486
            },
487
        }
488
    }
10,205✔
489

490
    pub(crate) fn path_prev<'a, BK>(
10,229✔
491
        &'a self,
492
        key: &BK,
493
        mut path: Vec<(&'a Node<A>, usize)>,
494
    ) -> Vec<(&'a Node<A>, usize)>
495
    where
496
        A: 'a,
497
        BK: Ord + ?Sized,
498
        A::Key: Borrow<BK>,
499
    {
500
        if self.keys.is_empty() {
10,229✔
501
            return Vec::new();
×
502
        }
503
        match A::search_key(&self.keys, key) {
10,229✔
504
            Ok(index) => {
1,696✔
505
                path.push((self, index));
1,696✔
506
                path
1,696✔
507
            }
1,696✔
508
            Err(index) => match self.children[index] {
8,533✔
509
                None if index == 0 => {
1,752✔
510
                    // go back up to find prev
511
                    while let Some((_, idx)) = path.last_mut() {
99✔
512
                        if *idx == 0 {
91✔
513
                            path.pop();
21✔
514
                        } else {
515
                            *idx -= 1;
70✔
516
                            break;
517
                        }
518
                    }
519
                    path
78✔
520
                }
521
                None => {
522
                    path.push((self, index - 1));
1,674✔
523
                    path
1,674✔
524
                }
525
                Some(ref node) => {
6,781✔
526
                    path.push((self, index));
6,781✔
527
                    node.path_prev(key, path)
6,781✔
528
                }
529
            },
530
        }
531
    }
10,229✔
532

533
    fn split(
1,776,917✔
534
        &mut self,
535
        pool: &Pool<Node<A>>,
536
        value: A,
537
        ins_left: Option<Node<A>>,
538
        ins_right: Option<Node<A>>,
539
    ) -> Insert<A> {
540
        let left_child = ins_left.map(|node| PoolRef::new(pool, node));
2,225,071✔
541
        let right_child = ins_right.map(|node| PoolRef::new(pool, node));
2,225,071✔
542
        let index = A::search_value(&self.keys, &value).unwrap_err();
1,776,917✔
543
        let mut left_keys;
544
        let mut left_children;
545
        let mut right_keys;
546
        let mut right_children;
547
        let median;
548
        match index.cmp(&MEDIAN) {
1,776,917✔
549
            Ordering::Less => {
471,995✔
550
                self.children[index] = left_child;
471,995✔
551

552
                left_keys = Chunk::from_front(&mut self.keys, index);
471,995✔
553
                left_keys.push_back(value);
471,995✔
554
                left_keys.drain_from_front(&mut self.keys, MEDIAN - index - 1);
471,995✔
555

556
                left_children = Chunk::from_front(&mut self.children, index + 1);
471,995✔
557
                left_children.push_back(right_child);
471,995✔
558
                left_children.drain_from_front(&mut self.children, MEDIAN - index - 1);
471,995✔
559

560
                median = self.keys.pop_front();
471,995✔
561

562
                right_keys = Chunk::drain_from(&mut self.keys);
471,995✔
563
                right_children = Chunk::drain_from(&mut self.children);
471,995✔
564
            }
565
            Ordering::Greater => {
566
                self.children[index] = left_child;
1,074,861✔
567

568
                left_keys = Chunk::from_front(&mut self.keys, MEDIAN);
1,074,861✔
569
                left_children = Chunk::from_front(&mut self.children, MEDIAN + 1);
1,074,861✔
570

571
                median = self.keys.pop_front();
1,074,861✔
572

573
                right_keys = Chunk::from_front(&mut self.keys, index - MEDIAN - 1);
1,074,861✔
574
                right_keys.push_back(value);
1,074,861✔
575
                right_keys.append(&mut self.keys);
1,074,861✔
576

577
                right_children = Chunk::from_front(&mut self.children, index - MEDIAN);
1,074,861✔
578
                right_children.push_back(right_child);
1,074,861✔
579
                right_children.append(&mut self.children);
1,074,861✔
580
            }
581
            Ordering::Equal => {
230,061✔
582
                left_keys = Chunk::from_front(&mut self.keys, MEDIAN);
230,061✔
583
                left_children = Chunk::from_front(&mut self.children, MEDIAN);
230,061✔
584
                left_children.push_back(left_child);
230,061✔
585

586
                median = value;
230,061✔
587

588
                right_keys = Chunk::drain_from(&mut self.keys);
230,061✔
589
                right_children = Chunk::drain_from(&mut self.children);
230,061✔
590
                right_children[0] = right_child;
230,061✔
591
            }
592
        }
593

594
        debug_assert!(left_keys.len() == MEDIAN);
1,776,917✔
595
        debug_assert!(left_children.len() == MEDIAN + 1);
1,776,917✔
596
        debug_assert!(right_keys.len() == MEDIAN);
1,776,917✔
597
        debug_assert!(right_children.len() == MEDIAN + 1);
1,776,917✔
598

599
        Split(
1,776,917✔
600
            Node {
1,776,917✔
601
                keys: left_keys,
1,776,917✔
602
                children: left_children,
1,776,917✔
603
            },
604
            median,
1,776,917✔
605
            Node {
1,776,917✔
606
                keys: right_keys,
1,776,917✔
607
                children: right_children,
1,776,917✔
608
            },
609
        )
610
    }
1,776,917✔
611

612
    fn merge(middle: A, left: Node<A>, mut right: Node<A>) -> Node<A> {
156,934✔
613
        let mut keys = left.keys;
156,934✔
614
        keys.push_back(middle);
156,934✔
615
        keys.append(&mut right.keys);
156,934✔
616
        let mut children = left.children;
156,934✔
617
        children.append(&mut right.children);
156,934✔
618
        Node { keys, children }
156,934✔
619
    }
156,934✔
620

621
    fn pop_min(&mut self) -> (A, Option<PoolRef<Node<A>>>) {
205,613✔
622
        let value = self.keys.pop_front();
205,613✔
623
        let child = self.children.pop_front();
205,613✔
624
        (value, child)
205,555✔
625
    }
205,613✔
626

627
    fn pop_max(&mut self) -> (A, Option<PoolRef<Node<A>>>) {
37,894✔
628
        let value = self.keys.pop_back();
37,894✔
629
        let child = self.children.pop_back();
37,894✔
630
        (value, child)
37,850✔
631
    }
37,894✔
632

633
    fn push_min(&mut self, child: Option<PoolRef<Node<A>>>, value: A) {
37,911✔
634
        self.keys.push_front(value);
37,911✔
635
        self.children.push_front(child);
37,911✔
636
    }
37,911✔
637

638
    fn push_max(&mut self, child: Option<PoolRef<Node<A>>>, value: A) {
205,596✔
639
        self.keys.push_back(value);
205,596✔
640
        self.children.push_back(child);
205,596✔
641
    }
205,596✔
642

643
    fn is_leaf(&self) -> bool {
2,809,247✔
644
        // `children` is never empty, so we can index it.
645
        self.children[0].is_none()
2,809,247✔
646
    }
2,809,247✔
647

648
    pub(crate) fn insert(&mut self, pool: &Pool<Node<A>>, value: A) -> Insert<A>
28,207,973✔
649
    where
650
        A: Clone,
651
    {
652
        if self.keys.is_empty() {
28,207,973✔
653
            self.keys.push_back(value);
49,362✔
654
            self.children.push_back(None);
49,362✔
655
            return Insert::Added;
49,362✔
656
        }
657
        let (median, left, right) = match A::search_value(&self.keys, &value) {
29,935,528✔
658
            // Key exists in node
659
            Ok(index) => {
455,241✔
660
                return Insert::Replaced(mem::replace(&mut self.keys[index], value));
455,241✔
661
            }
662
            // Key is adjacent to some key in node
663
            Err(index) => {
27,703,370✔
664
                let has_room = self.has_room();
27,703,370✔
665
                let action = match self.children[index] {
27,703,370✔
666
                    // No child at location, this is the target node.
667
                    None => InsertAt,
8,731,828✔
668
                    // Child at location, pass it on.
669
                    Some(ref mut child_ref) => {
18,971,542✔
670
                        let child = PoolRef::make_mut(pool, child_ref);
18,971,542✔
671
                        match child.insert(pool, value.clone()) {
18,971,542✔
672
                            Insert::Added => AddedAction,
16,837,561✔
673
                            Insert::Replaced(value) => ReplacedAction(value),
420,630✔
674
                            Insert::Split(left, median, right) => InsertSplit(left, median, right),
1,713,351✔
675
                        }
676
                    }
677
                };
678
                match action {
27,703,370✔
679
                    ReplacedAction(value) => return Insert::Replaced(value),
420,630✔
680
                    AddedAction => {
681
                        return Insert::Added;
16,837,561✔
682
                    }
683
                    InsertAt => {
684
                        if has_room {
8,731,828✔
685
                            self.keys.insert(index, value);
7,403,065✔
686
                            self.children.insert(index + 1, None);
7,403,065✔
687
                            return Insert::Added;
7,403,065✔
688
                        } else {
689
                            (value, None, None)
1,328,763✔
690
                        }
1,328,763✔
691
                    }
692
                    InsertSplit(left, median, right) => {
1,713,351✔
693
                        if has_room {
1,713,351✔
694
                            self.children[index] = Some(PoolRef::new(pool, left));
1,265,197✔
695
                            self.keys.insert(index, median);
1,265,197✔
696
                            self.children
2,530,394✔
697
                                .insert(index + 1, Some(PoolRef::new(pool, right)));
1,265,197✔
698
                            return Insert::Added;
1,265,197✔
699
                        } else {
700
                            (median, Some(left), Some(right))
448,154✔
701
                        }
702
                    }
448,154✔
703
                }
704
            }
705
        };
706
        self.split(pool, median, left, right)
1,776,917✔
707
    }
28,207,973✔
708

709
    pub(crate) fn remove<BK>(&mut self, pool: &Pool<Node<A>>, key: &BK) -> Remove<A>
904,486✔
710
    where
711
        A: Clone,
712
        BK: Ord + ?Sized,
713
        A::Key: Borrow<BK>,
714
    {
715
        let index = A::search_key(&self.keys, key);
904,486✔
716
        self.remove_index(pool, index, Ok(key))
904,486✔
717
    }
904,486✔
718

719
    fn remove_target<BK>(
2,025,557✔
720
        &mut self,
721
        pool: &Pool<Node<A>>,
722
        target: Result<&BK, Boundary>,
723
    ) -> Remove<A>
724
    where
725
        A: Clone,
726
        BK: Ord + ?Sized,
727
        A::Key: Borrow<BK>,
728
    {
729
        let index = match target {
2,025,557✔
730
            Ok(key) => A::search_key(&self.keys, key),
1,953,557✔
731
            Err(Boundary::Lowest) => Err(0),
13,979✔
732
            Err(Boundary::Highest) => Err(self.keys.len()),
58,021✔
733
        };
734
        self.remove_index(pool, index, target)
2,025,557✔
735
    }
2,025,557✔
736

737
    fn remove_index<BK>(
2,930,043✔
738
        &mut self,
739
        pool: &Pool<Node<A>>,
740
        index: Result<usize, usize>,
741
        target: Result<&BK, Boundary>,
742
    ) -> Remove<A>
743
    where
744
        A: Clone,
745
        BK: Ord + ?Sized,
746
        A::Key: Borrow<BK>,
747
    {
748
        let action = match index {
2,930,043✔
749
            // Key exists in node, remove it.
750
            Ok(index) => {
766,229✔
751
                match (&self.children[index], &self.children[index + 1]) {
766,229✔
752
                    // If we're a leaf, just delete the entry.
753
                    (&None, &None) => RemoveAction::DeleteAt(index),
705,374✔
754
                    // First consider pulling either predecessor (from left) or successor (from right).
755
                    // otherwise just merge the two small children.
756
                    (Some(left), Some(right)) => {
60,855✔
757
                        if !left.too_small() {
60,855✔
758
                            RemoveAction::PullUp(Boundary::Highest, index, index)
36,851✔
759
                        } else if !right.too_small() {
24,004✔
760
                            RemoveAction::PullUp(Boundary::Lowest, index, index + 1)
10,534✔
761
                        } else {
762
                            RemoveAction::Merge(index)
13,470✔
763
                        }
764
                    }
765
                    _ => unreachable!("Branch missing children"),
×
766
                }
767
            }
768
            // Target is adjacent to some key in node
769
            Err(index) => match self.children[index] {
2,163,814✔
770
                // We're deading with a leaf node
771
                None => match target {
199,112✔
772
                    // No child at location means key isn't in map.
773
                    Ok(_key) => return Remove::NoChange,
151,727✔
774
                    // Looking for the lowest or highest key
775
                    Err(Boundary::Lowest) => RemoveAction::DeleteAt(0),
10,534✔
776
                    Err(Boundary::Highest) => RemoveAction::DeleteAt(self.keys.len() - 1),
36,851✔
777
                },
778
                // Child at location, but it's at minimum capacity.
779
                Some(ref child) if child.too_small() => {
1,964,702✔
780
                    let left = if index > 0 {
386,971✔
781
                        self.children.get(index - 1)
68,956✔
782
                    } else {
783
                        None
318,015✔
784
                    }; // index is usize and can't be negative, best make sure it never is.
785
                    match (left, self.children.get(index + 1)) {
418,016✔
786
                        // If it has a left sibling with capacity, steal a key from it.
787
                        (Some(Some(old_left)), _) if !old_left.too_small() => {
68,956✔
788
                            RemoveAction::StealFromLeft(index)
37,911✔
789
                        }
37,911✔
790
                        // If it has a right sibling with capacity, same as above.
791
                        (_, Some(Some(old_right))) if !old_right.too_small() => {
336,611✔
792
                            RemoveAction::StealFromRight(index)
205,596✔
793
                        }
205,596✔
794
                        // If it has neither, we'll have to merge it with a sibling.
795
                        // If we have a right sibling, we'll merge with that.
796
                        (_, Some(&Some(_))) => RemoveAction::MergeFirst(index),
131,015✔
797
                        // If we have a left sibling, we'll merge with that.
798
                        (Some(&Some(_)), _) => RemoveAction::MergeFirst(index - 1),
12,449✔
799
                        // If none of the above, we're in a bad state.
800
                        _ => unreachable!(),
×
801
                    }
802
                }
803
                // Child at location, and it's big enough, we can recurse down.
804
                Some(_) => RemoveAction::ContinueDown(index),
1,577,731✔
805
            },
806
        };
807
        match action {
2,778,316✔
808
            RemoveAction::DeleteAt(index) => {
752,759✔
809
                let pair = self.keys.remove(index);
752,759✔
810
                self.children.remove(index);
752,759✔
811
                Remove::Removed(pair)
752,759✔
812
            }
752,759✔
813
            RemoveAction::PullUp(boundary, pull_to, child_index) => {
47,385✔
814
                let children = &mut self.children;
47,385✔
815
                let mut update = None;
47,385✔
816
                let value;
817
                if let Some(&mut Some(ref mut child_ref)) = children.get_mut(child_index) {
47,385✔
818
                    let child = PoolRef::make_mut(pool, child_ref);
47,385✔
819
                    match child.remove_target(pool, Err(boundary)) {
47,385✔
820
                        Remove::NoChange => unreachable!(),
×
821
                        Remove::Removed(pulled_value) => {
47,385✔
822
                            value = self.keys.set(pull_to, pulled_value);
47,385✔
823
                        }
47,385✔
824
                        Remove::Update(pulled_value, new_child) => {
×
825
                            value = self.keys.set(pull_to, pulled_value);
×
826
                            update = Some(new_child);
×
827
                        }
×
828
                    }
829
                } else {
830
                    unreachable!()
×
831
                }
832
                if let Some(new_child) = update {
47,385✔
833
                    children[child_index] = Some(PoolRef::new(pool, new_child));
×
834
                }
835
                Remove::Removed(value)
47,385✔
836
            }
47,385✔
837
            RemoveAction::Merge(index) => {
13,470✔
838
                let left = self.children.remove(index).unwrap();
13,470✔
839
                let right = self.children[index].take().unwrap();
13,470✔
840
                let value = self.keys.remove(index);
13,470✔
841
                let mut merged_child = Node::merge(
13,470✔
842
                    value,
843
                    PoolRef::unwrap_or_clone(left),
13,470✔
844
                    PoolRef::unwrap_or_clone(right),
13,470✔
845
                );
13,470✔
846
                let (removed, new_child) = match merged_child.remove_target(pool, target) {
26,940✔
847
                    Remove::NoChange => unreachable!(),
×
848
                    Remove::Removed(removed) => (removed, merged_child),
13,470✔
849
                    Remove::Update(removed, updated_child) => (removed, updated_child),
×
850
                };
851
                if self.keys.is_empty() {
13,470✔
852
                    // If we've depleted the root node, the merged child becomes the root.
853
                    Remove::Update(removed, new_child)
133✔
854
                } else {
855
                    self.children[index] = Some(PoolRef::new(pool, new_child));
13,337✔
856
                    Remove::Removed(removed)
13,337✔
857
                }
858
            }
13,470✔
859
            RemoveAction::StealFromLeft(index) => {
37,911✔
860
                let mut update = None;
37,911✔
861
                let out_value;
862
                {
863
                    let mut children = self.children.as_mut_slice()[index - 1..=index]
37,911✔
864
                        .iter_mut()
865
                        .map(|n| n.as_mut().unwrap());
75,822✔
866
                    let left = PoolRef::make_mut(pool, children.next().unwrap());
37,911✔
867
                    let child = PoolRef::make_mut(pool, children.next().unwrap());
37,911✔
868
                    // Prepare the rebalanced node.
869
                    child.push_min(
37,911✔
870
                        left.children.last().unwrap().clone(),
37,911✔
871
                        self.keys[index - 1].clone(),
37,911✔
872
                    );
873
                    match child.remove_target(pool, target) {
37,911✔
874
                        Remove::NoChange => {
875
                            // Key wasn't there, we need to revert the steal.
876
                            child.pop_min();
56✔
877
                            return Remove::NoChange;
56✔
878
                        }
879
                        Remove::Removed(value) => {
37,855✔
880
                            // If we did remove something, we complete the rebalancing.
881
                            let (left_value, _) = left.pop_max();
37,855✔
882
                            self.keys[index - 1] = left_value;
37,855✔
883
                            out_value = value;
37,855✔
884
                        }
37,855✔
885
                        Remove::Update(value, new_child) => {
×
886
                            // If we did remove something, we complete the rebalancing.
887
                            let (left_value, _) = left.pop_max();
×
888
                            self.keys[index - 1] = left_value;
×
889
                            update = Some(new_child);
×
890
                            out_value = value;
×
891
                        }
×
892
                    }
893
                }
894
                if let Some(new_child) = update {
37,855✔
895
                    self.children[index] = Some(PoolRef::new(pool, new_child));
×
896
                }
897
                Remove::Removed(out_value)
37,855✔
898
            }
37,911✔
899
            RemoveAction::StealFromRight(index) => {
205,596✔
900
                let mut update = None;
205,596✔
901
                let out_value;
902
                {
903
                    let mut children = self.children.as_mut_slice()[index..index + 2]
205,596✔
904
                        .iter_mut()
905
                        .map(|n| n.as_mut().unwrap());
411,192✔
906
                    let child = PoolRef::make_mut(pool, children.next().unwrap());
205,596✔
907
                    let right = PoolRef::make_mut(pool, children.next().unwrap());
205,596✔
908
                    // Prepare the rebalanced node.
909
                    child.push_max(right.children[0].clone(), self.keys[index].clone());
205,596✔
910
                    match child.remove_target(pool, target) {
205,596✔
911
                        Remove::NoChange => {
912
                            // Key wasn't there, we need to revert the steal.
913
                            child.pop_max();
39✔
914
                            return Remove::NoChange;
39✔
915
                        }
916
                        Remove::Removed(value) => {
205,557✔
917
                            // If we did remove something, we complete the rebalancing.
918
                            let (right_value, _) = right.pop_min();
205,557✔
919
                            self.keys[index] = right_value;
205,557✔
920
                            out_value = value;
205,557✔
921
                        }
205,557✔
922
                        Remove::Update(value, new_child) => {
×
923
                            // If we did remove something, we complete the rebalancing.
924
                            let (right_value, _) = right.pop_min();
×
925
                            self.keys[index] = right_value;
×
926
                            update = Some(new_child);
×
927
                            out_value = value;
×
928
                        }
×
929
                    }
930
                }
931
                if let Some(new_child) = update {
205,557✔
932
                    self.children[index] = Some(PoolRef::new(pool, new_child));
×
933
                }
934
                Remove::Removed(out_value)
205,557✔
935
            }
205,596✔
936
            RemoveAction::MergeFirst(index) => {
143,464✔
937
                if let Ok(key) = target {
143,464✔
938
                    // Bail early if we're looking for a not existing key
939
                    match self.keys[index].cmp_keys(key) {
137,449✔
940
                        Ordering::Less if !self.child_contains(index + 1, key) => {
8,136✔
941
                            return Remove::NoChange
×
942
                        }
943
                        Ordering::Greater if !self.child_contains(index, key) => {
129,313✔
944
                            return Remove::NoChange
×
945
                        }
946
                        _ => (),
947
                    }
948
                }
949
                let left = self.children.remove(index).unwrap();
143,464✔
950
                let right = self.children[index].take().unwrap();
143,464✔
951
                let middle = self.keys.remove(index);
143,464✔
952
                let mut merged = Node::merge(
143,464✔
953
                    middle,
954
                    PoolRef::unwrap_or_clone(left),
143,464✔
955
                    PoolRef::unwrap_or_clone(right),
143,464✔
956
                );
143,464✔
957
                let update;
958
                let out_value;
959
                match merged.remove_target(pool, target) {
143,464✔
960
                    Remove::NoChange => {
961
                        panic!("nodes::btree::Node::remove: caught an absent key too late while merging");
×
962
                    }
963
                    Remove::Removed(value) => {
143,464✔
964
                        if self.keys.is_empty() {
143,464✔
965
                            return Remove::Update(value, merged);
3,510✔
966
                        }
967
                        update = merged;
139,954✔
968
                        out_value = value;
139,954✔
969
                    }
139,954✔
970
                    Remove::Update(value, new_child) => {
×
971
                        if self.keys.is_empty() {
×
972
                            return Remove::Update(value, new_child);
×
973
                        }
974
                        update = new_child;
×
975
                        out_value = value;
×
976
                    }
×
977
                }
978
                self.children[index] = Some(PoolRef::new(pool, update));
139,954✔
979
                Remove::Removed(out_value)
139,954✔
980
            }
143,464✔
981
            RemoveAction::ContinueDown(index) => {
1,577,731✔
982
                let mut update = None;
1,577,731✔
983
                let out_value;
984
                if let Some(&mut Some(ref mut child_ref)) = self.children.get_mut(index) {
1,577,731✔
985
                    let child = PoolRef::make_mut(pool, child_ref);
1,577,731✔
986
                    match child.remove_target(pool, target) {
1,577,731✔
987
                        Remove::NoChange => return Remove::NoChange,
307,416✔
988
                        Remove::Removed(value) => {
1,270,315✔
989
                            out_value = value;
1,270,315✔
990
                        }
1,270,315✔
991
                        Remove::Update(value, new_child) => {
×
992
                            update = Some(new_child);
×
993
                            out_value = value;
×
994
                        }
×
995
                    }
996
                } else {
997
                    unreachable!()
×
998
                }
999
                if let Some(new_child) = update {
1,270,315✔
1000
                    self.children[index] = Some(PoolRef::new(pool, new_child));
×
1001
                }
1002
                Remove::Removed(out_value)
1,270,315✔
1003
            }
1,577,731✔
1004
        }
1005
    }
2,930,043✔
1006
}
1007

1008
// Iterator
1009

1010
/// An iterator over an ordered set.
1011
pub struct Iter<'a, A> {
1012
    /// Path to the next element that we'll yield if we take a forward step.  Each element here is
1013
    /// of the form `(node, index)`. For the last path element, `index` points to the next key to
1014
    /// yield. For every other path element, `index` is the child index of the next node in the
1015
    /// path.
1016
    fwd_path: Vec<(&'a Node<A>, usize)>,
1017
    /// Path to the next element that we'll yield if we take a backward step. This has the same
1018
    /// format as `fwd_path`.
1019
    back_path: Vec<(&'a Node<A>, usize)>,
1020
    pub(crate) remaining: usize,
1021
}
1022

1023
// We impl Clone instead of deriving it, because we want Clone even if K and V aren't.
1024
impl<'a, A> Clone for Iter<'a, A> {
1025
    fn clone(&self) -> Self {
1026
        Iter {
1027
            fwd_path: self.fwd_path.clone(),
1028
            back_path: self.back_path.clone(),
1029
            remaining: self.remaining,
1030
        }
1031
    }
1032
}
1033

1034
impl<'a, A: BTreeValue> Iter<'a, A> {
1035
    pub(crate) fn new<R, BK>(root: &'a Node<A>, size: usize, range: R) -> Self
41,830✔
1036
    where
1037
        R: RangeBounds<BK>,
1038
        A::Key: Borrow<BK>,
1039
        BK: Ord + ?Sized,
1040
    {
1041
        let fwd_path = match range.start_bound() {
41,830✔
1042
            Bound::Included(key) => root.path_next(key, Vec::new()),
3,436✔
1043
            Bound::Excluded(key) => {
×
1044
                let mut path = root.path_next(key, Vec::new());
×
1045
                if let Some(value) = Self::get(&path) {
×
1046
                    if value.cmp_keys(key) == Ordering::Equal {
×
1047
                        Self::step_forward(&mut path);
×
1048
                    }
1049
                }
1050
                path
×
1051
            }
×
1052
            Bound::Unbounded => root.path_first(Vec::new()),
38,394✔
1053
        };
1054
        let back_path = match range.end_bound() {
41,830✔
1055
            Bound::Included(key) => root.path_prev(key, Vec::new()),
2,062✔
1056
            Bound::Excluded(key) => {
1,386✔
1057
                let mut path = root.path_prev(key, Vec::new());
1,386✔
1058
                if let Some(value) = Self::get(&path) {
1,386✔
1059
                    if value.cmp_keys(key) == Ordering::Equal {
1,382✔
1060
                        Self::step_back(&mut path);
686✔
1061
                    }
1062
                }
1063
                path
1,386✔
1064
            }
1,386✔
1065
            Bound::Unbounded => root.path_last(Vec::new()),
38,382✔
1066
        };
1067
        Iter {
41,830✔
1068
            fwd_path,
41,830✔
1069
            back_path,
41,830✔
1070
            remaining: size,
1071
        }
1072
    }
41,830✔
1073

1074
    fn get(path: &[(&'a Node<A>, usize)]) -> Option<&'a A> {
22,363,302✔
1075
        match path.last() {
22,363,302✔
1076
            Some((node, index)) => Some(&node.keys[*index]),
22,325,514✔
1077
            None => None,
37,788✔
1078
        }
1079
    }
22,363,302✔
1080

1081
    fn step_forward(path: &mut Vec<(&'a Node<A>, usize)>) -> Option<&'a A> {
10,907,971✔
1082
        match path.pop() {
10,907,971✔
1083
            Some((node, index)) => {
10,907,971✔
1084
                let index = index + 1;
10,907,971✔
1085
                match node.children[index] {
10,907,971✔
1086
                    // Child between current and next key -> step down
1087
                    Some(ref child) => {
821,740✔
1088
                        path.push((node, index));
821,740✔
1089
                        path.push((child, 0));
821,740✔
1090
                        let mut node = child;
821,740✔
1091
                        while let Some(ref left_child) = node.children[0] {
1,017,990✔
1092
                            path.push((left_child, 0));
196,250✔
1093
                            node = left_child;
196,250✔
1094
                        }
1095
                        Some(&node.keys[0])
821,740✔
1096
                    }
821,740✔
1097
                    None => match node.keys.get(index) {
10,086,231✔
1098
                        // Yield next key
1099
                        value @ Some(_) => {
1100
                            path.push((node, index));
9,227,814✔
1101
                            value
9,227,814✔
1102
                        }
1103
                        // No more keys -> exhausted level, step up and yield
1104
                        None => loop {
1105
                            match path.pop() {
1,093,248✔
1106
                                None => {
1107
                                    return None;
36,689✔
1108
                                }
1109
                                Some((node, index)) => {
1,056,559✔
1110
                                    if let value @ Some(_) = node.keys.get(index) {
1,056,559✔
1111
                                        path.push((node, index));
821,728✔
1112
                                        return value;
821,728✔
1113
                                    }
1114
                                }
1115
                            }
1116
                        },
1117
                    },
9,227,814✔
1118
                }
1119
            }
1120
            None => None,
×
1121
        }
1122
    }
10,907,971✔
1123

1124
    fn step_back(path: &mut Vec<(&'a Node<A>, usize)>) -> Option<&'a A> {
252,090✔
1125
        // TODO: we're doing some repetitive leaf-vs-internal checking.
1126
        match path.pop() {
252,090✔
1127
            Some((node, index)) => match node.children[index] {
252,090✔
1128
                Some(ref child) => {
42,703✔
1129
                    path.push((node, index));
42,703✔
1130
                    let mut end = if child.is_leaf() {
42,703✔
1131
                        child.keys.len() - 1
29,961✔
1132
                    } else {
1133
                        child.children.len() - 1
12,742✔
1134
                    };
1135
                    path.push((child, end));
42,703✔
1136
                    let mut node = child;
42,703✔
1137
                    while let Some(ref right_child) = node.children[end] {
60,721✔
1138
                        end = if right_child.is_leaf() {
18,018✔
1139
                            right_child.keys.len() - 1
12,742✔
1140
                        } else {
1141
                            right_child.children.len() - 1
5,276✔
1142
                        };
1143
                        path.push((right_child, end));
18,018✔
1144
                        node = right_child;
18,018✔
1145
                    }
1146
                    Some(&node.keys[end])
42,703✔
1147
                }
42,703✔
1148
                None => {
1149
                    if index == 0 {
209,387✔
1150
                        loop {
1151
                            match path.pop() {
62,565✔
1152
                                None => {
1153
                                    return None;
532✔
1154
                                }
1155
                                Some((node, index)) => {
62,033✔
1156
                                    if index > 0 {
62,033✔
1157
                                        let index = index - 1;
42,702✔
1158
                                        path.push((node, index));
42,702✔
1159
                                        return Some(&node.keys[index]);
42,702✔
1160
                                    }
1161
                                }
1162
                            }
1163
                        }
1164
                    } else {
1165
                        let index = index - 1;
166,153✔
1166
                        path.push((node, index));
166,153✔
1167
                        Some(&node.keys[index])
166,153✔
1168
                    }
166,153✔
1169
                }
1170
            },
1171
            None => None,
×
1172
        }
1173
    }
252,090✔
1174
}
1175

1176
impl<'a, A: 'a + BTreeValue> Iterator for Iter<'a, A> {
1177
    type Item = &'a A;
1178

1179
    fn next(&mut self) -> Option<Self::Item> {
10,947,903✔
1180
        match Iter::get(&self.fwd_path) {
10,947,903✔
1181
            None => None,
37,248✔
1182
            Some(value) => match Iter::get(&self.back_path) {
10,910,655✔
1183
                Some(last_value) if value.cmp_values(last_value) == Ordering::Greater => None,
10,910,649✔
1184
                None => None,
6✔
1185
                Some(_) => {
1186
                    Iter::step_forward(&mut self.fwd_path);
10,907,971✔
1187
                    self.remaining -= 1;
10,907,971✔
1188
                    Some(value)
10,907,971✔
1189
                }
1190
            },
1191
        }
1192
    }
10,947,903✔
1193

1194
    fn size_hint(&self) -> (usize, Option<usize>) {
8,130✔
1195
        // (0, Some(self.remaining))
1196
        (0, None)
8,130✔
1197
    }
8,130✔
1198
}
1199

1200
impl<'a, A: 'a + BTreeValue> DoubleEndedIterator for Iter<'a, A> {
1201
    fn next_back(&mut self) -> Option<Self::Item> {
251,944✔
1202
        match Iter::get(&self.back_path) {
251,944✔
1203
            None => None,
530✔
1204
            Some(value) => match Iter::get(&self.fwd_path) {
251,414✔
1205
                Some(last_value) if value.cmp_values(last_value) == Ordering::Less => None,
251,414✔
1206
                None => None,
×
1207
                Some(_) => {
1208
                    Iter::step_back(&mut self.back_path);
251,404✔
1209
                    self.remaining -= 1;
251,404✔
1210
                    Some(value)
251,404✔
1211
                }
1212
            },
1213
        }
1214
    }
251,944✔
1215
}
1216

1217
// Consuming iterator
1218

1219
enum ConsumingIterItem<A> {
1220
    Consider(Node<A>),
1221
    Yield(A),
1222
}
1223

1224
/// A consuming iterator over an ordered set.
1225
pub struct ConsumingIter<A> {
1226
    fwd_last: Option<A>,
1227
    fwd_stack: Vec<ConsumingIterItem<A>>,
1228
    back_last: Option<A>,
1229
    back_stack: Vec<ConsumingIterItem<A>>,
1230
    remaining: usize,
1231
}
1232

1233
impl<A: Clone> ConsumingIter<A> {
1234
    pub(crate) fn new(root: &Node<A>, total: usize) -> Self {
1,550✔
1235
        ConsumingIter {
1,550✔
1236
            fwd_last: None,
1,550✔
1237
            fwd_stack: vec![ConsumingIterItem::Consider(root.clone())],
1,550✔
1238
            back_last: None,
1,550✔
1239
            back_stack: vec![ConsumingIterItem::Consider(root.clone())],
1,550✔
1240
            remaining: total,
1241
        }
1242
    }
1,550✔
1243

1244
    fn push_node(stack: &mut Vec<ConsumingIterItem<A>>, maybe_node: Option<PoolRef<Node<A>>>) {
543,515✔
1245
        if let Some(node) = maybe_node {
543,515✔
1246
            stack.push(ConsumingIterItem::Consider(PoolRef::unwrap_or_clone(node)))
89,175✔
1247
        }
1248
    }
543,515✔
1249

1250
    fn push(stack: &mut Vec<ConsumingIterItem<A>>, mut node: Node<A>) {
90,725✔
1251
        for _n in 0..node.keys.len() {
543,515✔
1252
            ConsumingIter::push_node(stack, node.children.pop_back());
452,790✔
1253
            stack.push(ConsumingIterItem::Yield(node.keys.pop_back()));
452,790✔
1254
        }
1255
        ConsumingIter::push_node(stack, node.children.pop_back());
90,725✔
1256
    }
90,725✔
1257

1258
    fn push_fwd(&mut self, node: Node<A>) {
90,725✔
1259
        ConsumingIter::push(&mut self.fwd_stack, node)
90,725✔
1260
    }
90,725✔
1261

1262
    fn push_node_back(&mut self, maybe_node: Option<PoolRef<Node<A>>>) {
1263
        if let Some(node) = maybe_node {
1264
            self.back_stack
1265
                .push(ConsumingIterItem::Consider(PoolRef::unwrap_or_clone(node)))
1266
        }
1267
    }
1268

1269
    fn push_back(&mut self, mut node: Node<A>) {
1270
        for _i in 0..node.keys.len() {
1271
            self.push_node_back(node.children.pop_front());
1272
            self.back_stack
1273
                .push(ConsumingIterItem::Yield(node.keys.pop_front()));
1274
        }
1275
        self.push_node_back(node.children.pop_back());
1276
    }
1277
}
1278

1279
impl<A> Iterator for ConsumingIter<A>
1280
where
1281
    A: BTreeValue + Clone,
1282
{
1283
    type Item = A;
1284

1285
    fn next(&mut self) -> Option<Self::Item> {
454,340✔
1286
        loop {
545,065✔
1287
            match self.fwd_stack.pop() {
545,065✔
1288
                None => {
1289
                    self.remaining = 0;
1,550✔
1290
                    return None;
1,550✔
1291
                }
1292
                Some(ConsumingIterItem::Consider(node)) => self.push_fwd(node),
90,725✔
1293
                Some(ConsumingIterItem::Yield(value)) => {
452,790✔
1294
                    if let Some(ref last) = self.back_last {
452,790✔
1295
                        if value.cmp_values(last) != Ordering::Less {
×
1296
                            self.fwd_stack.clear();
×
1297
                            self.back_stack.clear();
×
1298
                            self.remaining = 0;
×
1299
                            return None;
×
1300
                        }
1301
                    }
1302
                    self.remaining -= 1;
452,790✔
1303
                    self.fwd_last = Some(value.clone());
452,790✔
1304
                    return Some(value);
452,790✔
1305
                }
452,790✔
1306
            }
1307
        }
545,065✔
1308
    }
454,340✔
1309

1310
    fn size_hint(&self) -> (usize, Option<usize>) {
1311
        (self.remaining, Some(self.remaining))
1312
    }
1313
}
1314

1315
impl<A> DoubleEndedIterator for ConsumingIter<A>
1316
where
1317
    A: BTreeValue + Clone,
1318
{
1319
    fn next_back(&mut self) -> Option<Self::Item> {
1320
        loop {
1321
            match self.back_stack.pop() {
1322
                None => {
1323
                    self.remaining = 0;
1324
                    return None;
1325
                }
1326
                Some(ConsumingIterItem::Consider(node)) => self.push_back(node),
1327
                Some(ConsumingIterItem::Yield(value)) => {
1328
                    if let Some(ref last) = self.fwd_last {
1329
                        if value.cmp_values(last) != Ordering::Greater {
1330
                            self.fwd_stack.clear();
1331
                            self.back_stack.clear();
1332
                            self.remaining = 0;
1333
                            return None;
1334
                        }
1335
                    }
1336
                    self.remaining -= 1;
1337
                    self.back_last = Some(value.clone());
1338
                    return Some(value);
1339
                }
1340
            }
1341
        }
1342
    }
1343
}
1344

1345
impl<A: BTreeValue + Clone> ExactSizeIterator for ConsumingIter<A> {}
1346

1347
// DiffIter
1348

1349
/// An iterator over the differences between two ordered sets.
1350
pub struct DiffIter<'a, 'b, A> {
1351
    old_stack: Vec<IterItem<'a, A>>,
1352
    new_stack: Vec<IterItem<'b, A>>,
1353
}
1354

1355
/// A description of a difference between two ordered sets.
1356
#[derive(PartialEq, Eq, Debug)]
1357
pub enum DiffItem<'a, 'b, A> {
1358
    /// This value has been added to the new set.
1359
    Add(&'b A),
1360
    /// This value has been changed between the two sets.
1361
    Update {
1362
        /// The old value.
1363
        old: &'a A,
1364
        /// The new value.
1365
        new: &'b A,
1366
    },
1367
    /// This value has been removed from the new set.
1368
    Remove(&'a A),
1369
}
1370

1371
enum IterItem<'a, A> {
1372
    Consider(&'a Node<A>),
1373
    Yield(&'a A),
1374
}
1375

1376
impl<'a, 'b, A: 'a + 'b> DiffIter<'a, 'b, A> {
1377
    pub(crate) fn new(old: &'a Node<A>, new: &'b Node<A>) -> Self {
29,258✔
1378
        DiffIter {
29,258✔
1379
            old_stack: if old.keys.is_empty() {
29,258✔
1380
                Vec::new()
521✔
1381
            } else {
1382
                vec![IterItem::Consider(old)]
28,737✔
1383
            },
1384
            new_stack: if new.keys.is_empty() {
29,258✔
1385
                Vec::new()
521✔
1386
            } else {
1387
                vec![IterItem::Consider(new)]
28,737✔
1388
            },
1389
        }
1390
    }
29,258✔
1391

1392
    fn push_node<'either>(
3,012,857✔
1393
        stack: &mut Vec<IterItem<'either, A>>,
1394
        maybe_node: &'either Option<PoolRef<Node<A>>>,
1395
    ) {
1396
        if let Some(node) = maybe_node {
3,012,857✔
1397
            stack.push(IterItem::Consider(node))
517,700✔
1398
        }
1399
    }
3,012,857✔
1400

1401
    fn push<'either>(stack: &mut Vec<IterItem<'either, A>>, node: &'either Node<A>) {
564,874✔
1402
        for n in 0..node.keys.len() {
3,012,857✔
1403
            let i = node.keys.len() - n;
2,447,983✔
1404
            Self::push_node(stack, &node.children[i]);
2,447,983✔
1405
            stack.push(IterItem::Yield(&node.keys[i - 1]));
2,447,983✔
1406
        }
1407
        Self::push_node(stack, &node.children[0]);
564,874✔
1408
    }
564,874✔
1409
}
1410

1411
impl<'a, 'b, A> Iterator for DiffIter<'a, 'b, A>
1412
where
1413
    A: 'a + 'b + BTreeValue + PartialEq,
1414
{
1415
    type Item = DiffItem<'a, 'b, A>;
1416

1417
    fn next(&mut self) -> Option<Self::Item> {
547,627✔
1418
        loop {
547,627✔
1419
            match (self.old_stack.pop(), self.new_stack.pop()) {
1,932,800✔
1420
                (None, None) => return None,
29,258✔
1421
                (None, Some(new)) => match new {
1,835✔
1422
                    IterItem::Consider(new) => Self::push(&mut self.new_stack, new),
169✔
1423
                    IterItem::Yield(new) => return Some(DiffItem::Add(new)),
1,666✔
1424
                },
1425
                (Some(old), None) => match old {
1,358✔
1426
                    IterItem::Consider(old) => Self::push(&mut self.old_stack, old),
155✔
1427
                    IterItem::Yield(old) => return Some(DiffItem::Remove(old)),
1,203✔
1428
                },
1429
                (Some(old), Some(new)) => match (old, new) {
1,900,349✔
1430
                    (IterItem::Consider(old), IterItem::Consider(new)) => {
185,506✔
1431
                        if !std::ptr::eq(old, new) {
185,506✔
1432
                            match old.keys[0].cmp_values(&new.keys[0]) {
180,356✔
1433
                                Ordering::Less => {
1434
                                    Self::push(&mut self.old_stack, old);
23,418✔
1435
                                    self.new_stack.push(IterItem::Consider(new));
23,418✔
1436
                                }
1437
                                Ordering::Greater => {
1438
                                    self.old_stack.push(IterItem::Consider(old));
7,280✔
1439
                                    Self::push(&mut self.new_stack, new);
7,280✔
1440
                                }
1441
                                Ordering::Equal => {
1442
                                    Self::push(&mut self.old_stack, old);
149,658✔
1443
                                    Self::push(&mut self.new_stack, new);
149,658✔
1444
                                }
1445
                            }
1446
                        }
1447
                    }
1448
                    (IterItem::Consider(old), IterItem::Yield(new)) => {
113,071✔
1449
                        Self::push(&mut self.old_stack, old);
113,071✔
1450
                        self.new_stack.push(IterItem::Yield(new));
113,071✔
1451
                    }
1452
                    (IterItem::Yield(old), IterItem::Consider(new)) => {
121,465✔
1453
                        self.old_stack.push(IterItem::Yield(old));
121,465✔
1454
                        Self::push(&mut self.new_stack, new);
121,465✔
1455
                    }
1456
                    (IterItem::Yield(old), IterItem::Yield(new)) => match old.cmp_values(new) {
1,480,307✔
1457
                        Ordering::Less => {
1458
                            self.new_stack.push(IterItem::Yield(new));
252,069✔
1459
                            return Some(DiffItem::Remove(old));
252,069✔
1460
                        }
1461
                        Ordering::Equal => {
1462
                            if old != new {
964,807✔
1463
                                return Some(DiffItem::Update { old, new });
×
1464
                            }
1465
                        }
1466
                        Ordering::Greater => {
1467
                            self.old_stack.push(IterItem::Yield(old));
263,431✔
1468
                            return Some(DiffItem::Add(new));
263,431✔
1469
                        }
1470
                    },
1471
                },
1472
            }
1473
        }
1474
    }
547,627✔
1475
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc