• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2016 Amanieu d'Antras
2 // Copyright 2020 Amari Robinson
3 //
4 // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
5 // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
6 // http://opensource.org/licenses/MIT>, at your option. This file may not be
7 // copied, modified, or distributed except according to those terms.
8 
9 //! Intrusive red-black tree.
10 
11 use core::borrow::Borrow;
12 use core::cell::Cell;
13 use core::cmp::Ordering;
14 use core::fmt;
15 use core::mem;
16 use core::ptr::NonNull;
17 use core::sync::atomic::{self, AtomicUsize};
18 
19 use crate::Bound::{self, Excluded, Included, Unbounded};
20 
21 use crate::link_ops::{self, DefaultLinkOps};
22 use crate::linked_list::LinkedListOps;
23 use crate::pointer_ops::PointerOps;
24 use crate::singly_linked_list::SinglyLinkedListOps;
25 use crate::unchecked_option::UncheckedOptionExt;
26 use crate::xor_linked_list::XorLinkedListOps;
27 use crate::Adapter;
28 use crate::KeyAdapter;
29 
30 // =============================================================================
31 // RBTreeOps
32 // =============================================================================
33 
34 /// The color of a red-black tree node.
35 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
36 #[allow(missing_docs)]
37 pub enum Color {
38     Red,
39     Black,
40 }
41 
42 /// Link operations for `RBTree`.
43 pub unsafe trait RBTreeOps: link_ops::LinkOps {
44     /// Returns the left child of `ptr`.
45     ///
46     /// # Safety
47     /// An implementation of `left` must not panic.
left(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>48     unsafe fn left(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>;
49 
50     /// Returns the right child of `ptr`.
51     ///
52     /// # Safety
53     /// An implementation of `right` must not panic.
right(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>54     unsafe fn right(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>;
55 
56     /// Returns the parent of `ptr`.
57     ///
58     /// # Safety
59     /// An implementation of `parent` must not panic.
parent(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>60     unsafe fn parent(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>;
61 
62     /// Returns the color of `ptr`.
63     ///
64     /// # Safety
65     /// An implementation of `color` must not panic.
color(&self, ptr: Self::LinkPtr) -> Color66     unsafe fn color(&self, ptr: Self::LinkPtr) -> Color;
67 
68     /// Sets the left child of `ptr`.
69     ///
70     /// # Safety
71     /// An implementation of `set_left` must not panic.
set_left(&mut self, ptr: Self::LinkPtr, left: Option<Self::LinkPtr>)72     unsafe fn set_left(&mut self, ptr: Self::LinkPtr, left: Option<Self::LinkPtr>);
73 
74     /// Sets the right child of `ptr`.
75     ///
76     /// # Safety
77     /// An implementation of `set_right` must not panic.
set_right(&mut self, ptr: Self::LinkPtr, right: Option<Self::LinkPtr>)78     unsafe fn set_right(&mut self, ptr: Self::LinkPtr, right: Option<Self::LinkPtr>);
79 
80     /// Sets the parent of `ptr`.
81     ///
82     /// # Safety
83     /// An implementation of `set_parent` must not panic.
set_parent(&mut self, ptr: Self::LinkPtr, parent: Option<Self::LinkPtr>)84     unsafe fn set_parent(&mut self, ptr: Self::LinkPtr, parent: Option<Self::LinkPtr>);
85 
86     /// Sets the color of `ptr`.
87     ///
88     /// # Safety
89     /// An implementation of `set_color` must not panic.
set_color(&mut self, ptr: Self::LinkPtr, color: Color)90     unsafe fn set_color(&mut self, ptr: Self::LinkPtr, color: Color);
91 }
92 
93 // =============================================================================
94 // Link
95 // =============================================================================
96 
97 /// Intrusive link that allows an object to be inserted into a
98 /// `RBTree`.
99 #[repr(align(2))]
100 pub struct Link {
101     left: Cell<Option<NonNull<Link>>>,
102     right: Cell<Option<NonNull<Link>>>,
103     parent_color: Cell<usize>,
104 }
105 
106 // Use a special value to indicate an unlinked node. This value represents a
107 // red root node, which is impossible in a valid red-black tree.
108 const UNLINKED_MARKER: usize = 0;
109 
110 impl Link {
111     /// Creates a new `Link`.
112     #[inline]
new() -> Link113     pub const fn new() -> Link {
114         Link {
115             left: Cell::new(None),
116             right: Cell::new(None),
117             parent_color: Cell::new(UNLINKED_MARKER),
118         }
119     }
120 
121     /// Checks whether the `Link` is linked into a `RBTree`.
122     #[inline]
is_linked(&self) -> bool123     pub fn is_linked(&self) -> bool {
124         self.parent_color.get() != UNLINKED_MARKER
125     }
126 
127     /// Forcibly unlinks an object from a `RBTree`.
128     ///
129     /// # Safety
130     ///
131     /// It is undefined behavior to call this function while still linked into a
132     /// `RBTree`. The only situation where this function is useful is
133     /// after calling `fast_clear` on a `RBTree`, since this clears
134     /// the collection without marking the nodes as unlinked.
135     #[inline]
force_unlink(&self)136     pub unsafe fn force_unlink(&self) {
137         self.parent_color.set(UNLINKED_MARKER);
138     }
139 }
140 
141 impl DefaultLinkOps for Link {
142     type Ops = LinkOps;
143 
144     const NEW: Self::Ops = LinkOps;
145 }
146 
147 // An object containing a link can be sent to another thread if it is unlinked.
148 unsafe impl Send for Link {}
149 
150 // Provide an implementation of Clone which simply initializes the new link as
151 // unlinked. This allows structs containing a link to derive Clone.
152 impl Clone for Link {
153     #[inline]
clone(&self) -> Link154     fn clone(&self) -> Link {
155         Link::new()
156     }
157 }
158 
159 // Same as above
160 impl Default for Link {
161     #[inline]
default() -> Link162     fn default() -> Link {
163         Link::new()
164     }
165 }
166 
167 // Provide an implementation of Debug so that structs containing a link can
168 // still derive Debug.
169 impl fmt::Debug for Link {
170     #[inline]
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result171     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172         // There isn't anything sensible to print here except whether the link
173         // is currently in a tree.
174         if self.is_linked() {
175             write!(f, "linked")
176         } else {
177             write!(f, "unlinked")
178         }
179     }
180 }
181 
182 // =============================================================================
183 // LinkOps
184 // =============================================================================
185 
186 /// Default `LinkOps` implementation for `RBTree`.
187 #[derive(Clone, Copy, Default)]
188 pub struct LinkOps;
189 
190 impl LinkOps {
191     #[inline]
set_parent_color( self, ptr: <Self as link_ops::LinkOps>::LinkPtr, parent: Option<<Self as link_ops::LinkOps>::LinkPtr>, color: Color, )192     unsafe fn set_parent_color(
193         self,
194         ptr: <Self as link_ops::LinkOps>::LinkPtr,
195         parent: Option<<Self as link_ops::LinkOps>::LinkPtr>,
196         color: Color,
197     ) {
198         assert!(mem::align_of::<Link>() >= 2);
199         let bit = match color {
200             Color::Red => 0,
201             Color::Black => 1,
202         };
203         let parent_usize = parent.map(|x| x.as_ptr() as usize).unwrap_or(0);
204         ptr.as_ref().parent_color.set((parent_usize & !1) | bit);
205     }
206 }
207 
208 unsafe impl link_ops::LinkOps for LinkOps {
209     type LinkPtr = NonNull<Link>;
210 
211     #[inline]
acquire_link(&mut self, ptr: Self::LinkPtr) -> bool212     unsafe fn acquire_link(&mut self, ptr: Self::LinkPtr) -> bool {
213         if ptr.as_ref().is_linked() {
214             false
215         } else {
216             self.set_parent_color(ptr, None, Color::Black);
217             true
218         }
219     }
220 
221     #[inline]
release_link(&mut self, ptr: Self::LinkPtr)222     unsafe fn release_link(&mut self, ptr: Self::LinkPtr) {
223         ptr.as_ref().parent_color.set(UNLINKED_MARKER);
224     }
225 }
226 
227 unsafe impl RBTreeOps for LinkOps {
228     #[inline]
left(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>229     unsafe fn left(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
230         ptr.as_ref().left.get()
231     }
232 
233     #[inline]
right(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>234     unsafe fn right(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
235         ptr.as_ref().right.get()
236     }
237 
238     #[inline]
parent(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>239     unsafe fn parent(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
240         let parent_usize = ptr.as_ref().parent_color.get() & !1;
241         NonNull::new(parent_usize as *mut Link)
242     }
243 
244     #[inline]
color(&self, ptr: Self::LinkPtr) -> Color245     unsafe fn color(&self, ptr: Self::LinkPtr) -> Color {
246         if ptr.as_ref().parent_color.get() & 1 == 1 {
247             Color::Black
248         } else {
249             Color::Red
250         }
251     }
252 
253     #[inline]
set_left(&mut self, ptr: Self::LinkPtr, left: Option<Self::LinkPtr>)254     unsafe fn set_left(&mut self, ptr: Self::LinkPtr, left: Option<Self::LinkPtr>) {
255         ptr.as_ref().left.set(left);
256     }
257 
258     #[inline]
set_right(&mut self, ptr: Self::LinkPtr, right: Option<Self::LinkPtr>)259     unsafe fn set_right(&mut self, ptr: Self::LinkPtr, right: Option<Self::LinkPtr>) {
260         ptr.as_ref().right.set(right);
261     }
262 
263     #[inline]
set_parent(&mut self, ptr: Self::LinkPtr, parent: Option<Self::LinkPtr>)264     unsafe fn set_parent(&mut self, ptr: Self::LinkPtr, parent: Option<Self::LinkPtr>) {
265         self.set_parent_color(ptr, parent, self.color(ptr));
266     }
267 
268     #[inline]
set_color(&mut self, ptr: Self::LinkPtr, color: Color)269     unsafe fn set_color(&mut self, ptr: Self::LinkPtr, color: Color) {
270         self.set_parent_color(ptr, self.parent(ptr), color);
271     }
272 }
273 
274 unsafe impl SinglyLinkedListOps for LinkOps {
275     #[inline]
next(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>276     unsafe fn next(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
277         self.right(ptr)
278     }
279 
280     #[inline]
set_next(&mut self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>)281     unsafe fn set_next(&mut self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>) {
282         self.set_right(ptr, next);
283     }
284 }
285 
286 unsafe impl LinkedListOps for LinkOps {
287     #[inline]
next(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>288     unsafe fn next(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
289         self.right(ptr)
290     }
291 
292     #[inline]
prev(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>293     unsafe fn prev(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
294         self.left(ptr)
295     }
296 
297     #[inline]
set_next(&mut self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>)298     unsafe fn set_next(&mut self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>) {
299         self.set_right(ptr, next);
300     }
301 
302     #[inline]
set_prev(&mut self, ptr: Self::LinkPtr, prev: Option<Self::LinkPtr>)303     unsafe fn set_prev(&mut self, ptr: Self::LinkPtr, prev: Option<Self::LinkPtr>) {
304         self.set_left(ptr, prev);
305     }
306 }
307 
308 unsafe impl XorLinkedListOps for LinkOps {
309     #[inline]
next( &self, ptr: Self::LinkPtr, prev: Option<Self::LinkPtr>, ) -> Option<Self::LinkPtr>310     unsafe fn next(
311         &self,
312         ptr: Self::LinkPtr,
313         prev: Option<Self::LinkPtr>,
314     ) -> Option<Self::LinkPtr> {
315         let packed = self.right(ptr).map(|x| x.as_ptr() as usize).unwrap_or(0);
316         let raw = packed ^ prev.map(|x| x.as_ptr() as usize).unwrap_or(0);
317         NonNull::new(raw as *mut _)
318     }
319 
320     #[inline]
prev( &self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>, ) -> Option<Self::LinkPtr>321     unsafe fn prev(
322         &self,
323         ptr: Self::LinkPtr,
324         next: Option<Self::LinkPtr>,
325     ) -> Option<Self::LinkPtr> {
326         let packed = self.right(ptr).map(|x| x.as_ptr() as usize).unwrap_or(0);
327         let raw = packed ^ next.map(|x| x.as_ptr() as usize).unwrap_or(0);
328         NonNull::new(raw as *mut _)
329     }
330 
331     #[inline]
set( &mut self, ptr: Self::LinkPtr, prev: Option<Self::LinkPtr>, next: Option<Self::LinkPtr>, )332     unsafe fn set(
333         &mut self,
334         ptr: Self::LinkPtr,
335         prev: Option<Self::LinkPtr>,
336         next: Option<Self::LinkPtr>,
337     ) {
338         let new_packed = prev.map(|x| x.as_ptr() as usize).unwrap_or(0)
339             ^ next.map(|x| x.as_ptr() as usize).unwrap_or(0);
340 
341         let new_next = NonNull::new(new_packed as *mut _);
342         self.set_right(ptr, new_next);
343     }
344 
345     #[inline]
replace_next_or_prev( &mut self, ptr: Self::LinkPtr, old: Option<Self::LinkPtr>, new: Option<Self::LinkPtr>, )346     unsafe fn replace_next_or_prev(
347         &mut self,
348         ptr: Self::LinkPtr,
349         old: Option<Self::LinkPtr>,
350         new: Option<Self::LinkPtr>,
351     ) {
352         let packed = self.right(ptr).map(|x| x.as_ptr() as usize).unwrap_or(0);
353         let new_packed = packed
354             ^ old.map(|x| x.as_ptr() as usize).unwrap_or(0)
355             ^ new.map(|x| x.as_ptr() as usize).unwrap_or(0);
356 
357         let new_next = NonNull::new(new_packed as *mut _);
358         self.set_right(ptr, new_next);
359     }
360 }
361 
362 // =============================================================================
363 // AtomicLink
364 // =============================================================================
365 
366 /// Intrusive link that allows an object to be inserted into a
367 /// `RBTree`. This link allows the structure to be shared between threads.
368 
369 #[repr(align(2))]
370 pub struct AtomicLink {
371     left: Cell<Option<NonNull<AtomicLink>>>,
372     right: Cell<Option<NonNull<AtomicLink>>>,
373     parent_color: AtomicUsize,
374 }
375 
376 impl AtomicLink {
377     #[inline]
378     /// Creates a new `AtomicLink`.
new() -> AtomicLink379     pub const fn new() -> AtomicLink {
380         AtomicLink {
381             left: Cell::new(None),
382             right: Cell::new(None),
383             parent_color: AtomicUsize::new(UNLINKED_MARKER),
384         }
385     }
386 
387     /// Checks whether the `AtomicLink` is linked into a `RBTree`.
388     #[inline]
is_linked(&self) -> bool389     pub fn is_linked(&self) -> bool {
390         self.parent_color.load(atomic::Ordering::Relaxed) != UNLINKED_MARKER
391     }
392 
393     /// Forcibly unlinks an object from a `RBTree`.
394     ///
395     /// # Safety
396     ///
397     /// It is undefined behavior to call this function while still linked into a
398     /// `RBTree`. The only situation where this function is useful is
399     /// after calling `fast_clear` on a `RBTree`, since this clears
400     /// the collection without marking the nodes as unlinked.
401     #[inline]
force_unlink(&self)402     pub unsafe fn force_unlink(&self) {
403         self.parent_color
404             .store(UNLINKED_MARKER, atomic::Ordering::Release);
405     }
406 
407     /// Access `parent_color` in an exclusive context.
408     ///
409     /// # Safety
410     ///
411     /// This can only be called after `acquire_link` has been succesfully called.
412     #[inline]
parent_color_exclusive(&self) -> &Cell<usize>413     unsafe fn parent_color_exclusive(&self) -> &Cell<usize> {
414         // This is safe because currently AtomicUsize has the same representation Cell<usize>.
415         core::mem::transmute(&self.parent_color)
416     }
417 }
418 
419 impl DefaultLinkOps for AtomicLink {
420     type Ops = AtomicLinkOps;
421 
422     const NEW: Self::Ops = AtomicLinkOps;
423 }
424 
425 // An object containing a link can be sent to another thread since `acquire_link` is atomic.
426 unsafe impl Send for AtomicLink {}
427 
428 // An object containing a link can be shared between threads since `acquire_link` is atomic.
429 unsafe impl Sync for AtomicLink {}
430 
431 impl Clone for AtomicLink {
432     #[inline]
clone(&self) -> AtomicLink433     fn clone(&self) -> AtomicLink {
434         AtomicLink::new()
435     }
436 }
437 
438 impl Default for AtomicLink {
439     #[inline]
default() -> AtomicLink440     fn default() -> AtomicLink {
441         AtomicLink::new()
442     }
443 }
444 
445 // Provide an implementation of Debug so that structs containing a link can
446 // still derive Debug.
447 impl fmt::Debug for AtomicLink {
448     #[inline]
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result449     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
450         // There isn't anything sensible to print here except whether the link
451         // is currently in a list.
452         if self.is_linked() {
453             write!(f, "linked")
454         } else {
455             write!(f, "unlinked")
456         }
457     }
458 }
459 
460 // =============================================================================
461 // AtomicLinkOps
462 // =============================================================================
463 
464 /// Default `LinkOps` implementation for `RBTree`.
465 #[derive(Clone, Copy, Default)]
466 pub struct AtomicLinkOps;
467 
468 impl AtomicLinkOps {
469     #[inline]
set_parent_color( self, ptr: <Self as link_ops::LinkOps>::LinkPtr, parent: Option<<Self as link_ops::LinkOps>::LinkPtr>, color: Color, )470     unsafe fn set_parent_color(
471         self,
472         ptr: <Self as link_ops::LinkOps>::LinkPtr,
473         parent: Option<<Self as link_ops::LinkOps>::LinkPtr>,
474         color: Color,
475     ) {
476         assert!(mem::align_of::<Link>() >= 2);
477         let bit = match color {
478             Color::Red => 0,
479             Color::Black => 1,
480         };
481         let parent_usize = parent.map(|x| x.as_ptr() as usize).unwrap_or(0);
482         ptr.as_ref()
483             .parent_color_exclusive()
484             .set((parent_usize & !1) | bit);
485     }
486 }
487 
488 const LINKED_DEFAULT_VALUE: usize = 1;
489 
490 unsafe impl link_ops::LinkOps for AtomicLinkOps {
491     type LinkPtr = NonNull<AtomicLink>;
492 
493     #[inline]
acquire_link(&mut self, ptr: Self::LinkPtr) -> bool494     unsafe fn acquire_link(&mut self, ptr: Self::LinkPtr) -> bool {
495         ptr.as_ref()
496             .parent_color
497             .compare_exchange(
498                 UNLINKED_MARKER,
499                 LINKED_DEFAULT_VALUE,
500                 atomic::Ordering::Acquire,
501                 atomic::Ordering::Relaxed,
502             )
503             .is_ok()
504     }
505 
506     #[inline]
release_link(&mut self, ptr: Self::LinkPtr)507     unsafe fn release_link(&mut self, ptr: Self::LinkPtr) {
508         ptr.as_ref()
509             .parent_color
510             .store(UNLINKED_MARKER, atomic::Ordering::Release)
511     }
512 }
513 
514 unsafe impl RBTreeOps for AtomicLinkOps {
515     #[inline]
left(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>516     unsafe fn left(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
517         ptr.as_ref().left.get()
518     }
519 
520     #[inline]
right(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>521     unsafe fn right(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
522         ptr.as_ref().right.get()
523     }
524 
525     #[inline]
parent(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>526     unsafe fn parent(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
527         let parent_usize = ptr.as_ref().parent_color_exclusive().get() & !1;
528         NonNull::new(parent_usize as *mut AtomicLink)
529     }
530 
531     #[inline]
color(&self, ptr: Self::LinkPtr) -> Color532     unsafe fn color(&self, ptr: Self::LinkPtr) -> Color {
533         if ptr.as_ref().parent_color_exclusive().get() & 1 == 1 {
534             Color::Black
535         } else {
536             Color::Red
537         }
538     }
539 
540     #[inline]
set_left(&mut self, ptr: Self::LinkPtr, left: Option<Self::LinkPtr>)541     unsafe fn set_left(&mut self, ptr: Self::LinkPtr, left: Option<Self::LinkPtr>) {
542         ptr.as_ref().left.set(left);
543     }
544 
545     #[inline]
set_right(&mut self, ptr: Self::LinkPtr, right: Option<Self::LinkPtr>)546     unsafe fn set_right(&mut self, ptr: Self::LinkPtr, right: Option<Self::LinkPtr>) {
547         ptr.as_ref().right.set(right);
548     }
549 
550     #[inline]
set_parent(&mut self, ptr: Self::LinkPtr, parent: Option<Self::LinkPtr>)551     unsafe fn set_parent(&mut self, ptr: Self::LinkPtr, parent: Option<Self::LinkPtr>) {
552         self.set_parent_color(ptr, parent, self.color(ptr));
553     }
554 
555     #[inline]
set_color(&mut self, ptr: Self::LinkPtr, color: Color)556     unsafe fn set_color(&mut self, ptr: Self::LinkPtr, color: Color) {
557         self.set_parent_color(ptr, self.parent(ptr), color);
558     }
559 }
560 
561 unsafe impl SinglyLinkedListOps for AtomicLinkOps {
562     #[inline]
next(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>563     unsafe fn next(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
564         self.right(ptr)
565     }
566 
567     #[inline]
set_next(&mut self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>)568     unsafe fn set_next(&mut self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>) {
569         self.set_right(ptr, next);
570     }
571 }
572 
573 unsafe impl LinkedListOps for AtomicLinkOps {
574     #[inline]
next(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>575     unsafe fn next(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
576         self.right(ptr)
577     }
578 
579     #[inline]
prev(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr>580     unsafe fn prev(&self, ptr: Self::LinkPtr) -> Option<Self::LinkPtr> {
581         self.left(ptr)
582     }
583 
584     #[inline]
set_next(&mut self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>)585     unsafe fn set_next(&mut self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>) {
586         self.set_right(ptr, next);
587     }
588 
589     #[inline]
set_prev(&mut self, ptr: Self::LinkPtr, prev: Option<Self::LinkPtr>)590     unsafe fn set_prev(&mut self, ptr: Self::LinkPtr, prev: Option<Self::LinkPtr>) {
591         self.set_left(ptr, prev);
592     }
593 }
594 
595 unsafe impl XorLinkedListOps for AtomicLinkOps {
596     #[inline]
next( &self, ptr: Self::LinkPtr, prev: Option<Self::LinkPtr>, ) -> Option<Self::LinkPtr>597     unsafe fn next(
598         &self,
599         ptr: Self::LinkPtr,
600         prev: Option<Self::LinkPtr>,
601     ) -> Option<Self::LinkPtr> {
602         let packed = self.right(ptr).map(|x| x.as_ptr() as usize).unwrap_or(0);
603         let raw = packed ^ prev.map(|x| x.as_ptr() as usize).unwrap_or(0);
604         NonNull::new(raw as *mut _)
605     }
606 
607     #[inline]
prev( &self, ptr: Self::LinkPtr, next: Option<Self::LinkPtr>, ) -> Option<Self::LinkPtr>608     unsafe fn prev(
609         &self,
610         ptr: Self::LinkPtr,
611         next: Option<Self::LinkPtr>,
612     ) -> Option<Self::LinkPtr> {
613         let packed = self.right(ptr).map(|x| x.as_ptr() as usize).unwrap_or(0);
614         let raw = packed ^ next.map(|x| x.as_ptr() as usize).unwrap_or(0);
615         NonNull::new(raw as *mut _)
616     }
617 
618     #[inline]
set( &mut self, ptr: Self::LinkPtr, prev: Option<Self::LinkPtr>, next: Option<Self::LinkPtr>, )619     unsafe fn set(
620         &mut self,
621         ptr: Self::LinkPtr,
622         prev: Option<Self::LinkPtr>,
623         next: Option<Self::LinkPtr>,
624     ) {
625         let new_packed = prev.map(|x| x.as_ptr() as usize).unwrap_or(0)
626             ^ next.map(|x| x.as_ptr() as usize).unwrap_or(0);
627 
628         let new_next = NonNull::new(new_packed as *mut _);
629         self.set_right(ptr, new_next);
630     }
631 
632     #[inline]
replace_next_or_prev( &mut self, ptr: Self::LinkPtr, old: Option<Self::LinkPtr>, new: Option<Self::LinkPtr>, )633     unsafe fn replace_next_or_prev(
634         &mut self,
635         ptr: Self::LinkPtr,
636         old: Option<Self::LinkPtr>,
637         new: Option<Self::LinkPtr>,
638     ) {
639         let packed = self.right(ptr).map(|x| x.as_ptr() as usize).unwrap_or(0);
640         let new_packed = packed
641             ^ old.map(|x| x.as_ptr() as usize).unwrap_or(0)
642             ^ new.map(|x| x.as_ptr() as usize).unwrap_or(0);
643 
644         let new_next = NonNull::new(new_packed as *mut _);
645         self.set_right(ptr, new_next);
646     }
647 }
648 
649 #[inline]
is_left_child<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr, parent: T::LinkPtr) -> bool650 unsafe fn is_left_child<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr, parent: T::LinkPtr) -> bool {
651     link_ops.left(parent) == Some(ptr)
652 }
653 
654 #[inline]
first_child<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr) -> T::LinkPtr655 unsafe fn first_child<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr) -> T::LinkPtr {
656     let mut x = ptr;
657     while let Some(y) = link_ops.left(x) {
658         x = y;
659     }
660     x
661 }
662 
663 #[inline]
last_child<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr) -> T::LinkPtr664 unsafe fn last_child<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr) -> T::LinkPtr {
665     let mut x = ptr;
666     while let Some(y) = link_ops.right(x) {
667         x = y;
668     }
669     x
670 }
671 
672 #[inline]
next<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr) -> Option<T::LinkPtr>673 unsafe fn next<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr) -> Option<T::LinkPtr> {
674     if let Some(right) = link_ops.right(ptr) {
675         Some(first_child(link_ops, right))
676     } else {
677         let mut x = ptr;
678         loop {
679             if let Some(parent) = link_ops.parent(x) {
680                 if is_left_child(link_ops, x, parent) {
681                     return Some(parent);
682                 }
683 
684                 x = parent;
685             } else {
686                 return None;
687             }
688         }
689     }
690 }
691 
692 #[inline]
prev<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr) -> Option<T::LinkPtr>693 unsafe fn prev<T: RBTreeOps>(link_ops: &T, ptr: T::LinkPtr) -> Option<T::LinkPtr> {
694     if let Some(left) = link_ops.left(ptr) {
695         Some(last_child(link_ops, left))
696     } else {
697         let mut x = ptr;
698         loop {
699             if let Some(parent) = link_ops.parent(x) {
700                 if !is_left_child(link_ops, x, parent) {
701                     return Some(parent);
702                 }
703 
704                 x = parent;
705             } else {
706                 return None;
707             }
708         }
709     }
710 }
711 
712 #[inline]
replace_with<T: RBTreeOps>( link_ops: &mut T, ptr: T::LinkPtr, new: T::LinkPtr, root: &mut Option<T::LinkPtr>, )713 unsafe fn replace_with<T: RBTreeOps>(
714     link_ops: &mut T,
715     ptr: T::LinkPtr,
716     new: T::LinkPtr,
717     root: &mut Option<T::LinkPtr>,
718 ) {
719     if let Some(parent) = link_ops.parent(ptr) {
720         if is_left_child(link_ops, ptr, parent) {
721             link_ops.set_left(parent, Some(new));
722         } else {
723             link_ops.set_right(parent, Some(new));
724         }
725     } else {
726         *root = Some(new);
727     }
728     if let Some(left) = link_ops.left(ptr) {
729         link_ops.set_parent(left, Some(new));
730     }
731     if let Some(right) = link_ops.right(ptr) {
732         link_ops.set_parent(right, Some(new));
733     }
734     link_ops.set_left(new, link_ops.left(ptr));
735     link_ops.set_right(new, link_ops.right(ptr));
736     link_ops.set_parent(new, link_ops.parent(ptr));
737     link_ops.set_color(new, link_ops.color(ptr));
738     link_ops.release_link(ptr);
739 }
740 
741 #[inline]
insert_left<T: RBTreeOps>( link_ops: &mut T, ptr: T::LinkPtr, new: T::LinkPtr, root: &mut Option<T::LinkPtr>, )742 unsafe fn insert_left<T: RBTreeOps>(
743     link_ops: &mut T,
744     ptr: T::LinkPtr,
745     new: T::LinkPtr,
746     root: &mut Option<T::LinkPtr>,
747 ) {
748     link_ops.set_parent(new, Some(ptr));
749     link_ops.set_color(new, Color::Red);
750     link_ops.set_left(new, None);
751     link_ops.set_right(new, None);
752     link_ops.set_left(ptr, Some(new));
753     post_insert(link_ops, new, root);
754 }
755 
756 #[inline]
insert_right<T: RBTreeOps>( link_ops: &mut T, ptr: T::LinkPtr, new: T::LinkPtr, root: &mut Option<T::LinkPtr>, )757 unsafe fn insert_right<T: RBTreeOps>(
758     link_ops: &mut T,
759     ptr: T::LinkPtr,
760     new: T::LinkPtr,
761     root: &mut Option<T::LinkPtr>,
762 ) {
763     link_ops.set_parent(new, Some(ptr));
764     link_ops.set_color(new, Color::Red);
765     link_ops.set_left(new, None);
766     link_ops.set_right(new, None);
767     link_ops.set_right(ptr, Some(new));
768     post_insert(link_ops, new, root);
769 }
770 
rotate_left<T: RBTreeOps>( link_ops: &mut T, ptr: T::LinkPtr, root: &mut Option<T::LinkPtr>, )771 unsafe fn rotate_left<T: RBTreeOps>(
772     link_ops: &mut T,
773     ptr: T::LinkPtr,
774     root: &mut Option<T::LinkPtr>,
775 ) {
776     let y = link_ops.right(ptr).unwrap_unchecked();
777     link_ops.set_right(ptr, link_ops.left(y));
778     if let Some(right) = link_ops.right(ptr) {
779         link_ops.set_parent(right, Some(ptr));
780     }
781     link_ops.set_parent(y, link_ops.parent(ptr));
782     if let Some(parent) = link_ops.parent(ptr) {
783         if is_left_child(link_ops, ptr, parent) {
784             link_ops.set_left(parent, Some(y));
785         } else {
786             link_ops.set_right(parent, Some(y));
787         }
788     } else {
789         *root = Some(y);
790     }
791     link_ops.set_left(y, Some(ptr));
792     link_ops.set_parent(ptr, Some(y));
793 }
794 
rotate_right<T: RBTreeOps>( link_ops: &mut T, ptr: T::LinkPtr, root: &mut Option<T::LinkPtr>, )795 unsafe fn rotate_right<T: RBTreeOps>(
796     link_ops: &mut T,
797     ptr: T::LinkPtr,
798     root: &mut Option<T::LinkPtr>,
799 ) {
800     let y = link_ops.left(ptr).unwrap_unchecked();
801     link_ops.set_left(ptr, link_ops.right(y));
802     if let Some(left) = link_ops.left(ptr) {
803         link_ops.set_parent(left, Some(ptr));
804     }
805     link_ops.set_parent(y, link_ops.parent(ptr));
806     if let Some(parent) = link_ops.parent(ptr) {
807         if is_left_child(link_ops, ptr, parent) {
808             link_ops.set_left(parent, Some(y));
809         } else {
810             link_ops.set_right(parent, Some(y));
811         }
812     } else {
813         *root = Some(y);
814     }
815     link_ops.set_right(y, Some(ptr));
816     link_ops.set_parent(ptr, Some(y));
817 }
818 
819 // This code is based on the red-black tree implementation in libc++
post_insert<T: RBTreeOps>( link_ops: &mut T, ptr: T::LinkPtr, root: &mut Option<T::LinkPtr>, )820 unsafe fn post_insert<T: RBTreeOps>(
821     link_ops: &mut T,
822     ptr: T::LinkPtr,
823     root: &mut Option<T::LinkPtr>,
824 ) {
825     let mut x = ptr;
826     while let Some(parent) = link_ops.parent(x) {
827         if link_ops.color(parent) != Color::Red {
828             break;
829         }
830         // SAFETY: The root of the tree must be black, and `parent` cannot be the root if it is red.
831         let grandparent = link_ops.parent(parent).unwrap_unchecked();
832 
833         if is_left_child(link_ops, parent, grandparent) {
834             let y = link_ops.right(grandparent);
835             if let Some(y) = y {
836                 if link_ops.color(y) == Color::Red {
837                     x = parent;
838                     link_ops.set_color(x, Color::Black);
839                     x = grandparent;
840 
841                     if link_ops.parent(x).is_none() {
842                         link_ops.set_color(x, Color::Black);
843                     } else {
844                         link_ops.set_color(x, Color::Red);
845                     }
846                     link_ops.set_color(y, Color::Black);
847                     continue;
848                 }
849             }
850             if !is_left_child(link_ops, x, parent) {
851                 x = parent;
852                 rotate_left(link_ops, x, root);
853             }
854             x = link_ops.parent(x).unwrap_unchecked();
855             link_ops.set_color(x, Color::Black);
856             x = link_ops.parent(x).unwrap_unchecked();
857             link_ops.set_color(x, Color::Red);
858             rotate_right(link_ops, x, root);
859         } else {
860             let y = link_ops.left(grandparent);
861             if let Some(y) = y {
862                 if link_ops.color(y) == Color::Red {
863                     x = parent;
864                     link_ops.set_color(x, Color::Black);
865                     x = grandparent;
866                     if link_ops.parent(x).is_none() {
867                         link_ops.set_color(x, Color::Black);
868                     } else {
869                         link_ops.set_color(x, Color::Red);
870                     }
871                     link_ops.set_color(y, Color::Black);
872                     continue;
873                 }
874             }
875             if is_left_child(link_ops, x, parent) {
876                 x = parent;
877                 rotate_right(link_ops, x, root);
878             }
879             x = link_ops.parent(x).unwrap_unchecked();
880             link_ops.set_color(x, Color::Black);
881             x = link_ops.parent(x).unwrap_unchecked();
882             link_ops.set_color(x, Color::Red);
883             rotate_left(link_ops, x, root);
884         }
885         break;
886     }
887 }
888 
889 // This code is based on the red-black tree implementation in libc++
remove<T: RBTreeOps>(link_ops: &mut T, ptr: T::LinkPtr, root: &mut Option<T::LinkPtr>)890 unsafe fn remove<T: RBTreeOps>(link_ops: &mut T, ptr: T::LinkPtr, root: &mut Option<T::LinkPtr>) {
891     let y = if link_ops.left(ptr).is_none() || link_ops.right(ptr).is_none() {
892         ptr
893     } else {
894         next(link_ops, ptr).unwrap_unchecked()
895     };
896     let x = if link_ops.left(y).is_some() {
897         link_ops.left(y)
898     } else {
899         link_ops.right(y)
900     };
901     let mut w = None;
902     if let Some(x) = x {
903         link_ops.set_parent(x, link_ops.parent(y));
904     }
905     if let Some(y_parent) = link_ops.parent(y) {
906         if is_left_child(link_ops, y, y_parent) {
907             link_ops.set_left(y_parent, x);
908             w = link_ops.right(y_parent);
909         } else {
910             link_ops.set_right(y_parent, x);
911             w = link_ops.left(y_parent);
912         }
913     } else {
914         *root = x;
915     }
916     let removed_black = link_ops.color(y) == Color::Black;
917     if y != ptr {
918         if let Some(parent) = link_ops.parent(ptr) {
919             link_ops.set_parent(y, Some(parent));
920             if is_left_child(link_ops, ptr, parent) {
921                 link_ops.set_left(parent, Some(y));
922             } else {
923                 link_ops.set_right(parent, Some(y));
924             }
925         } else {
926             link_ops.set_parent(y, None);
927             *root = Some(y);
928         }
929         link_ops.set_left(y, link_ops.left(ptr));
930         link_ops.set_parent(link_ops.left(y).unwrap_unchecked(), Some(y));
931         link_ops.set_right(y, link_ops.right(ptr));
932         if let Some(y_right) = link_ops.right(y) {
933             link_ops.set_parent(y_right, Some(y));
934         }
935         link_ops.set_color(y, link_ops.color(ptr));
936     }
937     if removed_black && !root.is_none() {
938         if let Some(x) = x {
939             link_ops.set_color(x, Color::Black);
940         } else {
941             let mut w = w.unwrap_unchecked();
942             loop {
943                 let mut w_parent = link_ops.parent(w).unwrap_unchecked();
944                 if !is_left_child(link_ops, w, w_parent) {
945                     if link_ops.color(w) == Color::Red {
946                         link_ops.set_color(w, Color::Black);
947                         link_ops.set_color(w_parent, Color::Red);
948                         rotate_left(link_ops, w_parent, root);
949                         w = link_ops
950                             .right(link_ops.left(w).unwrap_unchecked())
951                             .unwrap_unchecked();
952                         w_parent = link_ops.parent(w).unwrap_unchecked();
953                     }
954 
955                     let left_color = link_ops.left(w).map(|x| link_ops.color(x));
956                     let right_color = link_ops.right(w).map(|x| link_ops.color(x));
957                     if (left_color != Some(Color::Red)) && (right_color != Some(Color::Red)) {
958                         link_ops.set_color(w, Color::Red);
959                         if link_ops.parent(w_parent).is_none()
960                             || link_ops.color(w_parent) == Color::Red
961                         {
962                             link_ops.set_color(w_parent, Color::Black);
963                             break;
964                         }
965                         let w_grandparent = link_ops.parent(w_parent).unwrap_unchecked();
966                         w = if is_left_child(link_ops, w_parent, w_grandparent) {
967                             link_ops.right(w_grandparent).unwrap_unchecked()
968                         } else {
969                             link_ops.left(w_grandparent).unwrap_unchecked()
970                         };
971                     } else {
972                         if link_ops.right(w).map(|x| link_ops.color(x)) != Some(Color::Red) {
973                             link_ops.set_color(link_ops.left(w).unwrap_unchecked(), Color::Black);
974                             link_ops.set_color(w, Color::Red);
975                             rotate_right(link_ops, w, root);
976                             w = link_ops.parent(w).unwrap_unchecked();
977                             w_parent = link_ops.parent(w).unwrap_unchecked();
978                         }
979                         link_ops.set_color(w, link_ops.color(w_parent));
980                         link_ops.set_color(w_parent, Color::Black);
981                         link_ops.set_color(link_ops.right(w).unwrap_unchecked(), Color::Black);
982                         rotate_left(link_ops, w_parent, root);
983                         break;
984                     }
985                 } else {
986                     if link_ops.color(w) == Color::Red {
987                         link_ops.set_color(w, Color::Black);
988                         link_ops.set_color(w_parent, Color::Red);
989                         rotate_right(link_ops, w_parent, root);
990                         w = link_ops
991                             .left(link_ops.right(w).unwrap_unchecked())
992                             .unwrap_unchecked();
993                         w_parent = link_ops.parent(w).unwrap_unchecked();
994                     }
995                     let left_color = link_ops.left(w).map(|x| link_ops.color(x));
996                     let right_color = link_ops.right(w).map(|x| link_ops.color(x));
997                     if (left_color != Some(Color::Red)) && (right_color != Some(Color::Red)) {
998                         link_ops.set_color(w, Color::Red);
999                         if link_ops.parent(w_parent).is_none()
1000                             || link_ops.color(w_parent) == Color::Red
1001                         {
1002                             link_ops.set_color(w_parent, Color::Black);
1003                             break;
1004                         }
1005                         w = if is_left_child(
1006                             link_ops,
1007                             w_parent,
1008                             link_ops.parent(w_parent).unwrap_unchecked(),
1009                         ) {
1010                             link_ops
1011                                 .right(link_ops.parent(w_parent).unwrap_unchecked())
1012                                 .unwrap_unchecked()
1013                         } else {
1014                             link_ops
1015                                 .left(link_ops.parent(w_parent).unwrap_unchecked())
1016                                 .unwrap_unchecked()
1017                         };
1018                     } else {
1019                         if link_ops.left(w).map(|x| link_ops.color(x)) != Some(Color::Red) {
1020                             link_ops.set_color(link_ops.right(w).unwrap_unchecked(), Color::Black);
1021                             link_ops.set_color(w, Color::Red);
1022                             rotate_left(link_ops, w, root);
1023                             w = link_ops.parent(w).unwrap_unchecked();
1024                             w_parent = link_ops.parent(w).unwrap_unchecked();
1025                         }
1026                         link_ops.set_color(w, link_ops.color(w_parent));
1027                         link_ops.set_color(w_parent, Color::Black);
1028                         link_ops.set_color(link_ops.left(w).unwrap_unchecked(), Color::Black);
1029                         rotate_right(link_ops, w_parent, root);
1030                         break;
1031                     }
1032                 }
1033             }
1034         }
1035     }
1036     link_ops.release_link(ptr);
1037 }
1038 
1039 // =============================================================================
1040 // Cursor, CursorMut
1041 // =============================================================================
1042 
1043 /// A cursor which provides read-only access to a `RBTree`.
1044 pub struct Cursor<'a, A: Adapter>
1045 where
1046     A::LinkOps: RBTreeOps,
1047 {
1048     current: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
1049     tree: &'a RBTree<A>,
1050 }
1051 
1052 impl<'a, A: Adapter> Clone for Cursor<'a, A>
1053 where
1054     A::LinkOps: RBTreeOps,
1055 {
1056     #[inline]
1057     fn clone(&self) -> Cursor<'a, A> {
1058         Cursor {
1059             current: self.current,
1060             tree: self.tree,
1061         }
1062     }
1063 }
1064 
1065 impl<'a, A: Adapter> Cursor<'a, A>
1066 where
1067     A::LinkOps: RBTreeOps,
1068 {
1069     /// Checks if the cursor is currently pointing to the null object.
1070     #[inline]
1071     pub fn is_null(&self) -> bool {
1072         self.current.is_none()
1073     }
1074 
1075     /// Returns a reference to the object that the cursor is currently
1076     /// pointing to.
1077     ///
1078     /// This returns `None` if the cursor is currently pointing to the null
1079     /// object.
1080     #[inline]
1081     pub fn get(&self) -> Option<&'a <A::PointerOps as PointerOps>::Value> {
1082         Some(unsafe { &*self.tree.adapter.get_value(self.current?) })
1083     }
1084 
1085     /// Clones and returns the pointer that points to the element that the
1086     /// cursor is referencing.
1087     ///
1088     /// This returns `None` if the cursor is currently pointing to the null
1089     /// object.
1090     #[inline]
1091     pub fn clone_pointer(&self) -> Option<<A::PointerOps as PointerOps>::Pointer>
1092     where
1093         <A::PointerOps as PointerOps>::Pointer: Clone,
1094     {
1095         let raw_pointer = self.get()? as *const <A::PointerOps as PointerOps>::Value;
1096         Some(unsafe {
1097             crate::pointer_ops::clone_pointer_from_raw(self.tree.adapter.pointer_ops(), raw_pointer)
1098         })
1099     }
1100 
1101     /// Moves the cursor to the next element of the `RBTree`.
1102     ///
1103     /// If the cursor is pointer to the null object then this will move it to
1104     /// the first element of the `RBTree`. If it is pointing to the last
1105     /// element of the `RBTree` then this will move it to the null object.
1106     #[inline]
1107     pub fn move_next(&mut self) {
1108         if let Some(current) = self.current {
1109             self.current = unsafe { next(self.tree.adapter.link_ops(), current) };
1110         } else if let Some(root) = self.tree.root {
1111             self.current = Some(unsafe { first_child(self.tree.adapter.link_ops(), root) });
1112         } else {
1113             self.current = None;
1114         }
1115     }
1116 
1117     /// Moves the cursor to the previous element of the `RBTree`.
1118     ///
1119     /// If the cursor is pointer to the null object then this will move it to
1120     /// the last element of the `RBTree`. If it is pointing to the first
1121     /// element of the `RBTree` then this will move it to the null object.
1122     #[inline]
1123     pub fn move_prev(&mut self) {
1124         if let Some(current) = self.current {
1125             self.current = unsafe { prev(self.tree.adapter.link_ops(), current) };
1126         } else if let Some(root) = self.tree.root {
1127             self.current = Some(unsafe { last_child(self.tree.adapter.link_ops(), root) });
1128         } else {
1129             self.current = None;
1130         }
1131     }
1132 
1133     /// Returns a cursor pointing to the next element of the `RBTree`.
1134     ///
1135     /// If the cursor is pointer to the null object then this will return the
1136     /// first element of the `RBTree`. If it is pointing to the last
1137     /// element of the `RBTree` then this will return a null cursor.
1138     #[inline]
1139     pub fn peek_next(&self) -> Cursor<'_, A> {
1140         let mut next = self.clone();
1141         next.move_next();
1142         next
1143     }
1144 
1145     /// Returns a cursor pointing to the previous element of the `RBTree`.
1146     ///
1147     /// If the cursor is pointer to the null object then this will return the
1148     /// last element of the `RBTree`. If it is pointing to the first
1149     /// element of the `RBTree` then this will return a null cursor.
1150     #[inline]
1151     pub fn peek_prev(&self) -> Cursor<'_, A> {
1152         let mut prev = self.clone();
1153         prev.move_prev();
1154         prev
1155     }
1156 }
1157 
1158 /// A cursor which provides mutable access to a `RBTree`.
1159 pub struct CursorMut<'a, A: Adapter>
1160 where
1161     A::LinkOps: RBTreeOps,
1162 {
1163     current: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
1164     tree: &'a mut RBTree<A>,
1165 }
1166 
1167 impl<'a, A: Adapter> CursorMut<'a, A>
1168 where
1169     A::LinkOps: RBTreeOps,
1170 {
1171     /// Checks if the cursor is currently pointing to the null object.
1172     #[inline]
1173     pub fn is_null(&self) -> bool {
1174         self.current.is_none()
1175     }
1176 
1177     /// Returns a reference to the object that the cursor is currently
1178     /// pointing to.
1179     ///
1180     /// This returns None if the cursor is currently pointing to the null
1181     /// object.
1182     #[inline]
1183     pub fn get(&self) -> Option<&<A::PointerOps as PointerOps>::Value> {
1184         Some(unsafe { &*self.tree.adapter.get_value(self.current?) })
1185     }
1186 
1187     /// Returns a read-only cursor pointing to the current element.
1188     ///
1189     /// The lifetime of the returned `Cursor` is bound to that of the
1190     /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
1191     /// `CursorMut` is frozen for the lifetime of the `Cursor`.
1192     #[inline]
1193     pub fn as_cursor(&self) -> Cursor<'_, A> {
1194         Cursor {
1195             current: self.current,
1196             tree: self.tree,
1197         }
1198     }
1199 
1200     /// Moves the cursor to the next element of the `RBTree`.
1201     ///
1202     /// If the cursor is pointer to the null object then this will move it to
1203     /// the first element of the `RBTree`. If it is pointing to the last
1204     /// element of the `RBTree` then this will move it to the null object.
1205     #[inline]
1206     pub fn move_next(&mut self) {
1207         if let Some(current) = self.current {
1208             self.current = unsafe { next(self.tree.adapter.link_ops(), current) };
1209         } else if let Some(root) = self.tree.root {
1210             self.current = Some(unsafe { first_child(self.tree.adapter.link_ops(), root) });
1211         } else {
1212             self.current = None;
1213         }
1214     }
1215 
1216     /// Moves the cursor to the previous element of the `RBTree`.
1217     ///
1218     /// If the cursor is pointer to the null object then this will move it to
1219     /// the last element of the `RBTree`. If it is pointing to the first
1220     /// element of the `RBTree` then this will move it to the null object.
1221     #[inline]
1222     pub fn move_prev(&mut self) {
1223         if let Some(current) = self.current {
1224             self.current = unsafe { prev(self.tree.adapter.link_ops(), current) };
1225         } else if let Some(root) = self.tree.root {
1226             self.current = Some(unsafe { last_child(self.tree.adapter.link_ops(), root) });
1227         } else {
1228             self.current = None;
1229         }
1230     }
1231 
1232     /// Returns a cursor pointing to the next element of the `RBTree`.
1233     ///
1234     /// If the cursor is pointer to the null object then this will return the
1235     /// first element of the `RBTree`. If it is pointing to the last
1236     /// element of the `RBTree` then this will return a null cursor.
1237     #[inline]
1238     pub fn peek_next(&self) -> Cursor<'_, A> {
1239         let mut next = self.as_cursor();
1240         next.move_next();
1241         next
1242     }
1243 
1244     /// Returns a cursor pointing to the previous element of the `RBTree`.
1245     ///
1246     /// If the cursor is pointer to the null object then this will return the
1247     /// last element of the `RBTree`. If it is pointing to the first
1248     /// element of the `RBTree` then this will return a null cursor.
1249     #[inline]
1250     pub fn peek_prev(&self) -> Cursor<'_, A> {
1251         let mut prev = self.as_cursor();
1252         prev.move_prev();
1253         prev
1254     }
1255 
1256     /// Removes the current element from the `RBTree`.
1257     ///
1258     /// A pointer to the element that was removed is returned, and the cursor is
1259     /// moved to point to the next element in the `RBTree`.
1260     ///
1261     /// If the cursor is currently pointing to the null object then no element
1262     /// is removed and `None` is returned.
1263     #[inline]
1264     pub fn remove(&mut self) -> Option<<A::PointerOps as PointerOps>::Pointer> {
1265         unsafe {
1266             if let Some(current) = self.current {
1267                 let next = next(self.tree.adapter.link_ops(), current);
1268                 let result = current;
1269                 remove(
1270                     self.tree.adapter.link_ops_mut(),
1271                     current,
1272                     &mut self.tree.root,
1273                 );
1274                 self.current = next;
1275                 Some(
1276                     self.tree
1277                         .adapter
1278                         .pointer_ops()
1279                         .from_raw(self.tree.adapter.get_value(result)),
1280                 )
1281             } else {
1282                 None
1283             }
1284         }
1285     }
1286 
1287     /// Removes the current element from the `RBTree` and inserts another
1288     /// object in its place.
1289     ///
1290     /// A pointer to the element that was removed is returned, and the cursor is
1291     /// modified to point to the newly added element.
1292     ///
1293     /// When using this function you must ensure that the elements in the
1294     /// collection are maintained in increasing order. Failure to do this may
1295     /// lead to `find`, `upper_bound`, `lower_bound` and `range` returning
1296     /// incorrect results.
1297     ///
1298     /// If the cursor is currently pointing to the null object then an error is
1299     /// returned containing the given `val` parameter.
1300     ///
1301     /// # Panics
1302     ///
1303     /// Panics if the new element is already linked to a different intrusive
1304     /// collection.
1305     #[inline]
1306     pub fn replace_with(
1307         &mut self,
1308         val: <A::PointerOps as PointerOps>::Pointer,
1309     ) -> Result<<A::PointerOps as PointerOps>::Pointer, <A::PointerOps as PointerOps>::Pointer>
1310     {
1311         unsafe {
1312             if let Some(current) = self.current {
1313                 let new = self.tree.node_from_value(val);
1314                 let result = current;
1315                 replace_with(
1316                     self.tree.adapter.link_ops_mut(),
1317                     current,
1318                     new,
1319                     &mut self.tree.root,
1320                 );
1321                 self.current = Some(new);
1322                 Ok(self
1323                     .tree
1324                     .adapter
1325                     .pointer_ops()
1326                     .from_raw(self.tree.adapter.get_value(result)))
1327             } else {
1328                 Err(val)
1329             }
1330         }
1331     }
1332 
1333     /// Inserts a new element into the `RBTree` after the current one.
1334     ///
1335     /// When using this function you must ensure that the elements in the
1336     /// collection are maintained in increasing order. Failure to do this may
1337     /// lead to `find`, `upper_bound`, `lower_bound` and `range` returning
1338     /// incorrect results.
1339     ///
1340     /// If the cursor is pointing at the null object then the new element is
1341     /// inserted at the start of the `RBTree`.
1342     ///
1343     /// # Panics
1344     ///
1345     /// Panics if the new element is already linked to a different intrusive
1346     /// collection.
1347     #[inline]
1348     pub fn insert_after(&mut self, val: <A::PointerOps as PointerOps>::Pointer) {
1349         unsafe {
1350             let new = self.tree.node_from_value(val);
1351             let link_ops = self.tree.adapter.link_ops_mut();
1352 
1353             if let Some(root) = self.tree.root {
1354                 if let Some(current) = self.current {
1355                     if link_ops.right(current).is_some() {
1356                         let next = next(link_ops, current).unwrap_unchecked();
1357                         insert_left(link_ops, next, new, &mut self.tree.root);
1358                     } else {
1359                         insert_right(link_ops, current, new, &mut self.tree.root);
1360                     }
1361                 } else {
1362                     insert_left(
1363                         link_ops,
1364                         first_child(link_ops, root),
1365                         new,
1366                         &mut self.tree.root,
1367                     );
1368                 }
1369             } else {
1370                 self.tree.insert_root(new);
1371             }
1372         }
1373     }
1374 
1375     /// Inserts a new element into the `RBTree` before the current one.
1376     ///
1377     /// When using this function you must ensure that the elements in the
1378     /// collection are maintained in increasing order. Failure to do this may
1379     /// lead to `find`, `upper_bound`, `lower_bound` and `range` returning
1380     /// incorrect results.
1381     ///
1382     /// If the cursor is pointing at the null object then the new element is
1383     /// inserted at the end of the `RBTree`.
1384     ///
1385     /// # Panics
1386     ///
1387     /// Panics if the new element is already linked to a different intrusive
1388     /// collection.
1389     #[inline]
1390     pub fn insert_before(&mut self, val: <A::PointerOps as PointerOps>::Pointer) {
1391         unsafe {
1392             let new = self.tree.node_from_value(val);
1393             let link_ops = self.tree.adapter.link_ops_mut();
1394 
1395             if let Some(root) = self.tree.root {
1396                 if let Some(current) = self.current {
1397                     if link_ops.left(current).is_some() {
1398                         let prev = prev(link_ops, current).unwrap_unchecked();
1399                         insert_right(link_ops, prev, new, &mut self.tree.root);
1400                     } else {
1401                         insert_left(link_ops, current, new, &mut self.tree.root);
1402                     }
1403                 } else {
1404                     insert_right(
1405                         link_ops,
1406                         last_child(link_ops, root),
1407                         new,
1408                         &mut self.tree.root,
1409                     );
1410                 }
1411             } else {
1412                 self.tree.insert_root(new);
1413             }
1414         }
1415     }
1416 
1417     /// Consumes `CursorMut` and returns a reference to the object that
1418     /// the cursor is currently pointing to. Unlike [get](Self::get),
1419     /// the returned reference's lifetime is tied to `RBTree`'s lifetime.
1420     ///
1421     /// This returns None if the cursor is currently pointing to the null object.
1422     #[inline]
1423     pub fn into_ref(self) -> Option<&'a <A::PointerOps as PointerOps>::Value> {
1424         Some(unsafe { &*self.tree.adapter.get_value(self.current?) })
1425     }
1426 }
1427 
1428 impl<'a, A: for<'b> KeyAdapter<'b>> CursorMut<'a, A>
1429 where
1430     <A as Adapter>::LinkOps: RBTreeOps,
1431 {
1432     /// Inserts a new element into the `RBTree`.
1433     ///
1434     /// The new element will be inserted at the correct position in the tree
1435     /// based on its key, regardless of the current cursor position.
1436     ///
1437     /// # Panics
1438     ///
1439     /// Panics if the new element is already linked to a different intrusive
1440     /// collection.
1441     #[inline]
1442     pub fn insert<'c>(&'c mut self, val: <A::PointerOps as PointerOps>::Pointer)
1443     where
1444         <A as KeyAdapter<'c>>::Key: Ord,
1445     {
1446         // We explicitly drop the returned CursorMut here, otherwise we would
1447         // end up with multiple CursorMut in the same collection.
1448         self.tree.insert(val);
1449     }
1450 }
1451 
1452 // =============================================================================
1453 // RBTree
1454 // =============================================================================
1455 
1456 /// An intrusive red-black tree.
1457 ///
1458 /// When this collection is dropped, all elements linked into it will be
1459 /// converted back to owned pointers and dropped.
1460 ///
1461 /// Note that you are responsible for ensuring that the elements in a `RBTree`
1462 /// remain in ascending key order. This property can be violated, either because
1463 /// the key of an element was modified, or because the
1464 /// `insert_before`/`insert_after` methods of `CursorMut` were incorrectly used.
1465 /// If this situation occurs, memory safety will not be violated but the `find`,
1466 /// `upper_bound`, `lower_bound` and `range` may return incorrect results.
1467 pub struct RBTree<A: Adapter>
1468 where
1469     A::LinkOps: RBTreeOps,
1470 {
1471     root: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
1472     adapter: A,
1473 }
1474 
1475 impl<A: Adapter> RBTree<A>
1476 where
1477     A::LinkOps: RBTreeOps,
1478 {
1479     #[inline]
1480     fn node_from_value(
1481         &mut self,
1482         val: <A::PointerOps as PointerOps>::Pointer,
1483     ) -> <A::LinkOps as link_ops::LinkOps>::LinkPtr {
1484         use link_ops::LinkOps;
1485 
1486         unsafe {
1487             let raw = self.adapter.pointer_ops().into_raw(val);
1488             let link = self.adapter.get_link(raw);
1489 
1490             if !self.adapter.link_ops_mut().acquire_link(link) {
1491                 // convert the node back into a pointer
1492                 self.adapter.pointer_ops().from_raw(raw);
1493 
1494                 panic!("attempted to insert an object that is already linked");
1495             }
1496 
1497             link
1498         }
1499     }
1500 
1501     /// Creates an empty `RBTree`.
1502     #[cfg(not(feature = "nightly"))]
1503     #[inline]
1504     pub fn new(adapter: A) -> RBTree<A> {
1505         RBTree {
1506             root: None,
1507             adapter,
1508         }
1509     }
1510 
1511     /// Creates an empty `RBTree`.
1512     #[cfg(feature = "nightly")]
1513     #[inline]
1514     pub const fn new(adapter: A) -> RBTree<A> {
1515         RBTree {
1516             root: None,
1517             adapter,
1518         }
1519     }
1520 
1521     /// Returns `true` if the `RBTree` is empty.
1522     #[inline]
1523     pub fn is_empty(&self) -> bool {
1524         self.root.is_none()
1525     }
1526 
1527     /// Returns a null `Cursor` for this tree.
1528     #[inline]
1529     pub fn cursor(&self) -> Cursor<'_, A> {
1530         Cursor {
1531             current: None,
1532             tree: self,
1533         }
1534     }
1535 
1536     /// Returns a null `CursorMut` for this tree.
1537     #[inline]
1538     pub fn cursor_mut(&mut self) -> CursorMut<'_, A> {
1539         CursorMut {
1540             current: None,
1541             tree: self,
1542         }
1543     }
1544 
1545     /// Creates a `Cursor` from a pointer to an element.
1546     ///
1547     /// # Safety
1548     ///
1549     /// `ptr` must be a pointer to an object that is part of this tree.
1550     #[inline]
1551     pub unsafe fn cursor_from_ptr(
1552         &self,
1553         ptr: *const <A::PointerOps as PointerOps>::Value,
1554     ) -> Cursor<'_, A> {
1555         Cursor {
1556             current: Some(self.adapter.get_link(ptr)),
1557             tree: self,
1558         }
1559     }
1560 
1561     /// Creates a `CursorMut` from a pointer to an element.
1562     ///
1563     /// # Safety
1564     ///
1565     /// `ptr` must be a pointer to an object that is part of this tree.
1566     #[inline]
1567     pub unsafe fn cursor_mut_from_ptr(
1568         &mut self,
1569         ptr: *const <A::PointerOps as PointerOps>::Value,
1570     ) -> CursorMut<'_, A> {
1571         CursorMut {
1572             current: Some(self.adapter.get_link(ptr)),
1573             tree: self,
1574         }
1575     }
1576 
1577     /// Returns a `Cursor` pointing to the first element of the tree. If the
1578     /// tree is empty then a null cursor is returned.
1579     #[inline]
1580     pub fn front(&self) -> Cursor<'_, A> {
1581         let mut cursor = self.cursor();
1582         cursor.move_next();
1583         cursor
1584     }
1585 
1586     /// Returns a `CursorMut` pointing to the first element of the tree. If the
1587     /// the tree is empty then a null cursor is returned.
1588     #[inline]
1589     pub fn front_mut(&mut self) -> CursorMut<'_, A> {
1590         let mut cursor = self.cursor_mut();
1591         cursor.move_next();
1592         cursor
1593     }
1594 
1595     /// Returns a `Cursor` pointing to the last element of the tree. If the tree
1596     /// is empty then a null cursor is returned.
1597     #[inline]
1598     pub fn back(&self) -> Cursor<'_, A> {
1599         let mut cursor = self.cursor();
1600         cursor.move_prev();
1601         cursor
1602     }
1603 
1604     /// Returns a `CursorMut` pointing to the last element of the tree. If the
1605     /// tree is empty then a null cursor is returned.
1606     #[inline]
1607     pub fn back_mut(&mut self) -> CursorMut<'_, A> {
1608         let mut cursor = self.cursor_mut();
1609         cursor.move_prev();
1610         cursor
1611     }
1612 
1613     #[inline]
1614     unsafe fn insert_root(&mut self, node: <A::LinkOps as link_ops::LinkOps>::LinkPtr) {
1615         self.adapter.link_ops_mut().set_parent(node, None);
1616         self.adapter.link_ops_mut().set_color(node, Color::Black);
1617         self.adapter.link_ops_mut().set_left(node, None);
1618         self.adapter.link_ops_mut().set_right(node, None);
1619         self.root = Some(node);
1620     }
1621 
1622     /// Gets an iterator over the objects in the `RBTree`.
1623     #[inline]
1624     pub fn iter(&self) -> Iter<'_, A> {
1625         let link_ops = self.adapter.link_ops();
1626 
1627         if let Some(root) = self.root {
1628             Iter {
1629                 head: Some(unsafe { first_child(link_ops, root) }),
1630                 tail: Some(unsafe { last_child(link_ops, root) }),
1631                 tree: self,
1632             }
1633         } else {
1634             Iter {
1635                 head: None,
1636                 tail: None,
1637                 tree: self,
1638             }
1639         }
1640     }
1641 
1642     #[inline]
1643     fn clear_recurse(&mut self, current: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>) {
1644         use link_ops::LinkOps;
1645         // If adapter.get_value or Pointer::from_raw panic here, it will leak
1646         // the nodes and keep them linked. However this is harmless since there
1647         // is nothing you can do with just a Link.
1648         if let Some(current) = current {
1649             unsafe {
1650                 let left = self.adapter.link_ops_mut().left(current);
1651                 let right = self.adapter.link_ops_mut().right(current);
1652                 self.clear_recurse(left);
1653                 self.clear_recurse(right);
1654                 self.adapter.link_ops_mut().release_link(current);
1655                 self.adapter
1656                     .pointer_ops()
1657                     .from_raw(self.adapter.get_value(current));
1658             }
1659         }
1660     }
1661 
1662     /// Removes all elements from the `RBTree`.
1663     ///
1664     /// This will unlink all object currently in the tree, which requires
1665     /// iterating through all elements in the `RBTree`. Each element is
1666     /// converted back to an owned pointer and then dropped.
1667     #[inline]
1668     pub fn clear(&mut self) {
1669         let root = self.root.take();
1670         self.clear_recurse(root);
1671     }
1672 
1673     /// Empties the `RBTree` without unlinking or freeing objects in it.
1674     ///
1675     /// Since this does not unlink any objects, any attempts to link these
1676     /// objects into another `RBTree` will fail but will not cause any
1677     /// memory unsafety. To unlink those objects manually, you must call the
1678     /// `force_unlink` function on them.
1679     #[inline]
1680     pub fn fast_clear(&mut self) {
1681         self.root = None;
1682     }
1683 
1684     /// Takes all the elements out of the `RBTree`, leaving it empty. The
1685     /// taken elements are returned as a new `RBTree`.
1686     #[inline]
1687     pub fn take(&mut self) -> RBTree<A>
1688     where
1689         A: Clone,
1690     {
1691         let tree = RBTree {
1692             root: self.root,
1693             adapter: self.adapter.clone(),
1694         };
1695         self.root = None;
1696         tree
1697     }
1698 }
1699 
1700 impl<A: for<'a> KeyAdapter<'a>> RBTree<A>
1701 where
1702     <A as Adapter>::LinkOps: RBTreeOps,
1703 {
1704     #[inline]
1705     fn find_internal<'a, Q: ?Sized + Ord>(
1706         &self,
1707         key: &Q,
1708     ) -> Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>
1709     where
1710         <A as KeyAdapter<'a>>::Key: Borrow<Q>,
1711         <A::PointerOps as PointerOps>::Value: 'a,
1712     {
1713         let link_ops = self.adapter.link_ops();
1714 
1715         let mut tree = self.root;
1716         while let Some(x) = tree {
1717             let current = unsafe { &*self.adapter.get_value(x) };
1718             match key.cmp(self.adapter.get_key(current).borrow()) {
1719                 Ordering::Less => tree = unsafe { link_ops.left(x) },
1720                 Ordering::Equal => return tree,
1721                 Ordering::Greater => tree = unsafe { link_ops.right(x) },
1722             }
1723         }
1724         None
1725     }
1726 
1727     /// Returns a `Cursor` pointing to an element with the given key. If no such
1728     /// element is found then a null cursor is returned.
1729     ///
1730     /// If multiple elements with an identical key are found then an arbitrary
1731     /// one is returned.
1732     #[inline]
1733     pub fn find<'a, 'b, Q: ?Sized + Ord>(&'a self, key: &Q) -> Cursor<'a, A>
1734     where
1735         <A as KeyAdapter<'b>>::Key: Borrow<Q>,
1736         'a: 'b,
1737     {
1738         Cursor {
1739             current: self.find_internal(key),
1740             tree: self,
1741         }
1742     }
1743 
1744     /// Returns a `CursorMut` pointing to an element with the given key. If no
1745     /// such element is found then a null cursor is returned.
1746     ///
1747     /// If multiple elements with an identical key are found then an arbitrary
1748     /// one is returned.
1749     #[inline]
1750     pub fn find_mut<'a, 'b, Q: ?Sized + Ord>(&'a mut self, key: &Q) -> CursorMut<'a, A>
1751     where
1752         <A as KeyAdapter<'b>>::Key: Borrow<Q>,
1753         'a: 'b,
1754     {
1755         CursorMut {
1756             current: self.find_internal(key),
1757             tree: self,
1758         }
1759     }
1760 
1761     #[inline]
1762     fn lower_bound_internal<'a, Q: ?Sized + Ord>(
1763         &self,
1764         bound: Bound<&Q>,
1765     ) -> Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>
1766     where
1767         <A as KeyAdapter<'a>>::Key: Borrow<Q>,
1768         <A::PointerOps as PointerOps>::Value: 'a,
1769     {
1770         let link_ops = self.adapter.link_ops();
1771 
1772         let mut tree = self.root;
1773         let mut result = None;
1774         while let Some(x) = tree {
1775             let current = unsafe { &*self.adapter.get_value(x) };
1776             let cond = match bound {
1777                 Unbounded => true,
1778                 Included(key) => key <= self.adapter.get_key(current).borrow(),
1779                 Excluded(key) => key < self.adapter.get_key(current).borrow(),
1780             };
1781             if cond {
1782                 result = tree;
1783                 tree = unsafe { link_ops.left(x) };
1784             } else {
1785                 tree = unsafe { link_ops.right(x) };
1786             }
1787         }
1788         result
1789     }
1790 
1791     /// Returns a `Cursor` pointing to the lowest element whose key is above
1792     /// the given bound. If no such element is found then a null cursor is
1793     /// returned.
1794     #[inline]
1795     pub fn lower_bound<'a, 'b, Q: ?Sized + Ord>(&'a self, bound: Bound<&Q>) -> Cursor<'a, A>
1796     where
1797         <A as KeyAdapter<'b>>::Key: Borrow<Q>,
1798         'a: 'b,
1799     {
1800         Cursor {
1801             current: self.lower_bound_internal(bound),
1802             tree: self,
1803         }
1804     }
1805 
1806     /// Returns a `CursorMut` pointing to the first element whose key is
1807     /// above the given bound. If no such element is found then a null
1808     /// cursor is returned.
1809     #[inline]
1810     pub fn lower_bound_mut<'a, 'b, Q: ?Sized + Ord>(
1811         &'a mut self,
1812         bound: Bound<&Q>,
1813     ) -> CursorMut<'a, A>
1814     where
1815         <A as KeyAdapter<'b>>::Key: Borrow<Q>,
1816         'a: 'b,
1817     {
1818         CursorMut {
1819             current: self.lower_bound_internal(bound),
1820             tree: self,
1821         }
1822     }
1823 
1824     #[inline]
1825     fn upper_bound_internal<'a, Q: ?Sized + Ord>(
1826         &self,
1827         bound: Bound<&Q>,
1828     ) -> Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>
1829     where
1830         <A as KeyAdapter<'a>>::Key: Borrow<Q>,
1831         <A::PointerOps as PointerOps>::Value: 'a,
1832     {
1833         let link_ops = self.adapter.link_ops();
1834 
1835         let mut tree = self.root;
1836         let mut result = None;
1837         while let Some(x) = tree {
1838             let current = unsafe { &*self.adapter.get_value(x) };
1839             let cond = match bound {
1840                 Unbounded => false,
1841                 Included(key) => key < self.adapter.get_key(current).borrow(),
1842                 Excluded(key) => key <= self.adapter.get_key(current).borrow(),
1843             };
1844             if cond {
1845                 tree = unsafe { link_ops.left(x) };
1846             } else {
1847                 result = tree;
1848                 tree = unsafe { link_ops.right(x) };
1849             }
1850         }
1851         result
1852     }
1853 
1854     /// Returns a `Cursor` pointing to the last element whose key is below
1855     /// the given bound. If no such element is found then a null cursor is
1856     /// returned.
1857     #[inline]
1858     pub fn upper_bound<'a, 'b, Q: ?Sized + Ord>(&'a self, bound: Bound<&Q>) -> Cursor<'a, A>
1859     where
1860         <A as KeyAdapter<'b>>::Key: Borrow<Q>,
1861         'a: 'b,
1862     {
1863         Cursor {
1864             current: self.upper_bound_internal(bound),
1865             tree: self,
1866         }
1867     }
1868 
1869     /// Returns a `CursorMut` pointing to the last element whose key is
1870     /// below the given bound. If no such element is found then a null
1871     /// cursor is returned.
1872     #[inline]
1873     pub fn upper_bound_mut<'a, 'b, Q: ?Sized + Ord>(
1874         &'a mut self,
1875         bound: Bound<&Q>,
1876     ) -> CursorMut<'a, A>
1877     where
1878         <A as KeyAdapter<'b>>::Key: Borrow<Q>,
1879         'a: 'b,
1880     {
1881         CursorMut {
1882             current: self.upper_bound_internal(bound),
1883             tree: self,
1884         }
1885     }
1886 
1887     /// Inserts a new element into the `RBTree`.
1888     ///
1889     /// The new element will be inserted at the correct position in the tree
1890     /// based on its key.
1891     ///
1892     /// Returns a mutable cursor pointing to the newly added element.
1893     ///
1894     /// # Panics
1895     ///
1896     /// Panics if the new element is already linked to a different intrusive
1897     /// collection.
1898     #[inline]
1899     pub fn insert<'a>(&'a mut self, val: <A::PointerOps as PointerOps>::Pointer) -> CursorMut<'_, A>
1900     where
1901         <A as KeyAdapter<'a>>::Key: Ord,
1902     {
1903         unsafe {
1904             let new = self.node_from_value(val);
1905             let raw = self.adapter.get_value(new);
1906             if let Some(root) = self.root {
1907                 let key = self.adapter.get_key(&*raw);
1908                 let mut tree = root;
1909                 loop {
1910                     let current = &*self.adapter.get_value(tree);
1911                     if key < self.adapter.get_key(current) {
1912                         if let Some(left) = self.adapter.link_ops().left(tree) {
1913                             tree = left;
1914                         } else {
1915                             insert_left(self.adapter.link_ops_mut(), tree, new, &mut self.root);
1916                             break;
1917                         }
1918                     } else {
1919                         if let Some(right) = self.adapter.link_ops().right(tree) {
1920                             tree = right;
1921                         } else {
1922                             insert_right(self.adapter.link_ops_mut(), tree, new, &mut self.root);
1923                             break;
1924                         }
1925                     }
1926                 }
1927             } else {
1928                 self.insert_root(new);
1929             }
1930             CursorMut {
1931                 current: Some(new),
1932                 tree: self,
1933             }
1934         }
1935     }
1936 
1937     /// Returns an `Entry` for the given key which contains a `CursorMut` to an
1938     /// element with the given key or an `InsertCursor` which points to a place
1939     /// in which to insert a new element with the given key.
1940     ///
1941     /// This is more efficient than calling `find` followed by `insert` since
1942     /// the tree does not have to be searched a second time to find a place to
1943     /// insert the new element.
1944     ///
1945     /// If multiple elements with an identical key are found then an arbitrary
1946     /// one is returned.
1947     #[inline]
1948     pub fn entry<'a, Q: ?Sized + Ord>(&'a mut self, key: &Q) -> Entry<'a, A>
1949     where
1950         <A as KeyAdapter<'a>>::Key: Borrow<Q>,
1951     {
1952         unsafe {
1953             if let Some(root) = self.root {
1954                 let mut tree = root;
1955                 loop {
1956                     let current = &*self.adapter.get_value(tree);
1957                     match key.cmp(self.adapter.get_key(current).borrow()) {
1958                         Ordering::Less => {
1959                             if let Some(left) = self.adapter.link_ops().left(tree) {
1960                                 tree = left;
1961                             } else {
1962                                 return Entry::Vacant(InsertCursor {
1963                                     parent: Some(tree),
1964                                     insert_left: true,
1965                                     tree: self,
1966                                 });
1967                             }
1968                         }
1969                         Ordering::Equal => {
1970                             return Entry::Occupied(CursorMut {
1971                                 current: Some(tree),
1972                                 tree: self,
1973                             });
1974                         }
1975                         Ordering::Greater => {
1976                             if let Some(right) = self.adapter.link_ops().right(tree) {
1977                                 tree = right;
1978                             } else {
1979                                 return Entry::Vacant(InsertCursor {
1980                                     parent: Some(tree),
1981                                     insert_left: false,
1982                                     tree: self,
1983                                 });
1984                             }
1985                         }
1986                     }
1987                 }
1988             } else {
1989                 Entry::Vacant(InsertCursor {
1990                     parent: None,
1991                     insert_left: false,
1992                     tree: self,
1993                 })
1994             }
1995         }
1996     }
1997 
1998     /// Constructs a double-ended iterator over a sub-range of elements in the
1999     /// tree, starting at min, and ending at max. If min is `Unbounded`, then it
2000     /// will be treated as "negative infinity", and if max is `Unbounded`, then
2001     /// it will be treated as "positive infinity". Thus
2002     /// `range(Unbounded, Unbounded)` will yield the whole collection.
2003     #[inline]
2004     pub fn range<'a, Min: ?Sized + Ord, Max: ?Sized + Ord>(
2005         &'a self,
2006         min: Bound<&Min>,
2007         max: Bound<&Max>,
2008     ) -> Iter<'a, A>
2009     where
2010         <A as KeyAdapter<'a>>::Key: Borrow<Min> + Borrow<Max>,
2011         <A as KeyAdapter<'a>>::Key: Ord,
2012     {
2013         let lower = self.lower_bound_internal(min);
2014         let upper = self.upper_bound_internal(max);
2015 
2016         if let (Some(lower), Some(upper)) = (lower, upper) {
2017             let lower_key = unsafe { self.adapter.get_key(&*self.adapter.get_value(lower)) };
2018             let upper_key = unsafe { self.adapter.get_key(&*self.adapter.get_value(upper)) };
2019             if upper_key >= lower_key {
2020                 return Iter {
2021                     head: Some(lower),
2022                     tail: Some(upper),
2023                     tree: self,
2024                 };
2025             }
2026         }
2027         Iter {
2028             head: None,
2029             tail: None,
2030             tree: self,
2031         }
2032     }
2033 }
2034 
2035 // Allow read-only access to values from multiple threads
2036 unsafe impl<A: Adapter + Sync> Sync for RBTree<A>
2037 where
2038     <A::PointerOps as PointerOps>::Value: Sync,
2039     A::LinkOps: RBTreeOps,
2040 {
2041 }
2042 
2043 // Allow sending to another thread if the ownership (represented by the <A::PointerOps as PointerOps>::Pointer owned
2044 // pointer type) can be transferred to another thread.
2045 unsafe impl<A: Adapter + Send> Send for RBTree<A>
2046 where
2047     <A::PointerOps as PointerOps>::Pointer: Send,
2048     A::LinkOps: RBTreeOps,
2049 {
2050 }
2051 
2052 // Drop all owned pointers if the collection is dropped
2053 impl<A: Adapter> Drop for RBTree<A>
2054 where
2055     A::LinkOps: RBTreeOps,
2056 {
2057     #[inline]
drop(&mut self)2058     fn drop(&mut self) {
2059         self.clear();
2060     }
2061 }
2062 
2063 impl<A: Adapter> IntoIterator for RBTree<A>
2064 where
2065     A::LinkOps: RBTreeOps,
2066 {
2067     type Item = <A::PointerOps as PointerOps>::Pointer;
2068     type IntoIter = IntoIter<A>;
2069 
2070     #[inline]
into_iter(self) -> IntoIter<A>2071     fn into_iter(self) -> IntoIter<A> {
2072         let link_ops = self.adapter.link_ops();
2073 
2074         if let Some(root) = self.root {
2075             IntoIter {
2076                 head: Some(unsafe { first_child(link_ops, root) }),
2077                 tail: Some(unsafe { last_child(link_ops, root) }),
2078                 tree: self,
2079             }
2080         } else {
2081             IntoIter {
2082                 head: None,
2083                 tail: None,
2084                 tree: self,
2085             }
2086         }
2087     }
2088 }
2089 
2090 impl<'a, A: Adapter + 'a> IntoIterator for &'a RBTree<A>
2091 where
2092     A::LinkOps: RBTreeOps,
2093 {
2094     type Item = &'a <A::PointerOps as PointerOps>::Value;
2095     type IntoIter = Iter<'a, A>;
2096 
2097     #[inline]
into_iter(self) -> Iter<'a, A>2098     fn into_iter(self) -> Iter<'a, A> {
2099         self.iter()
2100     }
2101 }
2102 
2103 impl<A: Adapter + Default> Default for RBTree<A>
2104 where
2105     A::LinkOps: RBTreeOps,
2106 {
default() -> RBTree<A>2107     fn default() -> RBTree<A> {
2108         RBTree::new(A::default())
2109     }
2110 }
2111 
2112 impl<A: Adapter> fmt::Debug for RBTree<A>
2113 where
2114     A::LinkOps: RBTreeOps,
2115     <A::PointerOps as PointerOps>::Value: fmt::Debug,
2116 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result2117     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2118         f.debug_set().entries(self.iter()).finish()
2119     }
2120 }
2121 
2122 // =============================================================================
2123 // InsertCursor, Entry
2124 // =============================================================================
2125 
2126 /// A cursor pointing to a slot in which an element can be inserted into a
2127 /// `RBTree`.
2128 pub struct InsertCursor<'a, A: Adapter>
2129 where
2130     A::LinkOps: RBTreeOps,
2131 {
2132     parent: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
2133     insert_left: bool,
2134     tree: &'a mut RBTree<A>,
2135 }
2136 
2137 impl<'a, A: Adapter + 'a> InsertCursor<'a, A>
2138 where
2139     A::LinkOps: RBTreeOps,
2140 {
2141     /// Inserts a new element into the `RBTree` at the location indicated by
2142     /// this `InsertCursor`.
2143     ///
2144     /// # Panics
2145     ///
2146     /// Panics if the new element is already linked to a different intrusive
2147     /// collection.
2148     pub fn insert(self, val: <A::PointerOps as PointerOps>::Pointer) -> CursorMut<'a, A> {
2149         unsafe {
2150             let new = self.tree.node_from_value(val);
2151             let link_ops = self.tree.adapter.link_ops_mut();
2152             if let Some(parent) = self.parent {
2153                 if self.insert_left {
2154                     insert_left(link_ops, parent, new, &mut self.tree.root);
2155                 } else {
2156                     insert_right(link_ops, parent, new, &mut self.tree.root);
2157                 }
2158             } else {
2159                 self.tree.insert_root(new);
2160             }
2161             CursorMut {
2162                 current: Some(new),
2163                 tree: self.tree,
2164             }
2165         }
2166     }
2167 }
2168 
2169 /// An entry in a `RBTree`.
2170 ///
2171 /// See the documentation for `RBTree::entry`.
2172 pub enum Entry<'a, A: Adapter>
2173 where
2174     A::LinkOps: RBTreeOps,
2175 {
2176     /// An occupied entry.
2177     Occupied(CursorMut<'a, A>),
2178 
2179     /// A vacant entry.
2180     Vacant(InsertCursor<'a, A>),
2181 }
2182 
2183 impl<'a, A: Adapter + 'a> Entry<'a, A>
2184 where
2185     A::LinkOps: RBTreeOps,
2186 {
2187     /// Inserts an element into the `RBTree` if the entry is vacant, returning
2188     /// a `CursorMut` to the resulting value. If the entry is occupied then a
2189     /// `CursorMut` pointing to the element is returned.
2190     ///
2191     /// # Panics
2192     ///
2193     /// Panics if the `Entry` is vacant and the new element is already linked to
2194     /// a different intrusive collection.
2195     pub fn or_insert(self, val: <A::PointerOps as PointerOps>::Pointer) -> CursorMut<'a, A> {
2196         match self {
2197             Entry::Occupied(entry) => entry,
2198             Entry::Vacant(entry) => entry.insert(val),
2199         }
2200     }
2201 
2202     /// Calls the given function and inserts the result into the `RBTree` if the
2203     /// entry is vacant, returning a `CursorMut` to the resulting value. If the
2204     /// entry is occupied then a `CursorMut` pointing to the element is
2205     /// returned and the function is not executed.
2206     ///
2207     /// # Panics
2208     ///
2209     /// Panics if the `Entry` is vacant and the new element is already linked to
2210     /// a different intrusive collection.
2211     pub fn or_insert_with<F>(self, default: F) -> CursorMut<'a, A>
2212     where
2213         F: FnOnce() -> <A::PointerOps as PointerOps>::Pointer,
2214     {
2215         match self {
2216             Entry::Occupied(entry) => entry,
2217             Entry::Vacant(entry) => entry.insert(default()),
2218         }
2219     }
2220 }
2221 
2222 // =============================================================================
2223 // Iter
2224 // =============================================================================
2225 
2226 /// An iterator over references to the items of a `RBTree`.
2227 pub struct Iter<'a, A: Adapter>
2228 where
2229     A::LinkOps: RBTreeOps,
2230 {
2231     head: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
2232     tail: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
2233     tree: &'a RBTree<A>,
2234 }
2235 impl<'a, A: Adapter + 'a> Iterator for Iter<'a, A>
2236 where
2237     A::LinkOps: RBTreeOps,
2238 {
2239     type Item = &'a <A::PointerOps as PointerOps>::Value;
2240 
2241     #[inline]
2242     fn next(&mut self) -> Option<&'a <A::PointerOps as PointerOps>::Value> {
2243         let head = self.head?;
2244 
2245         if Some(head) == self.tail {
2246             self.head = None;
2247             self.tail = None;
2248         } else {
2249             self.head = unsafe { next(self.tree.adapter.link_ops(), head) };
2250         }
2251         Some(unsafe { &*self.tree.adapter.get_value(head) })
2252     }
2253 }
2254 impl<'a, A: Adapter + 'a> DoubleEndedIterator for Iter<'a, A>
2255 where
2256     A::LinkOps: RBTreeOps,
2257 {
2258     #[inline]
2259     fn next_back(&mut self) -> Option<&'a <A::PointerOps as PointerOps>::Value> {
2260         let tail = self.tail?;
2261 
2262         if Some(tail) == self.head {
2263             self.head = None;
2264             self.tail = None;
2265         } else {
2266             self.tail = unsafe { prev(self.tree.adapter.link_ops(), tail) };
2267         }
2268         Some(unsafe { &*self.tree.adapter.get_value(tail) })
2269     }
2270 }
2271 impl<'a, A: Adapter + 'a> Clone for Iter<'a, A>
2272 where
2273     A::LinkOps: RBTreeOps,
2274 {
2275     #[inline]
2276     fn clone(&self) -> Iter<'a, A> {
2277         Iter {
2278             head: self.head,
2279             tail: self.tail,
2280             tree: self.tree,
2281         }
2282     }
2283 }
2284 
2285 // =============================================================================
2286 // IntoIter
2287 // =============================================================================
2288 
2289 /// An iterator which consumes a `RBTree`.
2290 pub struct IntoIter<A: Adapter>
2291 where
2292     A::LinkOps: RBTreeOps,
2293 {
2294     head: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
2295     tail: Option<<A::LinkOps as link_ops::LinkOps>::LinkPtr>,
2296     tree: RBTree<A>,
2297 }
2298 impl<A: Adapter> Iterator for IntoIter<A>
2299 where
2300     A::LinkOps: RBTreeOps,
2301 {
2302     type Item = <A::PointerOps as PointerOps>::Pointer;
2303 
2304     #[inline]
2305     fn next(&mut self) -> Option<<A::PointerOps as PointerOps>::Pointer> {
2306         use link_ops::LinkOps;
2307 
2308         let head = self.head?;
2309         let link_ops = self.tree.adapter.link_ops_mut();
2310         unsafe {
2311             // Remove the node from the tree. Since head is always the
2312             // left-most node, we can infer the following:
2313             // - head.left is null.
2314             // - head is a left child of its parent (or the root node).
2315             if let Some(parent) = link_ops.parent(head) {
2316                 link_ops.set_left(parent, link_ops.right(head));
2317             } else {
2318                 self.tree.root = link_ops.right(head);
2319                 if link_ops.right(head).is_none() {
2320                     self.tail = None;
2321                 }
2322             }
2323             if let Some(right) = link_ops.right(head) {
2324                 link_ops.set_parent(right, link_ops.parent(head));
2325                 self.head = Some(first_child(link_ops, right));
2326             } else {
2327                 self.head = link_ops.parent(head);
2328             }
2329             link_ops.release_link(head);
2330             Some(
2331                 self.tree
2332                     .adapter
2333                     .pointer_ops()
2334                     .from_raw(self.tree.adapter.get_value(head)),
2335             )
2336         }
2337     }
2338 }
2339 impl<A: Adapter> DoubleEndedIterator for IntoIter<A>
2340 where
2341     A::LinkOps: RBTreeOps,
2342 {
2343     #[inline]
2344     fn next_back(&mut self) -> Option<<A::PointerOps as PointerOps>::Pointer> {
2345         use link_ops::LinkOps;
2346 
2347         let tail = self.tail?;
2348         let link_ops = self.tree.adapter.link_ops_mut();
2349         unsafe {
2350             // Remove the node from the tree. Since tail is always the
2351             // right-most node, we can infer the following:
2352             // - tail.right is null.
2353             // - tail is a right child of its parent (or the root node).
2354             if let Some(parent) = link_ops.parent(tail) {
2355                 link_ops.set_right(parent, link_ops.left(tail));
2356             } else {
2357                 self.tree.root = link_ops.left(tail);
2358                 if link_ops.left(tail).is_none() {
2359                     self.tail = None;
2360                 }
2361             }
2362             if let Some(left) = link_ops.left(tail) {
2363                 link_ops.set_parent(left, link_ops.parent(tail));
2364                 self.tail = Some(last_child(link_ops, left));
2365             } else {
2366                 self.tail = link_ops.parent(tail);
2367             }
2368             link_ops.release_link(tail);
2369             Some(
2370                 self.tree
2371                     .adapter
2372                     .pointer_ops()
2373                     .from_raw(self.tree.adapter.get_value(tail)),
2374             )
2375         }
2376     }
2377 }
2378 
2379 // =============================================================================
2380 // Tests
2381 // =============================================================================
2382 
2383 #[cfg(test)]
2384 mod tests {
2385     use super::{Entry, KeyAdapter, Link, PointerOps, RBTree};
2386     use crate::Bound::*;
2387     use rand::prelude::*;
2388     use rand_xorshift::XorShiftRng;
2389     use std::fmt;
2390     use std::rc::Rc;
2391     use std::vec::Vec;
2392     use std::{format, vec};
2393 
2394     #[derive(Clone)]
2395     struct Obj {
2396         link: Link,
2397         value: i32,
2398     }
2399     impl fmt::Debug for Obj {
2400         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2401             write!(f, "{}", self.value)
2402         }
2403     }
2404     intrusive_adapter!(ObjAdapter = Rc<Obj>: Obj { link: Link });
2405     impl<'a> KeyAdapter<'a> for ObjAdapter {
2406         type Key = i32;
2407         fn get_key(&self, value: &'a <Self::PointerOps as PointerOps>::Value) -> i32 {
2408             value.value
2409         }
2410     }
2411     fn make_obj(value: i32) -> Rc<Obj> {
2412         Rc::new(Obj {
2413             link: Link::new(),
2414             value,
2415         })
2416     }
2417 
2418     #[test]
2419     fn test_link() {
2420         let a = make_obj(1);
2421         assert!(!a.link.is_linked());
2422         assert_eq!(format!("{:?}", a.link), "unlinked");
2423 
2424         let mut b = RBTree::<ObjAdapter>::default();
2425         assert!(b.is_empty());
2426 
2427         assert_eq!(b.insert(a.clone()).get().unwrap().value, 1);
2428         assert!(!b.is_empty());
2429         assert!(a.link.is_linked());
2430         assert_eq!(format!("{:?}", a.link), "linked");
2431 
2432         let c = a.as_ref().clone();
2433         assert!(!c.link.is_linked());
2434 
2435         unsafe {
2436             assert_eq!(b.cursor_from_ptr(a.as_ref()).get().unwrap().value, 1);
2437             assert_eq!(b.cursor_mut_from_ptr(a.as_ref()).get().unwrap().value, 1);
2438         }
2439 
2440         assert_eq!(
2441             b.front_mut().remove().unwrap().as_ref() as *const _,
2442             a.as_ref() as *const _
2443         );
2444         assert!(b.is_empty());
2445         assert!(!a.link.is_linked());
2446     }
2447 
2448     #[test]
2449     fn test_cursor() {
2450         let a = make_obj(1);
2451         let b = make_obj(2);
2452         let c = make_obj(3);
2453         let mut t = RBTree::new(ObjAdapter::new());
2454         let mut cur = t.cursor_mut();
2455         assert!(cur.is_null());
2456         assert!(cur.get().is_none());
2457         assert!(cur.remove().is_none());
2458 
2459         cur.insert_before(a.clone());
2460         cur.insert_before(c.clone());
2461         cur.move_prev();
2462         cur.insert(b.clone());
2463         assert!(cur.peek_next().is_null());
2464         cur.move_next();
2465         assert!(cur.is_null());
2466 
2467         cur.move_next();
2468         assert!(cur.peek_prev().is_null());
2469         assert!(!cur.is_null());
2470         assert_eq!(cur.get().unwrap() as *const _, a.as_ref() as *const _);
2471 
2472         {
2473             let mut cur2 = cur.as_cursor();
2474             assert_eq!(cur2.get().unwrap() as *const _, a.as_ref() as *const _);
2475             assert_eq!(cur2.peek_next().get().unwrap().value, 2);
2476             cur2.move_next();
2477             assert_eq!(cur2.get().unwrap().value, 2);
2478             cur2.move_next();
2479             assert_eq!(cur2.peek_prev().get().unwrap().value, 2);
2480             assert_eq!(cur2.get().unwrap() as *const _, c.as_ref() as *const _);
2481             cur2.move_prev();
2482             assert_eq!(cur2.get().unwrap() as *const _, b.as_ref() as *const _);
2483             cur2.move_next();
2484             assert_eq!(cur2.get().unwrap() as *const _, c.as_ref() as *const _);
2485             cur2.move_next();
2486             assert!(cur2.is_null());
2487             assert!(cur2.clone().get().is_none());
2488         }
2489         assert_eq!(cur.get().unwrap() as *const _, a.as_ref() as *const _);
2490 
2491         let a2 = make_obj(1);
2492         let b2 = make_obj(2);
2493         let c2 = make_obj(3);
2494         assert_eq!(
2495             cur.replace_with(a2).unwrap().as_ref() as *const _,
2496             a.as_ref() as *const _
2497         );
2498         assert!(!a.link.is_linked());
2499         cur.move_next();
2500         assert_eq!(
2501             cur.replace_with(b2).unwrap().as_ref() as *const _,
2502             b.as_ref() as *const _
2503         );
2504         assert!(!b.link.is_linked());
2505         cur.move_next();
2506         assert_eq!(
2507             cur.replace_with(c2).unwrap().as_ref() as *const _,
2508             c.as_ref() as *const _
2509         );
2510         assert!(!c.link.is_linked());
2511         cur.move_next();
2512         assert_eq!(
2513             cur.replace_with(c.clone()).unwrap_err().as_ref() as *const _,
2514             c.as_ref() as *const _
2515         );
2516     }
2517 
2518     #[cfg(not(miri))]
2519     #[test]
2520     fn test_insert_remove() {
2521         let v = (0..100).map(make_obj).collect::<Vec<_>>();
2522         assert!(v.iter().all(|x| !x.link.is_linked()));
2523         let mut t = RBTree::new(ObjAdapter::new());
2524         assert!(t.is_empty());
2525         let mut rng = XorShiftRng::seed_from_u64(0);
2526 
2527         {
2528             let mut expected = Vec::new();
2529             for x in v.iter() {
2530                 t.insert(x.clone());
2531                 expected.push(x.value);
2532                 assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
2533             }
2534 
2535             while let Some(x) = t.front_mut().remove() {
2536                 assert_eq!(x.value, expected.remove(0));
2537                 assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
2538             }
2539             assert!(expected.is_empty());
2540             assert!(t.is_empty());
2541         }
2542 
2543         {
2544             let mut expected = Vec::new();
2545             for x in v.iter().rev() {
2546                 t.insert(x.clone());
2547                 expected.insert(0, x.value);
2548                 assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
2549             }
2550 
2551             while let Some(x) = t.back_mut().remove() {
2552                 assert_eq!(x.value, expected.pop().unwrap());
2553                 assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
2554             }
2555             assert!(expected.is_empty());
2556             assert!(t.is_empty());
2557         }
2558 
2559         {
2560             let mut indices = (0..v.len()).collect::<Vec<_>>();
2561             indices.shuffle(&mut rng);
2562             let mut expected = Vec::new();
2563             for i in indices {
2564                 t.insert(v[i].clone());
2565                 expected.push(v[i].value);
2566                 expected[..].sort_unstable();
2567                 assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
2568             }
2569 
2570             while !expected.is_empty() {
2571                 {
2572                     let index = rng.gen_range(0..expected.len());
2573                     let mut c = t.cursor_mut();
2574                     for _ in 0..(index + 1) {
2575                         c.move_next();
2576                     }
2577                     assert_eq!(c.remove().unwrap().value, expected.remove(index));
2578                 }
2579                 assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
2580             }
2581             assert!(t.is_empty());
2582         }
2583 
2584         {
2585             let mut indices = (0..v.len()).collect::<Vec<_>>();
2586             indices.shuffle(&mut rng);
2587             let mut expected = Vec::new();
2588             for i in indices {
2589                 {
2590                     let mut c = t.front_mut();
2591                     loop {
2592                         if let Some(x) = c.get() {
2593                             if x.value > v[i].value {
2594                                 break;
2595                             }
2596                         } else {
2597                             break;
2598                         }
2599                         c.move_next();
2600                     }
2601                     c.insert_before(v[i].clone());
2602                 }
2603                 expected.push(v[i].value);
2604                 expected[..].sort_unstable();
2605                 assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
2606             }
2607 
2608             t.clear();
2609             assert!(t.is_empty());
2610         }
2611 
2612         {
2613             let mut indices = (0..v.len()).collect::<Vec<_>>();
2614             indices.shuffle(&mut rng);
2615             let mut expected = Vec::new();
2616             for i in indices {
2617                 {
2618                     let mut c = t.back_mut();
2619                     loop {
2620                         if let Some(x) = c.get() {
2621                             if x.value < v[i].value {
2622                                 break;
2623                             }
2624                         } else {
2625                             break;
2626                         }
2627                         c.move_prev();
2628                     }
2629                     c.insert_after(v[i].clone());
2630                 }
2631                 expected.push(v[i].value);
2632                 expected[..].sort_unstable();
2633                 assert_eq!(t.iter().map(|x| x.value).collect::<Vec<_>>(), expected);
2634             }
2635         }
2636     }
2637 
2638     #[cfg(not(miri))]
2639     #[test]
2640     fn test_iter() {
2641         let v = (0..10).map(|x| make_obj(x * 10)).collect::<Vec<_>>();
2642         let mut t = RBTree::new(ObjAdapter::new());
2643         for x in v.iter() {
2644             t.insert(x.clone());
2645         }
2646 
2647         assert_eq!(
2648             format!("{:?}", t),
2649             "{0, 10, 20, 30, 40, 50, 60, 70, 80, 90}"
2650         );
2651 
2652         assert_eq!(
2653             t.iter().clone().map(|x| x.value).collect::<Vec<_>>(),
2654             vec![0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
2655         );
2656         assert_eq!(
2657             (&t).into_iter().rev().map(|x| x.value).collect::<Vec<_>>(),
2658             vec![90, 80, 70, 60, 50, 40, 30, 20, 10, 0]
2659         );
2660         assert_eq!(
2661             t.range(Unbounded, Unbounded)
2662                 .map(|x| x.value)
2663                 .collect::<Vec<_>>(),
2664             vec![0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
2665         );
2666 
2667         assert_eq!(
2668             t.range(Included(&0), Unbounded)
2669                 .map(|x| x.value)
2670                 .collect::<Vec<_>>(),
2671             vec![0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
2672         );
2673         assert_eq!(
2674             t.range(Excluded(&0), Unbounded)
2675                 .map(|x| x.value)
2676                 .collect::<Vec<_>>(),
2677             vec![10, 20, 30, 40, 50, 60, 70, 80, 90]
2678         );
2679         assert_eq!(
2680             t.range(Included(&25), Unbounded)
2681                 .map(|x| x.value)
2682                 .collect::<Vec<_>>(),
2683             vec![30, 40, 50, 60, 70, 80, 90]
2684         );
2685         assert_eq!(
2686             t.range(Excluded(&25), Unbounded)
2687                 .map(|x| x.value)
2688                 .collect::<Vec<_>>(),
2689             vec![30, 40, 50, 60, 70, 80, 90]
2690         );
2691         assert_eq!(
2692             t.range(Included(&70), Unbounded)
2693                 .map(|x| x.value)
2694                 .collect::<Vec<_>>(),
2695             vec![70, 80, 90]
2696         );
2697         assert_eq!(
2698             t.range(Excluded(&70), Unbounded)
2699                 .map(|x| x.value)
2700                 .collect::<Vec<_>>(),
2701             vec![80, 90]
2702         );
2703         assert_eq!(
2704             t.range(Included(&100), Unbounded)
2705                 .map(|x| x.value)
2706                 .collect::<Vec<_>>(),
2707             vec![]
2708         );
2709         assert_eq!(
2710             t.range(Excluded(&100), Unbounded)
2711                 .map(|x| x.value)
2712                 .collect::<Vec<_>>(),
2713             vec![]
2714         );
2715 
2716         assert_eq!(
2717             t.range(Unbounded, Included(&90))
2718                 .map(|x| x.value)
2719                 .collect::<Vec<_>>(),
2720             vec![0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
2721         );
2722         assert_eq!(
2723             t.range(Unbounded, Excluded(&90))
2724                 .map(|x| x.value)
2725                 .collect::<Vec<_>>(),
2726             vec![0, 10, 20, 30, 40, 50, 60, 70, 80]
2727         );
2728         assert_eq!(
2729             t.range(Unbounded, Included(&25))
2730                 .map(|x| x.value)
2731                 .collect::<Vec<_>>(),
2732             vec![0, 10, 20]
2733         );
2734         assert_eq!(
2735             t.range(Unbounded, Excluded(&25))
2736                 .map(|x| x.value)
2737                 .collect::<Vec<_>>(),
2738             vec![0, 10, 20]
2739         );
2740         assert_eq!(
2741             t.range(Unbounded, Included(&70))
2742                 .map(|x| x.value)
2743                 .collect::<Vec<_>>(),
2744             vec![0, 10, 20, 30, 40, 50, 60, 70]
2745         );
2746         assert_eq!(
2747             t.range(Unbounded, Excluded(&70))
2748                 .map(|x| x.value)
2749                 .collect::<Vec<_>>(),
2750             vec![0, 10, 20, 30, 40, 50, 60]
2751         );
2752         assert_eq!(
2753             t.range(Unbounded, Included(&-1))
2754                 .map(|x| x.value)
2755                 .collect::<Vec<_>>(),
2756             vec![]
2757         );
2758         assert_eq!(
2759             t.range(Unbounded, Excluded(&-1))
2760                 .map(|x| x.value)
2761                 .collect::<Vec<_>>(),
2762             vec![]
2763         );
2764 
2765         assert_eq!(
2766             t.range(Included(&25), Included(&80))
2767                 .map(|x| x.value)
2768                 .collect::<Vec<_>>(),
2769             vec![30, 40, 50, 60, 70, 80]
2770         );
2771         assert_eq!(
2772             t.range(Included(&25), Excluded(&80))
2773                 .map(|x| x.value)
2774                 .collect::<Vec<_>>(),
2775             vec![30, 40, 50, 60, 70]
2776         );
2777         assert_eq!(
2778             t.range(Excluded(&25), Included(&80))
2779                 .map(|x| x.value)
2780                 .collect::<Vec<_>>(),
2781             vec![30, 40, 50, 60, 70, 80]
2782         );
2783         assert_eq!(
2784             t.range(Excluded(&25), Excluded(&80))
2785                 .map(|x| x.value)
2786                 .collect::<Vec<_>>(),
2787             vec![30, 40, 50, 60, 70]
2788         );
2789 
2790         assert_eq!(
2791             t.range(Included(&25), Included(&25))
2792                 .map(|x| x.value)
2793                 .collect::<Vec<_>>(),
2794             vec![]
2795         );
2796         assert_eq!(
2797             t.range(Included(&25), Excluded(&25))
2798                 .map(|x| x.value)
2799                 .collect::<Vec<_>>(),
2800             vec![]
2801         );
2802         assert_eq!(
2803             t.range(Excluded(&25), Included(&25))
2804                 .map(|x| x.value)
2805                 .collect::<Vec<_>>(),
2806             vec![]
2807         );
2808         assert_eq!(
2809             t.range(Excluded(&25), Excluded(&25))
2810                 .map(|x| x.value)
2811                 .collect::<Vec<_>>(),
2812             vec![]
2813         );
2814 
2815         assert_eq!(
2816             t.range(Included(&50), Included(&50))
2817                 .map(|x| x.value)
2818                 .collect::<Vec<_>>(),
2819             vec![50]
2820         );
2821         assert_eq!(
2822             t.range(Included(&50), Excluded(&50))
2823                 .map(|x| x.value)
2824                 .collect::<Vec<_>>(),
2825             vec![]
2826         );
2827         assert_eq!(
2828             t.range(Excluded(&50), Included(&50))
2829                 .map(|x| x.value)
2830                 .collect::<Vec<_>>(),
2831             vec![]
2832         );
2833         assert_eq!(
2834             t.range(Excluded(&50), Excluded(&50))
2835                 .map(|x| x.value)
2836                 .collect::<Vec<_>>(),
2837             vec![]
2838         );
2839 
2840         assert_eq!(
2841             t.range(Included(&100), Included(&-2))
2842                 .map(|x| x.value)
2843                 .collect::<Vec<_>>(),
2844             vec![]
2845         );
2846         assert_eq!(
2847             t.range(Included(&100), Excluded(&-2))
2848                 .map(|x| x.value)
2849                 .collect::<Vec<_>>(),
2850             vec![]
2851         );
2852         assert_eq!(
2853             t.range(Excluded(&100), Included(&-2))
2854                 .map(|x| x.value)
2855                 .collect::<Vec<_>>(),
2856             vec![]
2857         );
2858         assert_eq!(
2859             t.range(Excluded(&100), Excluded(&-2))
2860                 .map(|x| x.value)
2861                 .collect::<Vec<_>>(),
2862             vec![]
2863         );
2864 
2865         let mut v2 = Vec::new();
2866         for x in t.take() {
2867             v2.push(x.value);
2868         }
2869         assert_eq!(v2, vec![0, 10, 20, 30, 40, 50, 60, 70, 80, 90]);
2870         assert!(t.is_empty());
2871         for _ in t.take() {
2872             unreachable!();
2873         }
2874 
2875         for x in v.iter() {
2876             t.insert(x.clone());
2877         }
2878         v2.clear();
2879         for x in t.into_iter().rev() {
2880             v2.push(x.value);
2881         }
2882         assert_eq!(v2, vec![90, 80, 70, 60, 50, 40, 30, 20, 10, 0]);
2883     }
2884 
2885     #[test]
2886     fn test_find() {
2887         let v = (0..10).map(|x| make_obj(x * 10)).collect::<Vec<_>>();
2888         let mut t = RBTree::new(ObjAdapter::new());
2889         for x in v.iter() {
2890             t.insert(x.clone());
2891         }
2892 
2893         for i in -9..100 {
2894             fn mod10(x: i32) -> i32 {
2895                 if x < 0 {
2896                     10 + x % 10
2897                 } else {
2898                     x % 10
2899                 }
2900             }
2901             {
2902                 let c = t.find(&i);
2903                 assert_eq!(
2904                     c.get().map(|x| x.value),
2905                     if i % 10 == 0 { Some(i) } else { None }
2906                 );
2907             }
2908             {
2909                 let c = t.find_mut(&i);
2910                 assert_eq!(
2911                     c.get().map(|x| x.value),
2912                     if i % 10 == 0 { Some(i) } else { None }
2913                 );
2914             }
2915             {
2916                 let c = t.upper_bound(Unbounded);
2917                 assert_eq!(c.get().map(|x| x.value), Some(90));
2918             }
2919             {
2920                 let c = t.upper_bound_mut(Unbounded);
2921                 assert_eq!(c.get().map(|x| x.value), Some(90));
2922             }
2923             {
2924                 let c = t.upper_bound(Included(&i));
2925                 assert_eq!(
2926                     c.get().map(|x| x.value),
2927                     if i >= 0 { Some(i - mod10(i)) } else { None }
2928                 );
2929             }
2930             {
2931                 let c = t.upper_bound_mut(Included(&i));
2932                 assert_eq!(
2933                     c.get().map(|x| x.value),
2934                     if i >= 0 { Some(i - mod10(i)) } else { None }
2935                 );
2936             }
2937             {
2938                 let c = t.upper_bound(Excluded(&i));
2939                 assert_eq!(
2940                     c.get().map(|x| x.value),
2941                     if i > 0 {
2942                         Some(i - 1 - mod10(i - 1))
2943                     } else {
2944                         None
2945                     }
2946                 );
2947             }
2948             {
2949                 let c = t.upper_bound_mut(Excluded(&i));
2950                 assert_eq!(
2951                     c.get().map(|x| x.value),
2952                     if i > 0 {
2953                         Some(i - 1 - mod10(i - 1))
2954                     } else {
2955                         None
2956                     }
2957                 );
2958             }
2959             {
2960                 let c = t.lower_bound(Unbounded);
2961                 assert_eq!(c.get().map(|x| x.value), Some(0));
2962             }
2963             {
2964                 let c = t.lower_bound_mut(Unbounded);
2965                 assert_eq!(c.get().map(|x| x.value), Some(0));
2966             }
2967             {
2968                 let c = t.lower_bound(Included(&i));
2969                 assert_eq!(
2970                     c.get().map(|x| x.value),
2971                     if i <= 90 {
2972                         Some((i + 9) - mod10(i + 9))
2973                     } else {
2974                         None
2975                     }
2976                 );
2977             }
2978             {
2979                 let c = t.lower_bound_mut(Included(&i));
2980                 assert_eq!(
2981                     c.get().map(|x| x.value),
2982                     if i <= 90 {
2983                         Some((i + 9) - mod10(i + 9))
2984                     } else {
2985                         None
2986                     }
2987                 );
2988             }
2989             {
2990                 let c = t.lower_bound(Excluded(&i));
2991                 assert_eq!(
2992                     c.get().map(|x| x.value),
2993                     if i < 90 {
2994                         Some((i + 10) - mod10(i + 10))
2995                     } else {
2996                         None
2997                     }
2998                 );
2999             }
3000             {
3001                 let c = t.lower_bound_mut(Excluded(&i));
3002                 assert_eq!(
3003                     c.get().map(|x| x.value),
3004                     if i < 90 {
3005                         Some((i + 10) - mod10(i + 10))
3006                     } else {
3007                         None
3008                     }
3009                 );
3010             }
3011         }
3012     }
3013 
3014     #[test]
3015     fn test_fast_clear() {
3016         let mut t = RBTree::new(ObjAdapter::new());
3017         let a = make_obj(1);
3018         let b = make_obj(2);
3019         let c = make_obj(3);
3020         t.insert(a.clone());
3021         t.insert(b.clone());
3022         t.insert(c.clone());
3023 
3024         t.fast_clear();
3025         assert!(t.is_empty());
3026         assert!(a.link.is_linked());
3027         assert!(b.link.is_linked());
3028         assert!(c.link.is_linked());
3029         unsafe {
3030             a.link.force_unlink();
3031             b.link.force_unlink();
3032             c.link.force_unlink();
3033         }
3034         assert!(t.is_empty());
3035         assert!(!a.link.is_linked());
3036         assert!(!b.link.is_linked());
3037         assert!(!c.link.is_linked());
3038     }
3039 
3040     #[test]
3041     fn test_entry() {
3042         let mut t = RBTree::new(ObjAdapter::new());
3043         let a = make_obj(1);
3044         let b = make_obj(2);
3045         let c = make_obj(3);
3046         let d = make_obj(4);
3047         let e = make_obj(5);
3048         let f = make_obj(6);
3049         t.entry(&3).or_insert(c);
3050         t.entry(&2).or_insert(b.clone());
3051         t.entry(&1).or_insert(a);
3052 
3053         match t.entry(&2) {
3054             Entry::Vacant(_) => unreachable!(),
3055             Entry::Occupied(c) => assert_eq!(c.get().unwrap().value, 2),
3056         }
3057         assert_eq!(t.entry(&2).or_insert(b.clone()).get().unwrap().value, 2);
3058         assert_eq!(
3059             t.entry(&2)
3060                 .or_insert_with(|| b.clone())
3061                 .get()
3062                 .unwrap()
3063                 .value,
3064             2
3065         );
3066 
3067         match t.entry(&5) {
3068             Entry::Vacant(c) => assert_eq!(c.insert(e.clone()).get().unwrap().value, 5),
3069             Entry::Occupied(_) => unreachable!(),
3070         }
3071         assert!(e.link.is_linked());
3072         assert_eq!(t.entry(&4).or_insert(d.clone()).get().unwrap().value, 4);
3073         assert!(d.link.is_linked());
3074         assert_eq!(
3075             t.entry(&6)
3076                 .or_insert_with(|| f.clone())
3077                 .get()
3078                 .unwrap()
3079                 .value,
3080             6
3081         );
3082         assert!(f.link.is_linked());
3083     }
3084 
3085     #[test]
3086     fn test_non_static() {
3087         #[derive(Clone)]
3088         struct Obj<'a, T> {
3089             link: Link,
3090             value: &'a T,
3091         }
3092         intrusive_adapter!(ObjAdapter<'a, T> = &'a Obj<'a, T>: Obj<'a, T> {link: Link} where T: 'a);
3093         impl<'a, 'b, T: 'a + 'b> KeyAdapter<'a> for ObjAdapter<'b, T> {
3094             type Key = &'a T;
3095             fn get_key(&self, value: &'a Obj<'b, T>) -> &'a T {
3096                 value.value
3097             }
3098         }
3099 
3100         let v = 5;
3101         let a = Obj {
3102             link: Link::default(),
3103             value: &v,
3104         };
3105         let b = a.clone();
3106         let mut l = RBTree::new(ObjAdapter::new());
3107         l.insert(&a);
3108         l.insert(&b);
3109         assert_eq!(*l.front().get().unwrap().value, 5);
3110         assert_eq!(*l.back().get().unwrap().value, 5);
3111     }
3112 
3113     macro_rules! test_clone_pointer {
3114         ($ptr: ident, $ptr_import: path) => {
3115             use $ptr_import;
3116 
3117             #[derive(Clone)]
3118             struct Obj {
3119                 link: Link,
3120                 value: usize,
3121             }
3122             intrusive_adapter!(ObjAdapter = $ptr<Obj>: Obj { link: Link });
3123             impl<'a> KeyAdapter<'a> for ObjAdapter {
3124                 type Key = usize;
3125                 fn get_key(&self, value: &'a Obj) -> usize {
3126                     value.value
3127                 }
3128             }
3129 
3130             let a = $ptr::new(Obj {
3131                 link: Link::new(),
3132                 value: 5,
3133             });
3134             let mut l = RBTree::new(ObjAdapter::new());
3135             l.insert(a.clone());
3136             assert_eq!(2, $ptr::strong_count(&a));
3137 
3138             let pointer = l.front().clone_pointer().unwrap();
3139             assert_eq!(pointer.value, 5);
3140             assert_eq!(3, $ptr::strong_count(&a));
3141 
3142             l.front_mut().remove();
3143             assert!(l.front().clone_pointer().is_none());
3144         };
3145     }
3146 
3147     #[test]
3148     fn test_clone_pointer_rc() {
3149         test_clone_pointer!(Rc, std::rc::Rc);
3150     }
3151 
3152     #[test]
3153     fn test_clone_pointer_arc() {
3154         test_clone_pointer!(Arc, std::sync::Arc);
3155     }
3156 }
3157