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/.
5 use std
::borrow
::Borrow
;
6 use std
::cmp
::Ordering
;
8 use std
::ops
::{Bound, RangeBounds}
;
10 use typenum
::{Add1, Unsigned}
;
12 use config
::OrdChunkSize
as NodeSize
;
13 use nodes
::sized_chunk
::Chunk
;
14 use util
::{clone_ref, Ref}
;
17 use self::InsertAction
::*;
19 const NODE_SIZE
: usize = NodeSize
::USIZE
;
20 const MEDIAN
: usize = (NODE_SIZE
+ 1) >> 1;
22 pub trait BTreeValue
: Clone
{
24 fn ptr_eq(&self, other
: &Self) -> bool
;
25 fn search_key
<BK
>(slice
: &[Self], key
: &BK
) -> Result
<usize, usize>
28 Self::Key
: Borrow
<BK
>;
29 fn search_value(slice
: &[Self], value
: &Self) -> Result
<usize, usize>;
30 fn cmp_keys
<BK
>(&self, other
: &BK
) -> Ordering
33 Self::Key
: Borrow
<BK
>;
34 fn cmp_values(&self, other
: &Self) -> Ordering
;
38 keys
: Chunk
<A
, NodeSize
>,
39 children
: Chunk
<Option
<Ref
<Node
<A
>>>, Add1
<NodeSize
>>,
46 Split(Node
<A
>, A
, Node
<A
>),
49 enum InsertAction
<A
> {
53 InsertSplit(Node
<A
>, A
, Node
<A
>),
64 PullUp(usize, usize, usize),
67 StealFromRight(usize),
72 impl<A
> Clone
for Node
<A
>
76 fn clone(&self) -> Self {
78 keys
: self.keys
.clone(),
79 children
: self.children
.clone(),
84 impl<A
> Default
for Node
<A
> {
85 fn default() -> Self {
88 children
: Chunk
::unit(None
),
98 fn has_room(&self) -> bool
{
99 self.keys
.len() < NODE_SIZE
103 fn too_small(&self) -> bool
{
104 self.keys
.len() < MEDIAN
108 fn is_leaf(&self) -> bool
{
109 self.children
[0].is_none()
113 pub fn new() -> Self {
118 pub fn unit(value
: A
) -> Self {
120 keys
: Chunk
::unit(value
),
121 children
: Chunk
::pair(None
, None
),
126 pub fn from_split(left
: Node
<A
>, median
: A
, right
: Node
<A
>) -> Self {
128 keys
: Chunk
::unit(median
),
129 children
: Chunk
::pair(Some(Ref
::from(left
)), Some(Ref
::from(right
))),
133 pub fn min(&self) -> Option
<&A
> {
134 match self.children
.first().unwrap() {
135 None
=> self.keys
.first(),
136 Some(ref child
) => child
.min(),
140 pub fn max(&self) -> Option
<&A
> {
141 match self.children
.last().unwrap() {
142 None
=> self.keys
.last(),
143 Some(ref child
) => child
.max(),
148 impl<A
: BTreeValue
> Node
<A
> {
149 fn child_contains
<BK
>(&self, index
: usize, key
: &BK
) -> bool
154 if let Some(Some(ref child
)) = self.children
.get(index
) {
155 child
.lookup(key
).is_some()
161 pub fn lookup
<BK
>(&self, key
: &BK
) -> Option
<&A
>
166 if self.keys
.is_empty() {
169 // Perform a binary search, resulting in either a match or
170 // the index of the first higher key, meaning we search the
171 // child to the left of it.
172 match A
::search_key(&self.keys
, key
) {
173 Ok(index
) => Some(&self.keys
[index
]),
174 Err(index
) => match self.children
[index
] {
176 Some(ref node
) => node
.lookup(key
),
181 pub fn lookup_mut
<BK
>(&mut self, key
: &BK
) -> Option
<&mut A
>
186 if self.keys
.is_empty() {
189 // Perform a binary search, resulting in either a match or
190 // the index of the first higher key, meaning we search the
191 // child to the left of it.
192 match A
::search_key(&self.keys
, key
) {
193 Ok(index
) => Some(&mut self.keys
[index
]),
194 Err(index
) => match self.children
[index
] {
196 Some(ref mut child_ref
) => {
197 let child
= Ref
::make_mut(child_ref
);
198 child
.lookup_mut(key
)
204 pub fn path_first
<'a
, BK
>(
206 mut path
: Vec
<(&'a Node
<A
>, usize)>,
207 ) -> Vec
<(&'a Node
<A
>, usize)>
213 if self.keys
.is_empty() {
216 match self.children
[0] {
218 path
.push((self, 0));
222 path
.push((self, 0));
223 node
.path_first(path
)
228 pub fn path_last
<'a
, BK
>(
230 mut path
: Vec
<(&'a Node
<A
>, usize)>,
231 ) -> Vec
<(&'a Node
<A
>, usize)>
237 if self.keys
.is_empty() {
240 let end
= self.children
.len() - 1;
241 match self.children
[end
] {
243 path
.push((self, end
- 1));
247 path
.push((self, end
));
253 pub fn path_next
<'a
, BK
>(
256 mut path
: Vec
<(&'a Node
<A
>, usize)>,
257 ) -> Vec
<(&'a Node
<A
>, usize)>
263 if self.keys
.is_empty() {
266 match A
::search_key(&self.keys
, key
) {
268 path
.push((self, index
));
271 Err(index
) => match self.children
[index
] {
272 None
=> match self.keys
.get(index
) {
274 path
.push((self, index
));
280 path
.push((self, index
));
281 node
.path_next(key
, path
)
287 pub fn path_prev
<'a
, BK
>(
290 mut path
: Vec
<(&'a Node
<A
>, usize)>,
291 ) -> Vec
<(&'a Node
<A
>, usize)>
297 if self.keys
.is_empty() {
300 match A
::search_key(&self.keys
, key
) {
302 path
.push((self, index
));
305 Err(index
) => match self.children
[index
] {
306 None
if index
== 0 => Vec
::new(),
307 None
=> match self.keys
.get(index
- 1) {
309 path
.push((self, index
));
315 path
.push((self, index
));
316 node
.path_prev(key
, path
)
325 ins_left
: Option
<Node
<A
>>,
326 ins_right
: Option
<Node
<A
>>,
328 let left_child
= ins_left
.map(Ref
::from
);
329 let right_child
= ins_right
.map(Ref
::from
);
330 let index
= A
::search_value(&self.keys
, &value
).unwrap_err();
332 let mut left_children
;
334 let mut right_children
;
337 self.children
[index
] = left_child
;
339 left_keys
= Chunk
::from_front(&mut self.keys
, index
);
340 left_keys
.push_back(value
);
341 left_keys
.drain_from_front(&mut self.keys
, MEDIAN
- index
- 1);
343 left_children
= Chunk
::from_front(&mut self.children
, index
+ 1);
344 left_children
.push_back(right_child
);
345 left_children
.drain_from_front(&mut self.children
, MEDIAN
- index
- 1);
347 median
= self.keys
.pop_front();
349 right_keys
= Chunk
::drain_from(&mut self.keys
);
350 right_children
= Chunk
::drain_from(&mut self.children
);
351 } else if index
> MEDIAN
{
352 self.children
[index
] = left_child
;
354 left_keys
= Chunk
::from_front(&mut self.keys
, MEDIAN
);
355 left_children
= Chunk
::from_front(&mut self.children
, MEDIAN
+ 1);
357 median
= self.keys
.pop_front();
359 right_keys
= Chunk
::from_front(&mut self.keys
, index
- MEDIAN
- 1);
360 right_keys
.push_back(value
);
361 right_keys
.append(&mut self.keys
);
363 right_children
= Chunk
::from_front(&mut self.children
, index
- MEDIAN
);
364 right_children
.push_back(right_child
);
365 right_children
.append(&mut self.children
);
367 left_keys
= Chunk
::from_front(&mut self.keys
, MEDIAN
);
368 left_children
= Chunk
::from_front(&mut self.children
, MEDIAN
);
369 left_children
.push_back(left_child
);
373 right_keys
= Chunk
::drain_from(&mut self.keys
);
374 right_children
= Chunk
::drain_from(&mut self.children
);
375 right_children
[0] = right_child
;
378 debug_assert
!(left_keys
.len() == MEDIAN
);
379 debug_assert
!(left_children
.len() == MEDIAN
+ 1);
380 debug_assert
!(right_keys
.len() == MEDIAN
);
381 debug_assert
!(right_children
.len() == MEDIAN
+ 1);
386 children
: left_children
,
391 children
: right_children
,
396 fn merge(middle
: A
, left
: Node
<A
>, mut right
: Node
<A
>) -> Node
<A
> {
397 let mut keys
= left
.keys
;
398 keys
.push_back(middle
);
399 keys
.append(&mut right
.keys
);
400 let mut children
= left
.children
;
401 children
.append(&mut right
.children
);
402 Node { keys, children }
405 fn pop_min(&mut self) -> (A
, Option
<Ref
<Node
<A
>>>) {
406 let value
= self.keys
.pop_front();
407 let child
= self.children
.pop_front();
411 fn pop_max(&mut self) -> (A
, Option
<Ref
<Node
<A
>>>) {
412 let value
= self.keys
.pop_back();
413 let child
= self.children
.pop_back();
417 fn push_min(&mut self, child
: Option
<Ref
<Node
<A
>>>, value
: A
) {
418 self.keys
.push_front(value
);
419 self.children
.push_front(child
);
422 fn push_max(&mut self, child
: Option
<Ref
<Node
<A
>>>, value
: A
) {
423 self.keys
.push_back(value
);
424 self.children
.push_back(child
);
427 pub fn insert(&mut self, value
: A
) -> Insert
<A
> {
428 if self.keys
.is_empty() {
429 self.keys
.push_back(value
);
430 self.children
.push_back(None
);
431 return Insert
::Added
;
433 let (median
, left
, right
) = match A
::search_value(&self.keys
, &value
) {
434 // Key exists in node
436 return Insert
::Replaced(mem
::replace(&mut self.keys
[index
], value
));
438 // Key is adjacent to some key in node
440 let mut has_room
= self.has_room();
441 let action
= match self.children
[index
] {
442 // No child at location, this is the target node.
444 // Child at location, pass it on.
445 Some(ref mut child_ref
) => {
446 let child
= Ref
::make_mut(child_ref
);
447 match child
.insert(value
.clone()) {
448 Insert
::Added
=> AddedAction
,
449 Insert
::Replaced(value
) => ReplacedAction(value
),
450 Insert
::Update(_
) => unreachable
!(),
451 Insert
::Split(left
, median
, right
) => InsertSplit(left
, median
, right
),
456 ReplacedAction(value
) => return Insert
::Replaced(value
),
458 return Insert
::Added
;
462 self.keys
.insert(index
, value
);
463 self.children
.insert(index
+ 1, None
);
464 return Insert
::Added
;
469 InsertSplit(left
, median
, right
) => {
471 self.children
[index
] = Some(Ref
::from(left
));
472 self.keys
.insert(index
, median
);
473 self.children
.insert(index
+ 1, Some(Ref
::from(right
)));
474 return Insert
::Added
;
476 (median
, Some(left
), Some(right
))
482 self.split(median
, left
, right
)
485 pub fn remove
<BK
>(&mut self, key
: &BK
) -> Remove
<A
>
490 let index
= A
::search_key(&self.keys
, key
);
491 self.remove_index(index
, key
)
494 fn remove_index
<BK
>(&mut self, index
: Result
<usize, usize>, key
: &BK
) -> Remove
<A
>
499 let action
= match index
{
500 // Key exists in node, remove it.
502 match (&self.children
[index
], &self.children
[index
+ 1]) {
503 // If we're a leaf, just delete the entry.
504 (&None
, &None
) => RemoveAction
::DeleteAt(index
),
505 // If the left hand child has capacity, pull the predecessor up.
506 (&Some(ref left
), _
) if !left
.too_small() => {
508 RemoveAction
::PullUp(left
.keys
.len() - 1, index
, index
)
510 RemoveAction
::StealFromLeft(index
+ 1)
513 // If the right hand child has capacity, pull the successor up.
514 (_
, &Some(ref right
)) if !right
.too_small() => {
516 RemoveAction
::PullUp(0, index
, index
+ 1)
518 RemoveAction
::StealFromRight(index
)
521 // If neither child has capacity, we'll have to merge them.
522 (&Some(_
), &Some(_
)) => RemoveAction
::Merge(index
),
523 // If one child exists and the other doesn't, we're in a bad state.
527 // Key is adjacent to some key in node
528 Err(index
) => match self.children
[index
] {
529 // No child at location means key isn't in map.
530 None
=> return Remove
::NoChange
,
531 // Child at location, but it's at minimum capacity.
532 Some(ref child
) if child
.too_small() => {
533 let left
= if index
> 0 {
534 self.children
.get(index
- 1)
537 }; // index is usize and can't be negative, best make sure it never is.
538 match (left
, self.children
.get(index
+ 1)) {
539 // If it has a left sibling with capacity, steal a key from it.
540 (Some(&Some(ref old_left
)), _
) if !old_left
.too_small() => {
541 RemoveAction
::StealFromLeft(index
)
543 // If it has a right sibling with capacity, same as above.
544 (_
, Some(&Some(ref old_right
))) if !old_right
.too_small() => {
545 RemoveAction
::StealFromRight(index
)
547 // If it has neither, we'll have to merge it with a sibling.
548 // If we have a right sibling, we'll merge with that.
549 (_
, Some(&Some(_
))) => RemoveAction
::MergeFirst(index
),
550 // If we have a left sibling, we'll merge with that.
551 (Some(&Some(_
)), _
) => RemoveAction
::MergeFirst(index
- 1),
552 // If none of the above, we're in a bad state.
556 // Child at location, and it's big enough, we can recurse down.
557 Some(_
) => RemoveAction
::ContinueDown(index
),
561 RemoveAction
::DeleteAt(index
) => {
562 let pair
= self.keys
.remove(index
);
563 self.children
.remove(index
);
564 Remove
::Removed(pair
)
566 RemoveAction
::PullUp(target_index
, pull_to
, child_index
) => {
567 let mut children
= &mut self.children
;
568 let mut update
= None
;
570 if let Some(&mut Some(ref mut child_ref
)) = children
.get_mut(child_index
) {
571 let child
= Ref
::make_mut(child_ref
);
572 match child
.remove_index(Ok(target_index
), key
) {
573 Remove
::NoChange
=> unreachable
!(),
574 Remove
::Removed(pulled_value
) => {
575 value
= self.keys
.set(pull_to
, pulled_value
);
577 Remove
::Update(pulled_value
, new_child
) => {
578 value
= self.keys
.set(pull_to
, pulled_value
);
579 update
= Some(new_child
);
585 if let Some(new_child
) = update
{
586 children
[child_index
] = Some(Ref
::from(new_child
));
588 Remove
::Removed(value
)
590 RemoveAction
::Merge(index
) => {
591 let left
= self.children
.remove(index
).unwrap();
592 let right
= mem
::replace(&mut self.children
[index
], None
).unwrap();
593 let value
= self.keys
.remove(index
);
594 let mut merged_child
= Node
::merge(value
, clone_ref(left
), clone_ref(right
));
595 let (removed
, new_child
) = match merged_child
.remove(key
) {
596 Remove
::NoChange
=> unreachable
!(),
597 Remove
::Removed(removed
) => (removed
, merged_child
),
598 Remove
::Update(removed
, updated_child
) => (removed
, updated_child
),
600 if self.keys
.is_empty() {
601 // If we've depleted the root node, the merged child becomes the root.
602 Remove
::Update(removed
, new_child
)
604 self.children
[index
] = Some(Ref
::from(new_child
));
605 Remove
::Removed(removed
)
608 RemoveAction
::StealFromLeft(index
) => {
609 let mut update
= None
;
612 let mut children
= self.children
.as_mut_slice()[index
- 1..=index
]
615 if let Some(ref mut o
) = *n
{
621 let mut left
= Ref
::make_mut(children
.next().unwrap());
622 let mut child
= Ref
::make_mut(children
.next().unwrap());
623 // Prepare the rebalanced node.
625 left
.children
.last().unwrap().clone(),
626 self.keys
[index
- 1].clone(),
628 match child
.remove(key
) {
629 Remove
::NoChange
=> {
630 // Key wasn't there, we need to revert the steal.
632 return Remove
::NoChange
;
634 Remove
::Removed(value
) => {
635 // If we did remove something, we complete the rebalancing.
636 let (left_value
, _
) = left
.pop_max();
637 self.keys
[index
- 1] = left_value
;
640 Remove
::Update(value
, new_child
) => {
641 // If we did remove something, we complete the rebalancing.
642 let (left_value
, _
) = left
.pop_max();
643 self.keys
[index
- 1] = left_value
;
644 update
= Some(new_child
);
649 if let Some(new_child
) = update
{
650 self.children
[index
] = Some(Ref
::from(new_child
));
652 Remove
::Removed(out_value
)
654 RemoveAction
::StealFromRight(index
) => {
655 let mut update
= None
;
658 let mut children
= self.children
.as_mut_slice()[index
..index
+ 2]
661 if let Some(ref mut o
) = *n
{
667 let mut child
= Ref
::make_mut(children
.next().unwrap());
668 let mut right
= Ref
::make_mut(children
.next().unwrap());
669 // Prepare the rebalanced node.
670 child
.push_max(right
.children
[0].clone(), self.keys
[index
].clone());
671 match child
.remove(key
) {
672 Remove
::NoChange
=> {
673 // Key wasn't there, we need to revert the steal.
675 return Remove
::NoChange
;
677 Remove
::Removed(value
) => {
678 // If we did remove something, we complete the rebalancing.
679 let (right_value
, _
) = right
.pop_min();
680 self.keys
[index
] = right_value
;
683 Remove
::Update(value
, new_child
) => {
684 // If we did remove something, we complete the rebalancing.
685 let (right_value
, _
) = right
.pop_min();
686 self.keys
[index
] = right_value
;
687 update
= Some(new_child
);
692 if let Some(new_child
) = update
{
693 self.children
[index
] = Some(Ref
::from(new_child
));
695 Remove
::Removed(out_value
)
697 RemoveAction
::MergeFirst(index
) => {
698 if self.keys
[index
].cmp_keys(key
) != Ordering
::Equal
699 && !self.child_contains(index
, key
)
700 && !self.child_contains(index
+ 1, key
)
702 return Remove
::NoChange
;
704 let left
= self.children
.remove(index
).unwrap();
705 let right
= mem
::replace(&mut self.children
[index
], None
).unwrap();
706 let middle
= self.keys
.remove(index
);
707 let mut merged
= Node
::merge(middle
, clone_ref(left
), clone_ref(right
));
710 match merged
.remove(key
) {
711 Remove
::NoChange
=> {
712 panic
!("nodes::btree::Node::remove: caught an absent key too late while merging");
714 Remove
::Removed(value
) => {
715 if self.keys
.is_empty() {
716 return Remove
::Update(value
, merged
);
721 Remove
::Update(value
, new_child
) => {
722 if self.keys
.is_empty() {
723 return Remove
::Update(value
, new_child
);
729 self.children
[index
] = Some(Ref
::from(update
));
730 Remove
::Removed(out_value
)
732 RemoveAction
::ContinueDown(index
) => {
733 let mut update
= None
;
735 if let Some(&mut Some(ref mut child_ref
)) = self.children
.get_mut(index
) {
736 let child
= Ref
::make_mut(child_ref
);
737 match child
.remove(key
) {
738 Remove
::NoChange
=> return Remove
::NoChange
,
739 Remove
::Removed(value
) => {
742 Remove
::Update(value
, new_child
) => {
743 update
= Some(new_child
);
750 if let Some(new_child
) = update
{
751 self.children
[index
] = Some(Ref
::from(new_child
));
753 Remove
::Removed(out_value
)
761 pub struct Iter
<'a
, A
: 'a
> {
762 fwd_path
: Vec
<(&'a Node
<A
>, usize)>,
763 back_path
: Vec
<(&'a Node
<A
>, usize)>,
764 pub(crate) remaining
: usize,
767 impl<'a
, A
: 'a
+ BTreeValue
> Iter
<'a
, A
> {
768 pub fn new
<R
, BK
>(root
: &'a Node
<A
>, size
: usize, range
: R
) -> Self
774 let fwd_path
= match range
.start_bound() {
775 Bound
::Included(key
) => root
.path_next(key
, Vec
::new()),
776 Bound
::Excluded(key
) => {
777 let mut path
= root
.path_next(key
, Vec
::new());
778 if let Some(value
) = Self::get(&path
) {
779 if value
.cmp_keys(key
) == Ordering
::Equal
{
780 Self::step_forward(&mut path
);
785 Bound
::Unbounded
=> root
.path_first(Vec
::new()),
787 let back_path
= match range
.end_bound() {
788 Bound
::Included(key
) => root
.path_prev(key
, Vec
::new()),
789 Bound
::Excluded(key
) => {
790 let mut path
= root
.path_prev(key
, Vec
::new());
791 if let Some(value
) = Self::get(&path
) {
792 if value
.cmp_keys(key
) == Ordering
::Equal
{
793 Self::step_back(&mut path
);
798 Bound
::Unbounded
=> root
.path_last(Vec
::new()),
807 fn get(path
: &[(&'a Node
<A
>, usize)]) -> Option
<&'a A
> {
809 Some((node
, index
)) => Some(&node
.keys
[*index
]),
814 fn step_forward(path
: &mut Vec
<(&'a Node
<A
>, usize)>) -> Option
<&'a A
> {
816 Some((node
, index
)) => {
817 let index
= index
+ 1;
818 match node
.children
[index
] {
819 // Child between current and next key -> step down
821 path
.push((node
, index
));
822 path
.push((child
, 0));
823 let mut node
= child
;
824 while let Some(ref left_child
) = node
.children
[0] {
825 path
.push((left_child
, 0));
830 None
=> match node
.keys
.get(index
) {
833 path
.push((node
, index
));
836 // No more keys -> exhausted level, step up and yield
842 Some((node
, index
)) => {
843 if let value @
Some(_
) = node
.keys
.get(index
) {
844 path
.push((node
, index
));
857 fn step_back(path
: &mut Vec
<(&'a Node
<A
>, usize)>) -> Option
<&'a A
> {
859 Some((node
, index
)) => match node
.children
[index
] {
861 path
.push((node
, index
));
862 let mut end
= child
.keys
.len() - 1;
863 path
.push((child
, end
));
864 let mut node
= child
;
865 while let Some(ref right_child
) = node
.children
[end
+ 1] {
866 end
= right_child
.keys
.len() - 1;
867 path
.push((right_child
, end
));
870 Some(&node
.keys
[end
])
879 Some((node
, index
)) => {
881 let index
= index
- 1;
882 path
.push((node
, index
));
883 return Some(&node
.keys
[index
]);
889 let index
= index
- 1;
890 path
.push((node
, index
));
891 Some(&node
.keys
[index
])
900 impl<'a
, A
: 'a
+ BTreeValue
> Iterator
for Iter
<'a
, A
> {
903 fn next(&mut self) -> Option
<Self::Item
> {
904 match Iter
::get(&self.fwd_path
) {
906 Some(value
) => match Iter
::get(&self.back_path
) {
907 Some(last_value
) if value
.cmp_values(last_value
) == Ordering
::Greater
=> None
,
910 Iter
::step_forward(&mut self.fwd_path
);
918 fn size_hint(&self) -> (usize, Option
<usize>) {
919 // (0, Some(self.remaining))
924 impl<'a
, A
: 'a
+ BTreeValue
> DoubleEndedIterator
for Iter
<'a
, A
> {
925 fn next_back(&mut self) -> Option
<Self::Item
> {
926 match Iter
::get(&self.back_path
) {
928 Some(value
) => match Iter
::get(&self.fwd_path
) {
929 Some(last_value
) if value
.cmp_values(last_value
) == Ordering
::Less
=> None
,
932 Iter
::step_back(&mut self.back_path
);
941 // Consuming iterator
943 enum ConsumingIterItem
<A
> {
948 pub struct ConsumingIter
<A
> {
950 fwd_stack
: Vec
<ConsumingIterItem
<A
>>,
951 back_last
: Option
<A
>,
952 back_stack
: Vec
<ConsumingIterItem
<A
>>,
956 impl<A
: Clone
> ConsumingIter
<A
> {
957 pub fn new(root
: &Node
<A
>, total
: usize) -> Self {
960 fwd_stack
: vec
![ConsumingIterItem
::Consider(root
.clone())],
962 back_stack
: vec
![ConsumingIterItem
::Consider(root
.clone())],
967 fn push_node(stack
: &mut Vec
<ConsumingIterItem
<A
>>, maybe_node
: Option
<Ref
<Node
<A
>>>) {
968 if let Some(node
) = maybe_node
{
969 stack
.push(ConsumingIterItem
::Consider(clone_ref(node
)))
973 fn push(stack
: &mut Vec
<ConsumingIterItem
<A
>>, mut node
: Node
<A
>) {
974 for _n
in 0..node
.keys
.len() {
975 ConsumingIter
::push_node(stack
, node
.children
.pop_back());
976 stack
.push(ConsumingIterItem
::Yield(node
.keys
.pop_back()));
978 ConsumingIter
::push_node(stack
, node
.children
.pop_back());
981 fn push_fwd(&mut self, node
: Node
<A
>) {
982 ConsumingIter
::push(&mut self.fwd_stack
, node
)
985 fn push_node_back(&mut self, maybe_node
: Option
<Ref
<Node
<A
>>>) {
986 if let Some(node
) = maybe_node
{
988 .push(ConsumingIterItem
::Consider(clone_ref(node
)))
992 fn push_back(&mut self, mut node
: Node
<A
>) {
993 for _i
in 0..node
.keys
.len() {
994 self.push_node_back(node
.children
.pop_front());
996 .push(ConsumingIterItem
::Yield(node
.keys
.pop_front()));
998 self.push_node_back(node
.children
.pop_back());
1002 impl<A
> Iterator
for ConsumingIter
<A
>
1008 fn next(&mut self) -> Option
<Self::Item
> {
1010 match self.fwd_stack
.pop() {
1015 Some(ConsumingIterItem
::Consider(node
)) => self.push_fwd(node
),
1016 Some(ConsumingIterItem
::Yield(value
)) => {
1017 if let Some(ref last
) = self.back_last
{
1018 if value
.cmp_values(last
) != Ordering
::Less
{
1019 self.fwd_stack
.clear();
1020 self.back_stack
.clear();
1025 self.remaining
-= 1;
1026 self.fwd_last
= Some(value
.clone());
1033 fn size_hint(&self) -> (usize, Option
<usize>) {
1034 (self.remaining
, Some(self.remaining
))
1038 impl<A
> DoubleEndedIterator
for ConsumingIter
<A
>
1042 fn next_back(&mut self) -> Option
<Self::Item
> {
1044 match self.back_stack
.pop() {
1049 Some(ConsumingIterItem
::Consider(node
)) => self.push_back(node
),
1050 Some(ConsumingIterItem
::Yield(value
)) => {
1051 if let Some(ref last
) = self.fwd_last
{
1052 if value
.cmp_values(last
) != Ordering
::Greater
{
1053 self.fwd_stack
.clear();
1054 self.back_stack
.clear();
1059 self.remaining
-= 1;
1060 self.back_last
= Some(value
.clone());
1068 impl<A
: BTreeValue
> ExactSizeIterator
for ConsumingIter
<A
> {}
1072 pub struct DiffIter
<'a
, A
: 'a
> {
1073 old_stack
: Vec
<IterItem
<'a
, A
>>,
1074 new_stack
: Vec
<IterItem
<'a
, A
>>,
1077 #[derive(PartialEq, Eq)]
1078 pub enum DiffItem
<'a
, A
: 'a
> {
1080 Update { old: &'a A, new: &'a A }
,
1084 enum IterItem
<'a
, A
: 'a
> {
1085 Consider(&'a Node
<A
>),
1089 impl<'a
, A
: 'a
> DiffIter
<'a
, A
> {
1090 pub fn new(old
: &'a Node
<A
>, new
: &'a Node
<A
>) -> Self {
1092 old_stack
: if old
.keys
.is_empty() {
1095 vec
![IterItem
::Consider(old
)]
1097 new_stack
: if new
.keys
.is_empty() {
1100 vec
![IterItem
::Consider(new
)]
1105 fn push_node(stack
: &mut Vec
<IterItem
<'a
, A
>>, maybe_node
: &'a Option
<Ref
<Node
<A
>>>) {
1106 if let Some(ref node
) = *maybe_node
{
1107 stack
.push(IterItem
::Consider(&node
))
1111 fn push(stack
: &mut Vec
<IterItem
<'a
, A
>>, node
: &'a Node
<A
>) {
1112 for n
in 0..node
.keys
.len() {
1113 let i
= node
.keys
.len() - n
;
1114 Self::push_node(stack
, &node
.children
[i
]);
1115 stack
.push(IterItem
::Yield(&node
.keys
[i
- 1]));
1117 Self::push_node(stack
, &node
.children
[0]);
1121 impl<'a
, A
> Iterator
for DiffIter
<'a
, A
>
1123 A
: 'a
+ BTreeValue
+ PartialEq
,
1125 type Item
= DiffItem
<'a
, A
>;
1127 fn next(&mut self) -> Option
<Self::Item
> {
1129 match (self.old_stack
.pop(), self.new_stack
.pop()) {
1130 (None
, None
) => return None
,
1131 (None
, Some(new
)) => match new
{
1132 IterItem
::Consider(new
) => Self::push(&mut self.new_stack
, &new
),
1133 IterItem
::Yield(new
) => return Some(DiffItem
::Add(new
)),
1135 (Some(old
), None
) => match old
{
1136 IterItem
::Consider(old
) => Self::push(&mut self.old_stack
, &old
),
1137 IterItem
::Yield(old
) => return Some(DiffItem
::Remove(old
)),
1139 (Some(old
), Some(new
)) => match (old
, new
) {
1140 (IterItem
::Consider(old
), IterItem
::Consider(new
)) => {
1141 match old
.keys
[0].cmp_values(&new
.keys
[0]) {
1143 Self::push(&mut self.old_stack
, &old
);
1144 self.new_stack
.push(IterItem
::Consider(new
));
1146 Ordering
::Greater
=> {
1147 self.old_stack
.push(IterItem
::Consider(old
));
1148 Self::push(&mut self.new_stack
, &new
);
1150 Ordering
::Equal
=> {
1151 Self::push(&mut self.old_stack
, &old
);
1152 Self::push(&mut self.new_stack
, &new
);
1156 (IterItem
::Consider(old
), IterItem
::Yield(new
)) => {
1157 Self::push(&mut self.old_stack
, &old
);
1158 self.new_stack
.push(IterItem
::Yield(new
));
1160 (IterItem
::Yield(old
), IterItem
::Consider(new
)) => {
1161 self.old_stack
.push(IterItem
::Yield(old
));
1162 Self::push(&mut self.new_stack
, &new
);
1164 (IterItem
::Yield(old
), IterItem
::Yield(new
)) => match old
.cmp_values(&new
) {
1166 self.new_stack
.push(IterItem
::Yield(new
));
1167 return Some(DiffItem
::Remove(old
));
1169 Ordering
::Equal
=> {
1171 return Some(DiffItem
::Update { old, new }
);
1174 Ordering
::Greater
=> {
1175 self.old_stack
.push(IterItem
::Yield(old
));
1176 return Some(DiffItem
::Add(new
));