augmented-rbtree 0.2.0

An augmented red-black tree with generic, user-defined per-node statistics — enables interval trees, order-statistics trees, range-sum trees, and more.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
use crate::alloc_proxy::proxy::Allocator;
use crate::augmented_rbtree::internal_details::free_subtree;
use crate::iterators::internal_details::ValMutInt;
use crate::layout::AugmentedRBTreeLayout;
use crate::node::internal_details::NodeRef;
use crate::policy::internal_details::TreePolicy;
use core::borrow::Borrow;
use core::marker::PhantomData;
use core::ops::{Bound, RangeBounds};

/// A guarded mutable reference to an augmented tree value.
///
/// Modifying the underlying value via this guard automatically
/// propagates augmentation updates up the tree when it goes out of scope.
pub type ValMut<'a, K, V, S, P> = ValMutInt<'a, K, V, S, P>;

/// A mutable iterator over the values of an augmented tree.
pub type ValuesMut<'a, K, V, S, P> =
    crate::iterators::internal_details::ValuesMutInt<'a, K, V, S, P>;

pub mod internal_details {
    use core::{
        marker::PhantomData,
        ops::{Deref, DerefMut},
    };

    use crate::{
        node::{Node, internal_details::NodeRef},
        policy::internal_details::TreePolicy,
    };

    /// A mutable reference to a value in an `AugmentedRBTree`.
    ///
    /// When this reference is dropped, it triggers augmentation recalculation
    /// up the tree, ensuring the augmented data remains correct.
    #[derive(Debug)]
    pub struct ValMutInt<'a, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        node: NodeRef<K, V, S>,
        marker: PhantomData<(&'a mut Node<K, V, S>, &'a P)>,
    }

    impl<K, V, S, P> ValMutInt<'_, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        pub(crate) fn new(node: NodeRef<K, V, S>) -> Self {
            Self {
                node,
                marker: PhantomData,
            }
        }
    }

    impl<K, V, S, P> AsMut<V> for ValMutInt<'_, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        fn as_mut(&mut self) -> &mut V {
            unsafe { self.node.value_mut() }
        }
    }

    impl<K, V, S, P> Deref for ValMutInt<'_, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        type Target = V;

        #[inline]
        fn deref(&self) -> &Self::Target {
            unsafe { self.node.value() }
        }
    }

    impl<K, V, S, P> DerefMut for ValMutInt<'_, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        #[inline]
        fn deref_mut(&mut self) -> &mut Self::Target {
            unsafe { self.node.value_mut() }
        }
    }

    impl<K, V, S, P> Drop for ValMutInt<'_, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        fn drop(&mut self) {
            P::augment(self.node);
            P::augment_upstream(self.node);
        }
    }

    /// A mutable iterator over the values of an `AugmentedRBTree`.
    ///
    /// This struct is created by the [`values_mut`](crate::AugmentedRBTreeInt::values_mut) method.
    #[derive(Debug)]
    pub struct ValuesMutInt<'a, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        inner: IterMut<'a, K, V, S, P>,
    }

    impl<'a, K, V, S, P> ValuesMutInt<'a, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        pub(crate) fn new(inner: IterMut<'a, K, V, S, P>) -> Self {
            Self { inner }
        }
    }

    impl<'a, K, V, S: 'a, P> Iterator for ValuesMutInt<'a, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        type Item = ValMutInt<'a, K, V, S, P>;

        fn next(&mut self) -> Option<Self::Item> {
            self.inner.next().map(|(_, v, _)| v)
        }

        fn size_hint(&self) -> (usize, Option<usize>) {
            self.inner.size_hint()
        }
    }

    impl<'a, K, V, S: 'a, P> DoubleEndedIterator for ValuesMutInt<'a, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        fn next_back(&mut self) -> Option<Self::Item> {
            self.inner.next_back().map(|(_, v, _)| v)
        }
    }

    impl<'a, K, V, S: 'a, P> ExactSizeIterator for ValuesMutInt<'a, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        fn len(&self) -> usize {
            self.inner.len()
        }
    }

    impl<'a, K, V, S: 'a, P> core::iter::FusedIterator for ValuesMutInt<'a, K, V, S, P> where
        P: TreePolicy<K = K, V = V, S = S>
    {
    }

    /// A mutable iterator over the entries of an `AugmentedRBTree`.
    ///
    /// This struct is created by the [`iter_mut`](crate::AugmentedRBTreeInt::iter_mut) method.
    #[derive(Debug)]
    pub struct IterMut<'a, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        next: Option<NodeRef<K, V, S>>,
        back: Option<NodeRef<K, V, S>>,
        len: usize,
        _marker: PhantomData<(&'a mut (K, V, S), &'a P)>,
    }

    impl<K, V, S, P> IterMut<'_, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        pub(crate) fn new(root: Option<NodeRef<K, V, S>>, len: usize) -> Self {
            let next = root.map(NodeRef::leftmost);
            let back = root.map(NodeRef::rightmost);
            Self {
                next,
                back,
                len,
                _marker: PhantomData,
            }
        }
    }

    impl<'a, K, V, S, P> Iterator for IterMut<'a, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        type Item = (&'a K, ValMutInt<'a, K, V, S, P>, &'a S);

        fn next(&mut self) -> Option<Self::Item> {
            if self.len == 0 {
                return None;
            }

            let node = self.next?;

            // Check if we've crossed paths with the back iterator
            if self.next == self.back {
                self.next = None;
                self.back = None;
            } else {
                self.next = node.next_node();
            }

            self.len -= 1;

            unsafe {
                let key_ref = node.key();
                let stats_ref = node.stats();
                let val_mut = ValMutInt::new(node);
                Some((key_ref, val_mut, stats_ref))
            }
        }

        fn size_hint(&self) -> (usize, Option<usize>) {
            (self.len, Some(self.len))
        }
    }

    impl<'a, K, V, S: 'a, P> DoubleEndedIterator for IterMut<'a, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        fn next_back(&mut self) -> Option<Self::Item> {
            if self.len == 0 {
                return None;
            }

            let node = self.back?;

            // Check if we've crossed paths with the front iterator
            if self.next == self.back {
                self.next = None;
                self.back = None;
            } else {
                self.back = node.prev_node();
            }

            self.len -= 1;

            unsafe {
                let key_ref = node.key();
                let stats_ref = node.stats();
                let val_mut = ValMutInt::new(node);
                Some((key_ref, val_mut, stats_ref))
            }
        }
    }

    impl<'a, K, V, S: 'a, P> ExactSizeIterator for IterMut<'a, K, V, S, P>
    where
        P: TreePolicy<K = K, V = V, S = S>,
    {
        fn len(&self) -> usize {
            self.len
        }
    }

    impl<'a, K, V, S: 'a, P> core::iter::FusedIterator for IterMut<'a, K, V, S, P> where
        P: TreePolicy<K = K, V = V, S = S>
    {
    }
}

/// An iterator over the entries of an `AugmentedRBTree`.
///
/// This struct is created by the `AugmentedRBTreeInt::iter` method.
#[derive(Debug)]
pub struct Iter<'a, K, V, S> {
    next: Option<NodeRef<K, V, S>>,
    back: Option<NodeRef<K, V, S>>,
    len: usize,
    _marker: PhantomData<&'a (K, V, S)>,
}

impl<K, V, S> Iter<'_, K, V, S> {
    pub(crate) fn new(root: Option<NodeRef<K, V, S>>, len: usize) -> Self {
        let next = root.map(NodeRef::leftmost);
        let back = root.map(NodeRef::rightmost);
        Self {
            next,
            back,
            len,
            _marker: PhantomData,
        }
    }
}

impl<'a, K, V, S> Iterator for Iter<'a, K, V, S> {
    type Item = (&'a K, &'a V, &'a S);

    fn next(&mut self) -> Option<Self::Item> {
        if self.len == 0 {
            return None;
        }

        let node = self.next?;

        // Check if we've crossed paths with the back iterator
        if self.next == self.back {
            self.next = None;
            self.back = None;
        } else {
            self.next = node.next_node();
        }

        self.len -= 1;

        unsafe { Some((node.key(), node.value(), node.stats())) }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.len, Some(self.len))
    }
}

impl<'a, K, V, S: 'a> DoubleEndedIterator for Iter<'a, K, V, S> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.len == 0 {
            return None;
        }

        let node = self.back?;

        // Check if we've crossed paths with the front iterator
        if self.next == self.back {
            self.next = None;
            self.back = None;
        } else {
            self.back = node.prev_node();
        }

        self.len -= 1;

        unsafe { Some((node.key(), node.value(), node.stats())) }
    }
}

impl<'a, K, V, S: 'a> ExactSizeIterator for Iter<'a, K, V, S> {
    fn len(&self) -> usize {
        self.len
    }
}

impl<'a, K, V, S: 'a> core::iter::FusedIterator for Iter<'a, K, V, S> {}

/// An owning iterator over the entries of an `AugmentedRBTree`.
///
/// This struct is created by the [`into_iter`](IntoIterator::into_iter) method
/// on [`AugmentedRBTreeInt`](crate::AugmentedRBTreeInt) (provided by the [`IntoIterator`] trait).
///
/// Nodes are removed from the tree as they are iterated over but the augmented data is not recalculated.
///
#[derive(Debug)]
pub struct IntoIter<K, V, S, A, P>
where
    P: TreePolicy<K = K, V = V, S = S>,
    A: Allocator,
{
    next: Option<NodeRef<K, V, S>>,
    back: Option<NodeRef<K, V, S>>,
    layout: AugmentedRBTreeLayout<K, V, S, A, P>,
    len: usize,
}

impl<K, V, S, A: Allocator, P> IntoIter<K, V, S, A, P>
where
    P: TreePolicy<K = K, V = V, S = S>,
    A: Allocator,
{
    pub(crate) fn new(layout: AugmentedRBTreeLayout<K, V, S, A, P>, len: usize) -> Self {
        let next = layout.root.map(NodeRef::leftmost);
        let back = layout.root.map(NodeRef::rightmost);
        Self {
            next,
            back,
            layout,
            len,
        }
    }
}

impl<K, V, S, A, P> Drop for IntoIter<K, V, S, A, P>
where
    P: TreePolicy<K = K, V = V, S = S>,
    A: Allocator,
{
    fn drop(&mut self) {
        if let Some(root) = self.layout.root.take() {
            unsafe { free_subtree(root, &self.layout.node_allocator.alloc) };
        }
    }
}

impl<K, V, S, A: Allocator, P> Iterator for IntoIter<K, V, S, A, P>
where
    P: TreePolicy<K = K, V = V, S = S>,
{
    type Item = (K, V);

    fn next(&mut self) -> Option<Self::Item> {
        if self.len == 0 {
            return None;
        }

        let current = self
            .next
            .take()
            .expect("This node must exists because len > 0");

        let next_node = current.next_node();

        self.next = next_node;

        let (key, value) = self.layout.delete_node_no_fixup(current);

        self.len -= 1;

        Some((key, value))
    }
}

impl<K, V, S, A: Allocator, P> DoubleEndedIterator for IntoIter<K, V, S, A, P>
where
    P: TreePolicy<K = K, V = V, S = S>,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.len == 0 {
            return None;
        }

        let current = self
            .back
            .take()
            .expect("This node must exists because len > 0");

        let back_node = current.prev_node();

        self.back = back_node;

        let (key, value) = self.layout.delete_node_no_fixup(current);

        self.len -= 1;

        Some((key, value))
    }
}

impl<K, V, S, A: Allocator, P: TreePolicy<K = K, V = V, S = S>> ExactSizeIterator
    for IntoIter<K, V, S, A, P>
{
    fn len(&self) -> usize {
        self.len
    }
}

impl<K, V, S, A: Allocator, P: TreePolicy<K = K, V = V, S = S>> core::iter::FusedIterator
    for IntoIter<K, V, S, A, P>
{
}

/// An iterator over the keys of an `AugmentedRBTree`.
///
/// This struct is created by the `AugmentedRBTreeInt::keys` method.
#[derive(Debug)]
pub struct Keys<'a, K, V, S> {
    inner: Iter<'a, K, V, S>,
}

impl<'a, K, V, S> Keys<'a, K, V, S> {
    pub(crate) fn new(inner: Iter<'a, K, V, S>) -> Self {
        Self { inner }
    }
}

impl<'a, K, V, S: 'a> Iterator for Keys<'a, K, V, S> {
    type Item = &'a K;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(k, _, _)| k)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<'a, K, V, S: 'a> DoubleEndedIterator for Keys<'a, K, V, S> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|(k, _, _)| k)
    }
}

impl<'a, K, V, S: 'a> ExactSizeIterator for Keys<'a, K, V, S> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<'a, K, V, S: 'a> core::iter::FusedIterator for Keys<'a, K, V, S> {}

/// An iterator over the values of an `AugmentedRBTree`.
///
/// This struct is created by the `AugmentedRBTreeInt::values` method.
#[derive(Debug)]
pub struct Values<'a, K, V, S> {
    inner: Iter<'a, K, V, S>,
}

impl<'a, K, V, S> Values<'a, K, V, S> {
    pub(crate) fn new(inner: Iter<'a, K, V, S>) -> Self {
        Self { inner }
    }
}

impl<'a, K, V, S: 'a> Iterator for Values<'a, K, V, S> {
    type Item = &'a V;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(_, v, _)| v)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<'a, K, V, S: 'a> DoubleEndedIterator for Values<'a, K, V, S> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|(_, v, _)| v)
    }
}

impl<'a, K, V, S: 'a> ExactSizeIterator for Values<'a, K, V, S> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<'a, K, V, S: 'a> core::iter::FusedIterator for Values<'a, K, V, S> {}

/// An iterator over the values of an `AugmentedRBTree`.
///
/// This struct is created by the [`values`](crate::AugmentedRBTreeInt::values) method.
#[derive(Debug)]
pub struct Stats<'a, K, V, S> {
    inner: Iter<'a, K, V, S>,
}

impl<'a, K, V, S> Stats<'a, K, V, S> {
    pub(crate) fn new(inner: Iter<'a, K, V, S>) -> Self {
        Self { inner }
    }
}

impl<'a, K, V, S: 'a> Iterator for Stats<'a, K, V, S> {
    type Item = &'a S;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(_, _, s)| s)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<'a, K, V, S: 'a> DoubleEndedIterator for Stats<'a, K, V, S> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|(_, _, s)| s)
    }
}

impl<'a, K, V, S: 'a> ExactSizeIterator for Stats<'a, K, V, S> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<'a, K, V, S: 'a> core::iter::FusedIterator for Stats<'a, K, V, S> {}

// ============================================================================
// Range iterators
// ============================================================================

/// An iterator over a sub-range of entries in an `AugmentedRBTree`.
///
/// This struct is created by the `AugmentedRBTreeInt::range` method.
#[derive(Debug)]
pub struct Range<'a, K, V, S> {
    front: Option<NodeRef<K, V, S>>,
    back: Option<NodeRef<K, V, S>>,
    exhausted: bool,
    _marker: PhantomData<&'a (K, V, S)>,
}

impl<'a, K, V, S> Range<'a, K, V, S>
where
    K: Ord,
{
    pub(crate) fn new<Q, R>(layout: &'a dyn RangeBoundsLimits<K, V, S, Q>, range: R) -> Self
    where
        K: Borrow<Q> + Ord,
        Q: Ord + ?Sized + 'a,
        R: RangeBounds<Q>,
    {
        let (front, back, exhausted) = range_bounds_to_nodes(layout, &range);
        Self {
            front,
            back,
            exhausted,
            _marker: PhantomData,
        }
    }
}

impl<'a, K, V, S: 'a> Iterator for Range<'a, K, V, S> {
    type Item = (&'a K, &'a V, &'a S);

    fn next(&mut self) -> Option<Self::Item> {
        if self.exhausted {
            return None;
        }
        let node = self.front?;
        if self.front == self.back {
            self.exhausted = true;
        } else {
            self.front = node.next_node();
        }
        unsafe { Some((node.key(), node.value(), node.stats())) }
    }
}

impl<'a, K, V, S: 'a> DoubleEndedIterator for Range<'a, K, V, S> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.exhausted {
            return None;
        }
        let node = self.back?;
        if self.front == self.back {
            self.exhausted = true;
        } else {
            self.back = node.prev_node();
        }
        unsafe { Some((node.key(), node.value(), node.stats())) }
    }
}

impl<'a, K, V, S: 'a> core::iter::FusedIterator for Range<'a, K, V, S> {}

/// A mutable iterator over a sub-range of entries in an `AugmentedRBTree`.
///
/// This struct is created by the `AugmentedRBTreeInt::range_mut` method.
#[derive(Debug)]
pub struct RangeMut<'a, K, V, S, P>
where
    P: TreePolicy<K = K, V = V, S = S>,
{
    front: Option<NodeRef<K, V, S>>,
    back: Option<NodeRef<K, V, S>>,
    exhausted: bool,
    _marker: PhantomData<(&'a mut (K, V, S), &'a P)>,
}

impl<'a, K, V, S, P> RangeMut<'a, K, V, S, P>
where
    K: Ord,
    P: TreePolicy<K = K, V = V, S = S>,
{
    pub(crate) fn new<Q, R>(layout: &'a dyn RangeBoundsLimits<K, V, S, Q>, range: R) -> Self
    where
        K: Borrow<Q> + Ord,
        Q: Ord + ?Sized,
        R: RangeBounds<Q>,
    {
        let (front, back, exhausted) = range_bounds_to_nodes(layout, &range);

        Self {
            front,
            back,
            exhausted,
            _marker: PhantomData,
        }
    }
}

impl<'a, K, V, S, P> Iterator for RangeMut<'a, K, V, S, P>
where
    P: TreePolicy<K = K, V = V, S = S>,
{
    type Item = (&'a K, ValMutInt<'a, K, V, S, P>, &'a S);

    fn next(&mut self) -> Option<Self::Item> {
        if self.exhausted {
            return None;
        }
        let node = self.front?;
        if self.front == self.back {
            self.exhausted = true;
        } else {
            self.front = node.next_node();
        }
        unsafe {
            let key_ref = node.key();
            let stats_ref = node.stats();
            Some((key_ref, ValMutInt::new(node), stats_ref))
        }
    }
}

impl<'a, K, V, S: 'a, P> DoubleEndedIterator for RangeMut<'a, K, V, S, P>
where
    P: TreePolicy<K = K, V = V, S = S>,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.exhausted {
            return None;
        }
        let node = self.back?;
        if self.front == self.back {
            self.exhausted = true;
        } else {
            self.back = node.prev_node();
        }
        unsafe {
            let key_ref = node.key();
            let stats_ref = node.stats();
            Some((key_ref, ValMutInt::new(node), stats_ref))
        }
    }
}

impl<'a, K, V, S: 'a, P> core::iter::FusedIterator for RangeMut<'a, K, V, S, P> where
    P: TreePolicy<K = K, V = V, S = S>
{
}

// Helper: resolves a RangeBounds into (front_node, back_node, exhausted)
type RangeBoundsResult<K, V, S> = (Option<NodeRef<K, V, S>>, Option<NodeRef<K, V, S>>, bool);

pub(crate) trait RangeBoundsLimits<K, V, S, Q: ?Sized> {
    fn lower_bound(&self, key: &Q) -> Option<NodeRef<K, V, S>>;
    fn upper_bound(&self, key: &Q) -> Option<NodeRef<K, V, S>>;
    fn leftmost(&self) -> Option<NodeRef<K, V, S>>;
    fn rightmost(&self) -> Option<NodeRef<K, V, S>>;
}

fn range_bounds_to_nodes<K, V, S, R, Q>(
    layout: &dyn RangeBoundsLimits<K, V, S, Q>,
    range: &R,
) -> RangeBoundsResult<K, V, S>
where
    R: RangeBounds<Q>,
    K: Borrow<Q> + Ord,
    Q: Ord + ?Sized,
{
    let front = match range.start_bound() {
        Bound::Included(k) => layout.lower_bound(k),
        Bound::Excluded(k) => {
            // First node strictly greater than k
            layout.lower_bound(k).and_then(|n| {
                if unsafe { n.key() }.borrow() == k {
                    n.next_node()
                } else {
                    Some(n)
                }
            })
        }
        Bound::Unbounded => layout.leftmost(),
    };

    let back = match range.end_bound() {
        Bound::Included(k) => layout.upper_bound(k),
        Bound::Excluded(k) => {
            // Last node strictly less than k
            layout.upper_bound(k).and_then(|n| {
                if unsafe { n.key() }.borrow() == k {
                    n.prev_node()
                } else {
                    Some(n)
                }
            })
        }
        Bound::Unbounded => layout.rightmost(),
    };

    // Check if the range is empty (front is past back)
    let exhausted = match (front, back) {
        (Some(f), Some(b)) => unsafe { f.key() > b.key() },
        (Some(_), None) | (None, _) => true,
    };

    (front, back, exhausted)
}