unc_sdk/store/tree_map/
iter.rs

1use std::ops::Bound;
2use std::vec::Vec;
3use std::{borrow::Borrow, iter::FusedIterator};
4use unc_sdk_macros::unc;
5
6use borsh::{BorshDeserialize, BorshSerialize};
7
8use super::{expect, LookupMap, Tree, TreeMap};
9use crate::store::free_list::FreeListIndex;
10use crate::store::key::ToKey;
11
12impl<'a, K, V, H> IntoIterator for &'a TreeMap<K, V, H>
13where
14    K: BorshSerialize + Ord + BorshDeserialize + Clone,
15    V: BorshSerialize + BorshDeserialize,
16    H: ToKey,
17{
18    type Item = (&'a K, &'a V);
19    type IntoIter = Iter<'a, K, V, H>;
20
21    fn into_iter(self) -> Self::IntoIter {
22        self.iter()
23    }
24}
25
26impl<'a, K, V, H> IntoIterator for &'a mut TreeMap<K, V, H>
27where
28    K: BorshSerialize + Ord + BorshDeserialize + Clone,
29    V: BorshSerialize + BorshDeserialize,
30    H: ToKey,
31{
32    type Item = (&'a K, &'a mut V);
33    type IntoIter = IterMut<'a, K, V, H>;
34
35    fn into_iter(self) -> Self::IntoIter {
36        self.iter_mut()
37    }
38}
39
40/// An iterator over elements of a [`TreeMap`], in sorted order.
41///
42/// This `struct` is created by the `iter` method on [`TreeMap`].
43pub struct Iter<'a, K, V, H>
44where
45    K: BorshSerialize + Ord + BorshDeserialize,
46    V: BorshSerialize,
47    H: ToKey,
48{
49    keys: Keys<'a, K>,
50    values: &'a LookupMap<K, V, H>,
51}
52
53impl<'a, K, V, H> Iter<'a, K, V, H>
54where
55    K: BorshSerialize + Ord + BorshDeserialize,
56    V: BorshSerialize,
57    H: ToKey,
58{
59    pub(super) fn new(map: &'a TreeMap<K, V, H>) -> Self {
60        Self { keys: Keys::new(&map.tree), values: &map.values }
61    }
62}
63
64impl<'a, K, V, H> Iterator for Iter<'a, K, V, H>
65where
66    K: BorshSerialize + Ord + BorshDeserialize + Clone,
67    V: BorshSerialize + BorshDeserialize,
68    H: ToKey,
69{
70    type Item = (&'a K, &'a V);
71
72    fn next(&mut self) -> Option<Self::Item> {
73        <Self as Iterator>::nth(self, 0)
74    }
75
76    fn nth(&mut self, n: usize) -> Option<Self::Item> {
77        let key = self.keys.nth(n)?;
78        let entry = expect(self.values.get(key));
79
80        Some((key, entry))
81    }
82
83    fn size_hint(&self) -> (usize, Option<usize>) {
84        self.keys.size_hint()
85    }
86
87    fn count(self) -> usize {
88        self.keys.count()
89    }
90}
91
92impl<'a, K, V, H> ExactSizeIterator for Iter<'a, K, V, H>
93where
94    K: BorshSerialize + Ord + BorshDeserialize + Clone,
95    V: BorshSerialize + BorshDeserialize,
96    H: ToKey,
97{
98}
99impl<'a, K, V, H> FusedIterator for Iter<'a, K, V, H>
100where
101    K: BorshSerialize + Ord + BorshDeserialize + Clone,
102    V: BorshSerialize + BorshDeserialize,
103    H: ToKey,
104{
105}
106
107impl<'a, K, V, H> DoubleEndedIterator for Iter<'a, K, V, H>
108where
109    K: BorshSerialize + Ord + BorshDeserialize + Clone,
110    V: BorshSerialize + BorshDeserialize,
111    H: ToKey,
112{
113    fn next_back(&mut self) -> Option<Self::Item> {
114        <Self as DoubleEndedIterator>::nth_back(self, 0)
115    }
116
117    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
118        let key = self.keys.nth_back(n)?;
119        let entry = expect(self.values.get(key));
120
121        Some((key, entry))
122    }
123}
124
125fn get_entry_mut<'a, K, V, H>(map: &mut LookupMap<K, V, H>, key: &'a K) -> (&'a K, &'a mut V)
126where
127    K: BorshSerialize + Ord + BorshDeserialize + Clone,
128    V: BorshSerialize + BorshDeserialize,
129    H: ToKey,
130{
131    let entry = expect(map.get_mut(key));
132    //* SAFETY: The lifetime can be swapped here because we can assert that the iterator
133    //*         will only give out one mutable reference for every individual key in the bucket
134    //*         during the iteration, and there is no overlap. This operates under the
135    //*         assumption that all elements in the bucket are unique and no hash collisions.
136    //*         Because we use 32 byte hashes and all keys are verified unique based on the
137    //*         `TreeMap` API, this is safe.
138    let value = unsafe { &mut *(entry as *mut V) };
139    (key, value)
140}
141
142/// A mutable iterator over elements of a [`TreeMap`], in sorted order.
143///
144/// This `struct` is created by the `iter_mut` method on [`TreeMap`].
145pub struct IterMut<'a, K, V, H>
146where
147    K: BorshSerialize + Ord + BorshDeserialize,
148    V: BorshSerialize,
149    H: ToKey,
150{
151    /// Values iterator which contains empty and filled cells.
152    keys: Keys<'a, K>,
153    /// Exclusive reference to underlying map to lookup values with `keys`.
154    values: &'a mut LookupMap<K, V, H>,
155}
156
157impl<'a, K, V, H> IterMut<'a, K, V, H>
158where
159    K: BorshSerialize + Ord + BorshDeserialize,
160    V: BorshSerialize,
161    H: ToKey,
162{
163    pub(super) fn new(map: &'a mut TreeMap<K, V, H>) -> Self {
164        Self { keys: Keys::new(&map.tree), values: &mut map.values }
165    }
166}
167
168impl<'a, K, V, H> Iterator for IterMut<'a, K, V, H>
169where
170    K: BorshSerialize + Ord + BorshDeserialize + Clone,
171    V: BorshSerialize + BorshDeserialize,
172    H: ToKey,
173{
174    type Item = (&'a K, &'a mut V);
175
176    fn next(&mut self) -> Option<Self::Item> {
177        <Self as Iterator>::nth(self, 0)
178    }
179
180    fn nth(&mut self, n: usize) -> Option<Self::Item> {
181        let key = self.keys.nth(n)?;
182        Some(get_entry_mut(self.values, key))
183    }
184
185    fn size_hint(&self) -> (usize, Option<usize>) {
186        self.keys.size_hint()
187    }
188
189    fn count(self) -> usize {
190        self.keys.count()
191    }
192}
193
194impl<'a, K, V, H> ExactSizeIterator for IterMut<'a, K, V, H>
195where
196    K: BorshSerialize + Ord + BorshDeserialize + Clone,
197    V: BorshSerialize + BorshDeserialize,
198    H: ToKey,
199{
200}
201impl<'a, K, V, H> FusedIterator for IterMut<'a, K, V, H>
202where
203    K: BorshSerialize + Ord + BorshDeserialize + Clone,
204    V: BorshSerialize + BorshDeserialize,
205    H: ToKey,
206{
207}
208
209impl<'a, K, V, H> DoubleEndedIterator for IterMut<'a, K, V, H>
210where
211    K: BorshSerialize + Ord + BorshDeserialize + Clone,
212    V: BorshSerialize + BorshDeserialize,
213    H: ToKey,
214{
215    fn next_back(&mut self) -> Option<Self::Item> {
216        <Self as DoubleEndedIterator>::nth_back(self, 0)
217    }
218
219    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
220        let key = self.keys.nth_back(n)?;
221        Some(get_entry_mut(self.values, key))
222    }
223}
224
225/// This function takes the query range and map them to references to nodes in the map
226fn get_range_bounds<'a, Q, K>(
227    tree: &'a Tree<K>,
228    bounds: (Bound<&Q>, Bound<&Q>),
229) -> Option<(Bound<&'a K>, Bound<&'a K>)>
230where
231    K: Borrow<Q> + BorshSerialize + Ord + BorshDeserialize,
232    Q: ?Sized + Ord,
233{
234    let (min_bound, max_bound) = bounds;
235    let min = match min_bound {
236        Bound::Unbounded => Bound::Unbounded,
237        Bound::Included(bound) => {
238            if let Some(b) = tree.ceil_key(bound) {
239                Bound::Included(b)
240            } else {
241                return None;
242            }
243        }
244        Bound::Excluded(bound) => {
245            if let Some(b) = tree.higher(bound) {
246                Bound::Included(b)
247            } else {
248                return None;
249            }
250        }
251    };
252
253    let max = match max_bound {
254        Bound::Unbounded => Bound::Unbounded,
255        Bound::Included(bound) => {
256            if let Some(b) = tree.floor_key(bound) {
257                Bound::Included(b)
258            } else {
259                return None;
260            }
261        }
262        Bound::Excluded(bound) => {
263            if let Some(b) = tree.lower(bound) {
264                Bound::Included(b)
265            } else {
266                return None;
267            }
268        }
269    };
270
271    Some((min, max))
272}
273
274//Returns true if key is out of bounds to min value
275fn key_lt_bound<K>(key: &K, min: Bound<&K>) -> bool
276where
277    K: BorshSerialize + Ord + BorshDeserialize,
278{
279    match min {
280        Bound::Unbounded => false,
281        Bound::Excluded(a) => key <= a,
282        Bound::Included(a) => key < a,
283    }
284}
285
286//Returns true if key is out of bounds to max value
287fn key_gt_bound<K>(key: &K, max: Bound<&K>) -> bool
288where
289    K: BorshSerialize + Ord + BorshDeserialize,
290{
291    match max {
292        Bound::Unbounded => false,
293        Bound::Excluded(a) => key >= a,
294        Bound::Included(a) => key > a,
295    }
296}
297
298fn find_min<'a, K>(
299    tree: &'a Tree<K>,
300    root: Option<&FreeListIndex>,
301    stack_asc: &mut Vec<FreeListIndex>,
302    min: Bound<&'a K>,
303) -> Option<&'a K>
304where
305    K: BorshSerialize + Ord + BorshDeserialize,
306{
307    let mut curr = root;
308    let mut seen: Option<&K> = None;
309
310    while let Some(curr_idx) = curr {
311        if let Some(node) = tree.node(*curr_idx) {
312            if key_lt_bound(&node.key, min) {
313                curr = node.rgt.as_ref();
314            } else {
315                seen = Some(&node.key);
316                stack_asc.push(*curr_idx);
317                curr = node.lft.as_ref();
318            }
319        } else {
320            curr = None
321        }
322    }
323    seen
324}
325
326fn find_max<'a, K>(
327    tree: &'a Tree<K>,
328    root: Option<&FreeListIndex>,
329    stack_desc: &mut Vec<FreeListIndex>,
330    max: Bound<&'a K>,
331) -> Option<&'a K>
332where
333    K: BorshSerialize + Ord + BorshDeserialize,
334{
335    let mut curr = root;
336    let mut seen: Option<&K> = None;
337
338    while let Some(curr_idx) = curr {
339        if let Some(node) = tree.node(*curr_idx) {
340            if key_gt_bound(&node.key, max) {
341                curr = node.lft.as_ref();
342            } else {
343                seen = Some(&node.key);
344                stack_desc.push(*curr_idx);
345                curr = node.rgt.as_ref();
346            }
347        } else {
348            curr = None
349        }
350    }
351    seen
352}
353
354//The last element in the stack is the last returned key.
355//Find the next key to the last item in the stack
356fn find_next_asc<'a, K>(tree: &'a Tree<K>, stack_asc: &mut Vec<FreeListIndex>) -> Option<&'a K>
357where
358    K: BorshSerialize + Ord + BorshDeserialize,
359{
360    let last_key_idx = stack_asc.pop();
361    let mut seen: Option<&K> = None;
362    if let Some(last_idx) = last_key_idx {
363        if let Some(node) = tree.node(last_idx) {
364            //If the last returned key has right node then return minimum key from the
365            //tree where the right node is the root.
366            seen = match node.rgt {
367                Some(rgt) => find_min(tree, Some(&rgt), stack_asc, Bound::Unbounded),
368                None => None,
369            }
370        }
371    }
372    //If the last returned key does not have right node then return the
373    //last value in the stack.
374    if seen.is_none() && !stack_asc.is_empty() {
375        if let Some(result_idx) = stack_asc.last() {
376            seen = tree.node(*result_idx).map(|f| &f.key);
377        }
378    }
379    seen
380}
381
382fn find_next_desc<'a, K>(tree: &'a Tree<K>, stack_desc: &mut Vec<FreeListIndex>) -> Option<&'a K>
383where
384    K: BorshSerialize + Ord + BorshDeserialize,
385{
386    let last_key_idx = stack_desc.pop();
387    let mut seen: Option<&K> = None;
388    if let Some(last_idx) = last_key_idx {
389        if let Some(node) = tree.node(last_idx) {
390            //If the last returned key has left node then return maximum key from the
391            //tree where the left node is the root.
392            seen = match node.lft {
393                Some(lft) => find_max(tree, Some(&lft), stack_desc, Bound::Unbounded),
394                None => None,
395            }
396        }
397    }
398    //If the last returned key does not have left node then return the
399    //last value in the stack.
400    if seen.is_none() && !stack_desc.is_empty() {
401        if let Some(result_idx) = stack_desc.last() {
402            seen = tree.node(*result_idx).map(|f| &f.key);
403        }
404    }
405    seen
406}
407
408/// An iterator over the keys of a [`TreeMap`], in sorted order.
409///
410/// This `struct` is created by the `keys` method on [`TreeMap`].
411pub struct Keys<'a, K: 'a>
412where
413    K: BorshSerialize + BorshDeserialize + Ord,
414{
415    tree: &'a Tree<K>,
416    length: u32,
417    min: FindUnbounded,
418    max: FindUnbounded,
419    //The last element in the stack is the latest value returned by the iterator
420    stack_asc: Vec<FreeListIndex>,
421    stack_desc: Vec<FreeListIndex>,
422}
423
424impl<'a, K> Keys<'a, K>
425where
426    K: BorshSerialize + BorshDeserialize + Ord,
427{
428    pub(super) fn new(tree: &'a Tree<K>) -> Self {
429        Self {
430            tree,
431            length: tree.nodes.len(),
432            min: FindUnbounded::First,
433            max: FindUnbounded::First,
434            stack_asc: Vec::new(),
435            stack_desc: Vec::new(),
436        }
437    }
438}
439
440impl<'a, K> Iterator for Keys<'a, K>
441where
442    K: BorshSerialize + BorshDeserialize + Ord,
443{
444    type Item = &'a K;
445
446    fn next(&mut self) -> Option<&'a K> {
447        if self.length == 0 {
448            // Short circuit if all elements have been iterated.
449            return None;
450        }
451
452        let next = match self.min {
453            FindUnbounded::First => {
454                find_min(self.tree, self.tree.root.as_ref(), &mut self.stack_asc, Bound::Unbounded)
455            }
456            FindUnbounded::Next => find_next_asc(self.tree, &mut self.stack_asc),
457        };
458
459        if next.is_some() {
460            // Update minimum bound.
461            self.min = FindUnbounded::Next;
462
463            // Decrease count of potential elements
464            self.length -= 1;
465        } else {
466            // No more elements to iterate, set length to 0 to avoid duplicate lookups.
467            // Bounds can never be updated manually once initialized, so this can be done.
468            self.length = 0;
469        }
470
471        next
472    }
473
474    fn size_hint(&self) -> (usize, Option<usize>) {
475        let len = self.length as usize;
476        (len, Some(len))
477    }
478
479    fn count(self) -> usize {
480        self.length as usize
481    }
482}
483
484impl<'a, K> ExactSizeIterator for Keys<'a, K> where K: BorshSerialize + BorshDeserialize + Ord {}
485impl<'a, K> FusedIterator for Keys<'a, K> where K: BorshSerialize + BorshDeserialize + Ord {}
486
487impl<'a, K> DoubleEndedIterator for Keys<'a, K>
488where
489    K: BorshSerialize + Ord + BorshDeserialize,
490{
491    fn next_back(&mut self) -> Option<&'a K> {
492        if self.length == 0 {
493            // Short circuit if all elements have been iterated.
494            return None;
495        }
496
497        let next = match self.max {
498            FindUnbounded::First => {
499                find_max(self.tree, self.tree.root.as_ref(), &mut self.stack_desc, Bound::Unbounded)
500            }
501            FindUnbounded::Next => find_next_desc(self.tree, &mut self.stack_desc),
502        };
503
504        if next.is_some() {
505            // Update maximum bound.
506            self.max = FindUnbounded::Next;
507
508            // Decrease count of potential elements
509            self.length -= 1;
510        } else {
511            // No more elements to iterate, set length to 0 to avoid duplicate lookups.
512            // Bounds can never be updated manually once initialized, so this can be done.
513            self.length = 0;
514        }
515
516        next
517    }
518}
519
520/// An iterator over the keys of a [`TreeMap`], in sorted order.
521///
522/// This `struct` is created by the `keys` method on [`TreeMap`].
523pub struct KeysRange<'a, K: 'a>
524where
525    K: BorshSerialize + BorshDeserialize + Ord,
526{
527    tree: &'a Tree<K>,
528    length: u32,
529    min: Find<&'a K>,
530    max: Find<&'a K>,
531    //The last element in the stack is the latest value returned by the iterator
532    stack_asc: Vec<FreeListIndex>,
533    stack_desc: Vec<FreeListIndex>,
534}
535
536impl<'a, K> KeysRange<'a, K>
537where
538    K: BorshSerialize + BorshDeserialize + Ord,
539{
540    pub(super) fn new<Q>(tree: &'a Tree<K>, bounds: (Bound<&Q>, Bound<&Q>)) -> Self
541    where
542        K: Borrow<Q>,
543        Q: ?Sized + Ord,
544    {
545        if let Some((min, max)) = get_range_bounds(tree, bounds) {
546            Self {
547                tree,
548                length: tree.nodes.len(),
549                min: Find::First { bound: min },
550                max: Find::First { bound: max },
551                stack_asc: Vec::new(),
552                stack_desc: Vec::new(),
553            }
554        } else {
555            Self {
556                tree,
557                length: 0,
558                min: Find::First { bound: Bound::Unbounded },
559                max: Find::First { bound: Bound::Unbounded },
560                stack_asc: Vec::new(),
561                stack_desc: Vec::new(),
562            }
563        }
564    }
565}
566
567impl<'a, K> Iterator for KeysRange<'a, K>
568where
569    K: BorshSerialize + BorshDeserialize + Ord,
570{
571    type Item = &'a K;
572
573    fn next(&mut self) -> Option<&'a K> {
574        if self.length == 0 {
575            // Short circuit if all elements have been iterated.
576            return None;
577        }
578
579        let next = match self.min {
580            Find::First { bound: min } => {
581                find_min(self.tree, self.tree.root.as_ref(), &mut self.stack_asc, min)
582            }
583            Find::Next { bound: _ } => find_next_asc(self.tree, &mut self.stack_asc),
584        };
585
586        if let Some(next) = next {
587            // Check to make sure next key isn't past opposite bound.
588            match self.max.into_value() {
589                Bound::Included(bound) => {
590                    if next.gt(bound) {
591                        self.length = 0;
592                        return None;
593                    }
594                }
595                Bound::Excluded(bound) => {
596                    if !next.lt(bound) {
597                        self.length = 0;
598                        return None;
599                    }
600                }
601                Bound::Unbounded => (),
602            }
603
604            // Update minimum bound.
605            self.min = Find::Next { bound: Bound::Excluded(next) };
606
607            // Decrease count of potential elements
608            self.length -= 1;
609        } else {
610            // No more elements to iterate, set length to 0 to avoid duplicate lookups.
611            // Bounds can never be updated manually once initialized, so this can be done.
612            self.length = 0;
613        }
614
615        next
616    }
617
618    fn size_hint(&self) -> (usize, Option<usize>) {
619        let len = self.length as usize;
620        (0, Some(len))
621    }
622}
623
624impl<'a, K> FusedIterator for KeysRange<'a, K> where K: BorshSerialize + BorshDeserialize + Ord {}
625
626impl<'a, K> DoubleEndedIterator for KeysRange<'a, K>
627where
628    K: BorshSerialize + Ord + BorshDeserialize,
629{
630    fn next_back(&mut self) -> Option<&'a K> {
631        if self.length == 0 {
632            // Short circuit if all elements have been iterated.
633            return None;
634        }
635
636        let next = match self.max {
637            Find::First { bound: max } => {
638                find_max(self.tree, self.tree.root.as_ref(), &mut self.stack_desc, max)
639            }
640            Find::Next { bound: _ } => find_next_desc(self.tree, &mut self.stack_desc),
641        };
642
643        if let Some(next) = next {
644            // Check to make sure next key isn't past opposite bound
645            match self.min.into_value() {
646                Bound::Included(bound) => {
647                    if next.lt(bound) {
648                        self.length = 0;
649                        return None;
650                    }
651                }
652                Bound::Excluded(bound) => {
653                    if !next.gt(bound) {
654                        self.length = 0;
655                        return None;
656                    }
657                }
658                Bound::Unbounded => (),
659            }
660
661            // Update maximum bound.
662            self.max = Find::Next { bound: Bound::Excluded(next) };
663
664            // Decrease count of potential elements
665            self.length -= 1;
666        } else {
667            // No more elements to iterate, set length to 0 to avoid duplicate lookups.
668            // Bounds can never be updated manually once initialized, so this can be done.
669            self.length = 0;
670        }
671
672        next
673    }
674}
675
676/// An iterator over the values of a [`TreeMap`], in order by key.
677///
678/// This `struct` is created by the `values` method on [`TreeMap`].
679pub struct Values<'a, K, V, H>
680where
681    K: BorshSerialize + Ord + BorshDeserialize,
682    V: BorshSerialize,
683    H: ToKey,
684{
685    inner: Iter<'a, K, V, H>,
686}
687
688impl<'a, K, V, H> Values<'a, K, V, H>
689where
690    K: BorshSerialize + Ord + BorshDeserialize,
691    V: BorshSerialize,
692    H: ToKey,
693{
694    pub(super) fn new(map: &'a TreeMap<K, V, H>) -> Self {
695        Self { inner: map.iter() }
696    }
697}
698
699impl<'a, K, V, H> Iterator for Values<'a, K, V, H>
700where
701    K: BorshSerialize + Ord + BorshDeserialize + Clone,
702    V: BorshSerialize + BorshDeserialize,
703    H: ToKey,
704{
705    type Item = &'a V;
706
707    fn next(&mut self) -> Option<Self::Item> {
708        <Self as Iterator>::nth(self, 0)
709    }
710
711    fn nth(&mut self, n: usize) -> Option<Self::Item> {
712        self.inner.nth(n).map(|(_, v)| v)
713    }
714
715    fn size_hint(&self) -> (usize, Option<usize>) {
716        self.inner.size_hint()
717    }
718
719    fn count(self) -> usize {
720        self.inner.count()
721    }
722}
723
724impl<'a, K, V, H> ExactSizeIterator for Values<'a, K, V, H>
725where
726    K: BorshSerialize + Ord + BorshDeserialize + Clone,
727    V: BorshSerialize + BorshDeserialize,
728    H: ToKey,
729{
730}
731impl<'a, K, V, H> FusedIterator for Values<'a, K, V, H>
732where
733    K: BorshSerialize + Ord + BorshDeserialize + Clone,
734    V: BorshSerialize + BorshDeserialize,
735    H: ToKey,
736{
737}
738
739impl<'a, K, V, H> DoubleEndedIterator for Values<'a, K, V, H>
740where
741    K: BorshSerialize + Ord + BorshDeserialize + Clone,
742    V: BorshSerialize + BorshDeserialize,
743    H: ToKey,
744{
745    fn next_back(&mut self) -> Option<Self::Item> {
746        <Self as DoubleEndedIterator>::nth_back(self, 0)
747    }
748
749    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
750        self.inner.nth_back(n).map(|(_, v)| v)
751    }
752}
753
754/// A mutable iterator over values of a [`TreeMap`], in order by key.
755///
756/// This `struct` is created by the `values_mut` method on [`TreeMap`].
757pub struct ValuesMut<'a, K, V, H>
758where
759    K: BorshSerialize + Ord + BorshDeserialize,
760    V: BorshSerialize,
761    H: ToKey,
762{
763    inner: IterMut<'a, K, V, H>,
764}
765
766impl<'a, K, V, H> ValuesMut<'a, K, V, H>
767where
768    K: BorshSerialize + Ord + BorshDeserialize,
769    V: BorshSerialize,
770    H: ToKey,
771{
772    pub(super) fn new(map: &'a mut TreeMap<K, V, H>) -> Self {
773        Self { inner: map.iter_mut() }
774    }
775}
776
777impl<'a, K, V, H> Iterator for ValuesMut<'a, K, V, H>
778where
779    K: BorshSerialize + Ord + BorshDeserialize + Clone,
780    V: BorshSerialize + BorshDeserialize,
781    H: ToKey,
782{
783    type Item = &'a mut V;
784
785    fn next(&mut self) -> Option<Self::Item> {
786        <Self as Iterator>::nth(self, 0)
787    }
788
789    fn nth(&mut self, n: usize) -> Option<Self::Item> {
790        self.inner.nth(n).map(|(_, v)| v)
791    }
792
793    fn size_hint(&self) -> (usize, Option<usize>) {
794        self.inner.size_hint()
795    }
796
797    fn count(self) -> usize {
798        self.inner.count()
799    }
800}
801
802impl<'a, K, V, H> ExactSizeIterator for ValuesMut<'a, K, V, H>
803where
804    K: BorshSerialize + Ord + BorshDeserialize + Clone,
805    V: BorshSerialize + BorshDeserialize,
806    H: ToKey,
807{
808}
809impl<'a, K, V, H> FusedIterator for ValuesMut<'a, K, V, H>
810where
811    K: BorshSerialize + Ord + BorshDeserialize + Clone,
812    V: BorshSerialize + BorshDeserialize,
813    H: ToKey,
814{
815}
816
817impl<'a, K, V, H> DoubleEndedIterator for ValuesMut<'a, K, V, H>
818where
819    K: BorshSerialize + Ord + BorshDeserialize + Clone,
820    V: BorshSerialize + BorshDeserialize,
821    H: ToKey,
822{
823    fn next_back(&mut self) -> Option<Self::Item> {
824        <Self as DoubleEndedIterator>::nth_back(self, 0)
825    }
826
827    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
828        self.inner.nth_back(n).map(|(_, v)| v)
829    }
830}
831
832/// An iterator over a range of elements of a [`TreeMap`], in sorted order.
833///
834/// This `struct` is created by the `iter` method on [`TreeMap`].
835pub struct Range<'a, K, V, H>
836where
837    K: BorshSerialize + Ord + BorshDeserialize,
838    V: BorshSerialize,
839    H: ToKey,
840{
841    keys: KeysRange<'a, K>,
842    values: &'a LookupMap<K, V, H>,
843}
844
845impl<'a, K, V, H> Range<'a, K, V, H>
846where
847    K: BorshSerialize + Ord + BorshDeserialize,
848    V: BorshSerialize,
849    H: ToKey,
850{
851    pub(super) fn new<Q>(map: &'a TreeMap<K, V, H>, bounds: (Bound<&Q>, Bound<&Q>)) -> Self
852    where
853        K: Borrow<Q>,
854        Q: ?Sized + Ord,
855    {
856        Self { keys: KeysRange::new(&map.tree, bounds), values: &map.values }
857    }
858}
859
860impl<'a, K, V, H> Iterator for Range<'a, K, V, H>
861where
862    K: BorshSerialize + Ord + BorshDeserialize + Clone,
863    V: BorshSerialize + BorshDeserialize,
864    H: ToKey,
865{
866    type Item = (&'a K, &'a V);
867
868    fn next(&mut self) -> Option<Self::Item> {
869        <Self as Iterator>::nth(self, 0)
870    }
871
872    fn nth(&mut self, n: usize) -> Option<Self::Item> {
873        let key = self.keys.nth(n)?;
874        let entry = expect(self.values.get(key));
875
876        Some((key, entry))
877    }
878
879    fn size_hint(&self) -> (usize, Option<usize>) {
880        self.keys.size_hint()
881    }
882}
883
884impl<'a, K, V, H> FusedIterator for Range<'a, K, V, H>
885where
886    K: BorshSerialize + Ord + BorshDeserialize + Clone,
887    V: BorshSerialize + BorshDeserialize,
888    H: ToKey,
889{
890}
891
892impl<'a, K, V, H> DoubleEndedIterator for Range<'a, K, V, H>
893where
894    K: BorshSerialize + Ord + BorshDeserialize + Clone,
895    V: BorshSerialize + BorshDeserialize,
896    H: ToKey,
897{
898    fn next_back(&mut self) -> Option<Self::Item> {
899        <Self as DoubleEndedIterator>::nth_back(self, 0)
900    }
901
902    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
903        let key = self.keys.nth_back(n)?;
904        let entry = expect(self.values.get(key));
905
906        Some((key, entry))
907    }
908}
909
910/// A mutable iterator over a range of elements of a [`TreeMap`], in sorted order.
911///
912/// This `struct` is created by the `iter_mut` method on [`TreeMap`].
913pub struct RangeMut<'a, K, V, H>
914where
915    K: BorshSerialize + Ord + BorshDeserialize,
916    V: BorshSerialize,
917    H: ToKey,
918{
919    keys: KeysRange<'a, K>,
920    /// Exclusive reference to underlying map to lookup values with `keys`.
921    values: &'a mut LookupMap<K, V, H>,
922}
923
924impl<'a, K, V, H> RangeMut<'a, K, V, H>
925where
926    K: BorshSerialize + Ord + BorshDeserialize,
927    V: BorshSerialize,
928    H: ToKey,
929{
930    pub(super) fn new<Q>(map: &'a mut TreeMap<K, V, H>, bounds: (Bound<&Q>, Bound<&Q>)) -> Self
931    where
932        K: Borrow<Q>,
933        Q: ?Sized + Ord,
934    {
935        Self { keys: KeysRange::new(&map.tree, bounds), values: &mut map.values }
936    }
937}
938
939impl<'a, K, V, H> Iterator for RangeMut<'a, K, V, H>
940where
941    K: BorshSerialize + Ord + BorshDeserialize + Clone,
942    V: BorshSerialize + BorshDeserialize,
943    H: ToKey,
944{
945    type Item = (&'a K, &'a mut V);
946
947    fn next(&mut self) -> Option<Self::Item> {
948        <Self as Iterator>::nth(self, 0)
949    }
950
951    fn nth(&mut self, n: usize) -> Option<Self::Item> {
952        let key = self.keys.nth(n)?;
953        Some(get_entry_mut(self.values, key))
954    }
955
956    fn size_hint(&self) -> (usize, Option<usize>) {
957        self.keys.size_hint()
958    }
959}
960
961impl<'a, K, V, H> FusedIterator for RangeMut<'a, K, V, H>
962where
963    K: BorshSerialize + Ord + BorshDeserialize + Clone,
964    V: BorshSerialize + BorshDeserialize,
965    H: ToKey,
966{
967}
968
969impl<'a, K, V, H> DoubleEndedIterator for RangeMut<'a, K, V, H>
970where
971    K: BorshSerialize + Ord + BorshDeserialize + Clone,
972    V: BorshSerialize + BorshDeserialize,
973    H: ToKey,
974{
975    fn next_back(&mut self) -> Option<Self::Item> {
976        <Self as DoubleEndedIterator>::nth_back(self, 0)
977    }
978
979    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
980        let key = self.keys.nth_back(n)?;
981        Some(get_entry_mut(self.values, key))
982    }
983}
984
985#[derive(Debug, Copy, Clone)]
986enum Find<K> {
987    /// Find the first element based on bound.
988    First { bound: Bound<K> },
989    /// Find the next element from current pos
990    Next { bound: Bound<K> },
991}
992
993impl<K> Find<K> {
994    fn into_value(self) -> Bound<K> {
995        match self {
996            Find::First { bound } => bound,
997            Find::Next { bound } => bound,
998        }
999    }
1000}
1001
1002#[unc(inside_uncsdk)]
1003#[derive(Debug, Copy, Clone)]
1004enum FindUnbounded {
1005    /// Find the first element in the given root
1006    First,
1007    /// Find the next element from current pos
1008    Next,
1009}