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