valord_map/
lib.rs

1#![feature(let_chains)]
2#![doc = include_str!("../README.md")]
3#![doc(html_playground_url = "https://play.rust-lang.org")]
4mod order_by;
5pub use order_by::OrdBy;
6
7mod entry;
8pub use entry::{Entry, RawEntry};
9
10use indexmap::{map::MutableKeys, IndexMap};
11use std::{
12    collections::{BTreeMap, HashSet, VecDeque},
13    hash::Hash,
14};
15
16pub struct ValordMap<T, K, V: OrdBy<Target = T>> {
17    map: IndexMap<K, Option<V>>,
18    sorted_indexs: BTreeMap<T, HashSet<usize>>,
19
20    free_indexs: VecDeque<usize>,
21}
22
23impl<T, K, V> ValordMap<T, K, V>
24where
25    T: Ord + Clone,
26    K: Hash + Eq,
27    V: OrdBy<Target = T>,
28{
29    pub fn new() -> Self {
30        ValordMap {
31            map: IndexMap::new(),
32            sorted_indexs: BTreeMap::new(),
33            free_indexs: VecDeque::new(),
34        }
35    }
36
37    /// insert into ValordMap
38    ///
39    /// # Example
40    ///
41    /// ```
42    /// use valord_map::ValordMap;
43    ///
44    /// let mut valord = ValordMap::new();
45    /// valord.insert("qians", 1);
46    /// valord.insert("tedious", 2);
47    /// valord.insert("xuandu", 3);
48    /// valord.insert("xuandu", 1);
49    ///
50    /// let sorted_pairs: Vec<_> = valord.iter().collect();
51    ///
52    /// println!("{:?}", sorted_pairs);
53    ///
54    /// assert_eq!(sorted_pairs.len(), 3);
55    /// assert_eq!(sorted_pairs[0].1, &1);
56    /// assert_eq!(sorted_pairs[1].1, &1);
57    /// assert_eq!(sorted_pairs[2], (&"tedious", &2));
58    /// ```
59    pub fn insert(&mut self, key: K, value: V) {
60        // let key: Arc<_> = key.into();
61        self._insert(key, value)
62    }
63
64    fn _insert(&mut self, key: K, value: V) {
65        let ord_by = value.ord_by();
66
67        let index = if let Some((index, _k, old_val)) = self.map.get_full_mut(&key) {
68            if let Some(old_val) = old_val {
69                Self::remove_from_indexs(&mut self.sorted_indexs, &old_val.ord_by(), index);
70                *old_val = value;
71            }
72            index
73        } else if let Some(free_index) = self.free_indexs.front().copied()
74            && let Some((k, v)) = self.map.get_index_mut2(free_index)
75        {
76            *k = key;
77            *v = Some(value);
78            self.free_indexs.pop_front();
79            free_index
80        } else {
81            self.map.insert_full(key, Some(value)).0
82        };
83
84        self.sorted_indexs.entry(ord_by).or_default().insert(index);
85    }
86
87    /// Get the given key’s corresponding entry in the map for insertion and/or
88    /// in-place manipulation
89    ///
90    /// # Examples
91    ///
92    /// ```
93    /// use valord_map::ValordMap;
94    ///
95    /// let mut map = ValordMap::new();
96    /// map.entry("key").and_modify(|v| *v = "new value").or_insert("value");
97    ///
98    /// assert_eq!(map.get(&"key"), Some(&"value"));
99    ///
100    /// map.entry("key").and_modify(|v| *v = "new value").or_insert("value");
101    ///
102    /// assert_eq!(map.get(&"key"), Some(&"new value"));
103    /// ```
104    pub fn entry(&mut self, key: K) -> Entry<'_, T, K, V> {
105        let valord = self;
106        match valord.map.get_full(&key) {
107            Some((index, _, Some(_))) => return Entry::Occupied(RawEntry { index, valord }),
108            Some((index, _, None)) => return Entry::Vacant(RawEntry { index, valord }),
109            None => {}
110        }
111
112        let index = if let Some(free_index) = valord.free_indexs.front().copied() {
113            free_index
114        } else {
115            let index_entry = valord.map.entry(key);
116            let index = index_entry.index();
117            index_entry.or_insert(None);
118            valord.free_indexs.push_front(index);
119            index
120        };
121
122        Entry::Vacant(RawEntry { index, valord })
123    }
124
125    /// Returns an iterator over the ValordMap.
126    /// The iterator yields all items from start to end order by value.ord_by().
127    ///
128    /// # Example
129    ///
130    /// ```
131    /// use valord_map::ValordMap;
132    ///
133    /// let mut valord = ValordMap::new();
134    /// valord.insert("qians", 1);
135    /// valord.insert("tedious", 2);
136    /// valord.insert("xuandu", 3);
137    /// valord.insert("xuandu", 1);
138    ///
139    /// let mut iter = valord.iter();
140    ///
141    /// assert_eq!(iter.next().unwrap().1, &1);
142    /// assert_eq!(iter.next().unwrap().1, &1);
143    /// assert_eq!(iter.next().unwrap(), (&"tedious", &2));
144    /// ```
145    pub fn iter(&self) -> impl Iterator<Item = (&K, &V)> {
146        self.sorted_indexs
147            .iter()
148            .flat_map(|(_, indexs)| indexs.iter().filter_map(|index| self.get_by_index(*index)))
149    }
150
151    /// Returns an reversesed iterator over the ValordMap.
152    /// The iterator yields all items from start to end order by value.ord_by().
153    ///
154    /// # Example
155    ///
156    /// ```
157    /// use valord_map::ValordMap;
158    ///
159    /// let mut valord = ValordMap::new();
160    /// valord.insert("qians", 1);
161    /// valord.insert("tedious", 2);
162    /// valord.insert("xuandu", 3);
163    /// valord.insert("xuandu", 1);
164    ///
165    /// let mut iter = valord.rev_iter();
166    ///
167    /// assert_eq!(iter.next().unwrap(), (&"tedious", &2));
168    /// assert_eq!(iter.next().unwrap().1, &1);
169    /// assert_eq!(iter.next().unwrap().1, &1);
170    /// ```
171    pub fn rev_iter(&self) -> impl Iterator<Item = (&K, &V)> {
172        self.sorted_indexs
173            .iter()
174            .rev()
175            .flat_map(|(_, indexs)| indexs.iter().filter_map(|index| self.get_by_index(*index)))
176    }
177
178    /// Returns an mut iterator over the ValordMap.
179    /// The iterator yields all items from start to end order by value.ord_by().
180    ///
181    /// # Example
182    ///
183    /// ```
184    /// use valord_map::ValordMap;
185    ///
186    /// let mut valord = ValordMap::new();
187    /// valord.insert("qians", 1);
188    /// valord.insert("tedious", 2);
189    /// valord.insert("xuandu", 3);
190    ///
191    ///
192    /// let mut iter = valord.iter_mut();
193    ///
194    /// let mut item1 = iter.next().unwrap();
195    /// let (k, v) = item1.get_mut_with_key();
196    /// assert_eq!(v, &mut 1);
197    /// *v = 4;
198    /// drop(item1);
199    ///
200    /// assert_eq!(iter.next().unwrap().get_mut_with_key(), (&"tedious", &mut 2));
201    /// assert_eq!(iter.next().unwrap().get_mut_with_key(), (&"xuandu", &mut 3));
202    /// assert!(iter.next().is_none());
203    /// drop(iter);
204    ///
205    /// let max_list = valord.last();
206    /// assert_eq!(max_list.len(), 1);
207    /// assert_eq!(max_list, vec![(&"qians", &4)]);
208    /// ```
209    pub fn iter_mut(&mut self) -> impl Iterator<Item = RawEntry<'_, T, K, V>> {
210        let indexs: Vec<_> = self
211            .sorted_indexs
212            .iter()
213            .flat_map(|(_, indexs)| indexs.iter())
214            .copied()
215            .collect();
216        let valord: *mut ValordMap<T, K, V> = self;
217        indexs.into_iter().filter_map(move |index| {
218            let vm = unsafe { valord.as_mut()? };
219            vm.get_mut_by_index(index)
220        })
221    }
222
223    /// Returns an reversesed mut iterator over the ValordMap.
224    /// The iterator yields all items from start to end order by value.ord_by().
225    ///
226    /// # Example
227    ///
228    /// ```
229    /// use valord_map::ValordMap;
230    ///
231    /// let mut valord = ValordMap::new();
232    /// valord.insert("qians", 1);
233    /// valord.insert("tedious", 2);
234    /// valord.insert("xuandu", 3);
235    ///
236    ///
237    /// let mut iter = valord.rev_iter_mut();
238    ///
239    /// let mut item1 = iter.next().unwrap();
240    /// let (k, v) = item1.get_mut_with_key();
241    /// assert_eq!(v, &mut 3);
242    /// *v = 0;
243    /// drop(item1);
244    ///
245    /// assert_eq!(iter.next().unwrap().get_mut_with_key(), (&"tedious", &mut 2));
246    /// assert_eq!(iter.next().unwrap().get_mut_with_key(), (&"qians", &mut 1));
247    /// assert!(iter.next().is_none());
248    /// drop(iter);
249    ///
250    /// let max_list = valord.first();
251    /// assert_eq!(max_list.len(), 1);
252    /// assert_eq!(max_list, vec![(&"xuandu", &0)]);
253    /// ```
254    pub fn rev_iter_mut(&mut self) -> impl Iterator<Item = RawEntry<'_, T, K, V>> {
255        let indexs: Vec<_> = self
256            .sorted_indexs
257            .iter()
258            .rev()
259            .flat_map(|(_, indexs)| indexs.iter())
260            .copied()
261            .collect();
262        let valord: *mut ValordMap<T, K, V> = self;
263        indexs.into_iter().filter_map(move |index| {
264            let vm = unsafe { valord.as_mut()? };
265            vm.get_mut_by_index(index)
266        })
267    }
268
269    /// Returns the first vector of key-value pairs in the map. The value in this pair is the minimum values in the map.
270    ///
271    /// # Example
272    ///
273    /// ```
274    /// use valord_map::ValordMap;
275    ///
276    /// let mut valord = ValordMap::new();
277    /// valord.insert("qians", 1);
278    /// valord.insert("tedious", 2);
279    /// valord.insert("xuandu", 3);
280    /// valord.insert("xuandu", 1);
281    ///
282    /// let min_list = valord.first();
283    ///
284    /// assert_eq!(min_list.len(), 2);
285    /// assert!(min_list.iter().all(|(_, v)| **v == 1));
286    /// ```
287    pub fn first(&self) -> Vec<(&K, &V)> {
288        self.sorted_indexs
289            .first_key_value()
290            .map(|(_, indexs)| self.iter_from_indexs(indexs).collect())
291            .unwrap_or_default()
292    }
293
294    /// Returns the first vector of key-value mut pairs in the map. The value in this pair is the minimum values in the map.
295    ///
296    /// # Example
297    ///
298    /// ```
299    /// use valord_map::ValordMap;
300    ///
301    /// let mut valord = ValordMap::new();
302    /// valord.insert("qians", 1);
303    /// valord.insert("tedious", 2);
304    /// valord.insert("xuandu", 3);
305    /// valord.insert("xuandu", 1);
306    ///
307    /// let mut min_list = valord.first_mut();
308    /// assert_eq!(min_list.len(), 2);
309    /// min_list.iter_mut().for_each(|entry| {
310    ///     let (_k, v) = entry.get_mut_with_key();
311    ///     *v = 0;
312    /// });
313    /// drop(min_list);
314    ///
315    /// let min_list = valord.first();
316    /// assert!(min_list.iter().all(|(_, v)| **v == 0));
317    /// ```
318    pub fn first_mut(&mut self) -> Vec<RawEntry<'_, T, K, V>> {
319        let valord: *mut ValordMap<T, K, V> = self;
320        self.sorted_indexs
321            .first_key_value()
322            .map(|(_, indexs)| Self::iter_mut_from_indexs(valord, indexs.clone()).collect())
323            .unwrap_or_default()
324    }
325
326    /// Returns the last vector of key-value pairs in the map. The value in this pair is the maximum values in the map.
327    ///
328    /// # Example
329    ///
330    /// ```
331    /// use valord_map::ValordMap;
332    ///
333    /// let mut valord = ValordMap::new();
334    /// valord.insert("qians", 1);
335    /// valord.insert("tedious", 2);
336    /// valord.insert("xuandu", 3);
337    /// valord.insert("xuandu", 1);
338    ///
339    /// let max_list = valord.last();
340    ///
341    /// assert_eq!(max_list.len(), 1);
342    /// assert_eq!(max_list, vec![(&"tedious", &2)]);
343    /// ```
344    pub fn last(&self) -> Vec<(&K, &V)> {
345        self.sorted_indexs
346            .last_key_value()
347            .map(|(_, indexs)| self.iter_from_indexs(indexs).collect())
348            .unwrap_or_default()
349    }
350
351    /// Returns the last vector of key-value mut pairs in the map. The value in this pair is the minimum values in the map.
352    ///
353    /// # Example
354    ///
355    /// ```
356    /// use valord_map::ValordMap;
357    ///
358    /// let mut valord = ValordMap::new();
359    /// valord.insert("qians", 1);
360    /// valord.insert("tedious", 2);
361    /// valord.insert("xuandu", 3);
362    /// valord.insert("sheng", 4);
363    ///
364    /// let mut max_list = valord.last_mut();
365    /// assert_eq!(max_list.len(), 1);
366    /// let (k, v) = max_list[0].get_mut_with_key();
367    /// assert_eq!((&k, &v), (&&"sheng", &&mut 4));
368    ///
369    /// *v = 2;
370    /// drop(max_list);
371    ///
372    /// let max_list = valord.last();
373    /// assert_eq!(max_list.len(), 1);
374    /// assert_eq!(max_list, vec![(&"xuandu", &3)]);
375    /// ```
376    pub fn last_mut(&mut self) -> Vec<RawEntry<'_, T, K, V>> {
377        let valord: *mut ValordMap<T, K, V> = self;
378        self.sorted_indexs
379            .last_key_value()
380            .map(|(_, indexs)| Self::iter_mut_from_indexs(valord, indexs.clone()).collect())
381            .unwrap_or_default()
382    }
383
384    /// get range from ValordMap
385    ///
386    /// # Example
387    ///
388    /// ```
389    /// use valord_map::ValordMap;
390    ///
391    /// let mut valord = ValordMap::new();
392    /// valord.insert("qians", 1);
393    /// valord.insert("tedious", 2);
394    /// valord.insert("sheng", 3);
395    /// valord.insert("xuandu", 4);
396    /// valord.insert("xuandu2", 5);
397    /// valord.insert("xuandu3", 6);
398    /// assert_eq!(valord.range(4..).last().unwrap(), (&"xuandu3", &6));
399    /// assert_eq!(
400    ///     valord
401    ///         .range(4..)
402    ///         .filter(|(_, v)| **v != 6)
403    ///         .last()
404    ///         .unwrap(),
405    ///     (&"xuandu2", &5)
406    /// );
407    /// ```
408    pub fn range<R>(&self, range: R) -> impl Iterator<Item = (&K, &V)>
409    where
410        R: std::ops::RangeBounds<V::Target>,
411    {
412        self.sorted_indexs
413            .range(range)
414            .flat_map(|(_, indexs)| self.iter_from_indexs(indexs))
415    }
416
417    /// get range mut from ValordMap
418    ///
419    /// # Example
420    ///
421    /// ```
422    /// use valord_map::ValordMap;
423    ///
424    /// let mut valord = ValordMap::new();
425    /// valord.insert("qians", 1);
426    /// valord.insert("tedious", 2);
427    /// valord.insert("sheng", 3);
428    /// valord.insert("xuandu", 4);
429    /// valord.insert("xuandu2", 5);
430    /// valord.insert("xuandu3", 6);
431    ///
432    /// let mut range_iter = valord.range_mut(4..);
433    ///
434    /// let mut item1 = range_iter.next().unwrap();
435    /// let (k, v) = item1.get_mut_with_key();
436    /// assert_eq!(k, &"xuandu");
437    /// assert_eq!(v, &mut 4);
438    /// *v += 4;
439    /// drop(item1);
440    /// drop(range_iter);
441    ///
442    /// assert_eq!(
443    ///     valord
444    ///         .range(4..)
445    ///         .last(),
446    ///     Some((&"xuandu", &8))
447    /// );
448    /// ```
449    pub fn range_mut<R>(&mut self, range: R) -> impl Iterator<Item = RawEntry<'_, T, K, V>>
450    where
451        R: std::ops::RangeBounds<V::Target>,
452    {
453        let range: Vec<_> = self
454            .sorted_indexs
455            .range(range)
456            .flat_map(|(_, indexs)| indexs.iter())
457            .copied()
458            .collect();
459        let valord: *mut ValordMap<T, K, V> = self;
460        range.into_iter().filter_map(move |index| {
461            let vm = unsafe { valord.as_mut()? };
462            vm.get_mut_by_index(index)
463        })
464    }
465
466    /// Get the ref value by given key, or return `None` if not found
467    ///
468    /// # Example
469    ///
470    /// ```
471    /// use valord_map::ValordMap;
472    ///
473    /// let mut valord = ValordMap::new();
474    /// valord.insert("key1", 1);
475    /// valord.insert("key2", 2);
476    /// valord.insert("key3", 3);
477    ///
478    /// let mut val1 = valord.get(&"key2");
479    /// let mut val2 = valord.get(&"key4");
480    /// assert_eq!(val1.unwrap(), &2);
481    /// assert_eq!(val2, None);
482    /// ```
483    pub fn get(&self, key: &K) -> Option<&V> {
484        self.map.get(key).and_then(|v| v.as_ref())
485    }
486
487    /// Get the ref mut value by given key, or return `None` if not found
488    ///
489    /// # Example
490    ///
491    /// ```
492    /// use valord_map::ValordMap;
493    ///
494    /// let mut valord = ValordMap::new();
495    /// valord.insert("key1", 1);
496    /// valord.insert("key2", 2);
497    /// valord.insert("key3", 3);
498    ///
499    /// let mut val = valord.get_mut(&"key2").unwrap();
500    /// *val = 4;
501    /// drop(val);
502    /// assert_eq!(valord.get(&"key2").unwrap(), &4);
503    /// assert_eq!(valord.last(), vec![(&"key2", &4)]);
504    /// ```
505    pub fn get_mut<'a>(&'a mut self, key: &K) -> Option<RawEntry<'a, T, K, V>> {
506        RawEntry::try_new_by_key(self, key)
507    }
508
509    /// Modify value in map, if exist return true, else return false
510    ///
511    /// # Example
512    ///
513    /// ```
514    /// use valord_map::ValordMap;
515    ///
516    /// let mut valord = ValordMap::new();
517    /// valord.insert("qians", 1);
518    ///
519    /// assert!(valord.modify(&"qians", |v| *v = 2));
520    /// assert_eq!(valord.iter().next().unwrap(), (&"qians", &2));
521    /// ```
522    pub fn modify<F>(&mut self, key: &K, op: F) -> bool
523    where
524        F: Fn(&mut V),
525    {
526        if let Some((index, _, v)) = Self::get_full_mut(&mut self.map, key) {
527            Self::remove_from_indexs(&mut self.sorted_indexs, &v.ord_by(), index);
528            op(v);
529            self.sorted_indexs
530                .entry(v.ord_by())
531                .or_default()
532                .insert(index);
533            true
534        } else {
535            false
536        }
537    }
538
539    /// remove from ValordMap
540    ///
541    /// # Example
542    ///
543    /// ```
544    /// use valord_map::ValordMap;
545    ///
546    /// let mut valord = ValordMap::new();
547    /// valord.insert(1, "a");
548    /// valord.insert(2, "b");
549    ///
550    /// let removed_value = valord.remove(&1);
551    /// assert_eq!(removed_value, Some("a"));
552    /// assert_eq!(valord.get(&1), None);
553    /// ```
554    pub fn remove(&mut self, key: &K) -> Option<V> {
555        self.remove_entry(key).map(|v| v.1)
556    }
557
558    /// Removes a key from the map, returning the stored key and value if the
559    /// key was previously in the map.
560    ///
561    /// # Example
562    ///
563    /// ```
564    /// use valord_map::ValordMap;
565    ///
566    /// let mut valord = ValordMap::new();
567    /// valord.insert(1, "a");
568    /// valord.insert(2, "b");
569    ///
570    /// let removed_entry = valord.remove_entry(&1);
571    /// assert_eq!(removed_entry, Some((&1, "a")));
572    /// assert_eq!(valord.get(&1), None);
573    /// ```
574    pub fn remove_entry<'a>(&'a mut self, key: &'a K) -> Option<(&K, V)> {
575        if let Some((i, k, v)) = self.map.get_full_mut(key) {
576            if let Some(old) = v.take() {
577                self.free_indexs.push_back(i);
578                Self::remove_from_indexs(&mut self.sorted_indexs, &old.ord_by(), i);
579                return Some((k, old));
580            };
581        }
582        None
583    }
584
585    /// Return the number of key-value pairs in the map.
586    ///
587    /// # Example
588    ///
589    /// ```
590    /// use valord_map::ValordMap;
591    ///
592    /// let mut valord = ValordMap::new();
593    /// valord.insert(1, "a");
594    /// valord.insert(2, "b");
595    /// valord.insert(3, "c");
596    /// valord.insert(2, "d");
597    ///
598    /// assert_eq!(valord.len(), 3);
599    ///
600    /// let removed_value = valord.remove(&1);
601    /// assert_eq!(removed_value, Some("a"));
602    /// assert_eq!(valord.len(), 2);
603    /// ```
604    pub fn len(&self) -> usize {
605        self.map.len() - self.free_indexs.len()
606    }
607
608    /// Re-order the ValordMap by value.ord_by().
609    ///
610    /// # Example
611    ///
612    /// ```
613    /// use std::cell::Cell;
614    /// use valord_map::ValordMap;
615    ///
616    /// let mut valord = ValordMap::new();
617    /// valord.insert("qians", Cell::new(1));
618    /// valord.insert("tedious", Cell::new(2));
619    /// valord.insert("xuandu", Cell::new(3));
620    ///
621    /// valord
622    ///     .iter()
623    ///     .enumerate()
624    ///     .for_each(|(i, (_, v))| v.set(5 - i));
625    ///
626    /// assert_eq!(
627    ///     valord.iter().collect::<Vec<_>>(),
628    ///     vec![
629    ///         (&"qians", &Cell::new(5)),
630    ///         (&"tedious", &Cell::new(4)),
631    ///         (&"xuandu", &Cell::new(3))
632    ///     ]
633    /// );
634    ///
635    /// valord.re_order();
636    ///
637    /// assert_eq!(
638    ///     valord.iter().collect::<Vec<_>>(),
639    ///     vec![
640    ///         (&"xuandu", &Cell::new(3)),
641    ///         (&"tedious", &Cell::new(4)),
642    ///         (&"qians", &Cell::new(5)),
643    ///     ]
644    /// );
645    /// ```
646    pub fn re_order(&mut self) {
647        let mut sorted = BTreeMap::<T, HashSet<usize>>::new();
648        self.map
649            .iter()
650            .enumerate()
651            .filter_map(|(i, (_, v))| v.as_ref().map(|v| (v.ord_by(), i)))
652            .for_each(|(t, i)| {
653                sorted.entry(t).or_default().insert(i);
654            });
655        self.sorted_indexs = sorted;
656    }
657
658    pub fn is_empty(&self) -> bool {
659        self.len() == 0
660    }
661
662    fn get_by_index(&self, index: usize) -> Option<(&K, &V)> {
663        self.map
664            .get_index(index)
665            .and_then(|(k, maybe_val)| maybe_val.as_ref().map(|v| (k, v)))
666    }
667
668    fn get_mut_by_index(&mut self, index: usize) -> Option<RawEntry<'_, T, K, V>> {
669        RawEntry::try_new_by_index(self, index)
670    }
671
672    fn get_full_mut<'a>(
673        map: &'a mut IndexMap<K, Option<V>>,
674        key: &'a K,
675    ) -> Option<(usize, &'a K, &'a mut V)> {
676        map.get_full_mut(key)
677            .and_then(|(i, k, v)| v.as_mut().map(|v| (i, k, v)))
678    }
679
680    fn iter_from_indexs<'a>(
681        &'a self,
682        indexs: &'a HashSet<usize>,
683    ) -> impl Iterator<Item = (&K, &V)> {
684        indexs.iter().filter_map(|index| self.get_by_index(*index))
685    }
686
687    fn iter_mut_from_indexs<'a>(
688        valord: *mut ValordMap<T, K, V>,
689        indexs: HashSet<usize>,
690    ) -> impl Iterator<Item = RawEntry<'a, T, K, V>>
691    where
692        T: 'a,
693        K: 'a,
694        V: 'a,
695    {
696        indexs.into_iter().filter_map(move |index| {
697            let vm = unsafe { valord.as_mut()? };
698            vm.get_mut_by_index(index)
699        })
700    }
701
702    fn remove_from_indexs(sorted_indexs: &mut BTreeMap<T, HashSet<usize>>, key: &T, index: usize) {
703        if let Some(indexs) = sorted_indexs.get_mut(key) {
704            indexs.remove(&index);
705            if indexs.is_empty() {
706                sorted_indexs.remove(key);
707            }
708        }
709    }
710}
711
712impl<T, K, V> Default for ValordMap<T, K, V>
713where
714    T: Ord + Clone,
715    K: std::hash::Hash + Eq,
716    V: OrdBy<Target = T>,
717{
718    fn default() -> Self {
719        Self::new()
720    }
721}
722
723#[cfg(test)]
724mod tests {
725    use std::cell::Cell;
726
727    use super::*;
728
729    #[derive(Debug, PartialEq, Eq)]
730    struct OrdByValue {
731        sth: usize,
732        order_by: usize,
733    }
734
735    impl OrdByValue {
736        fn new(sth: usize, order_by: usize) -> Self {
737            Self { sth, order_by }
738        }
739    }
740
741    impl OrdBy for OrdByValue {
742        type Target = usize;
743
744        fn ord_by(&self) -> Self::Target {
745            self.order_by
746        }
747    }
748
749    #[test]
750    fn test_valord_insert_order_by() {
751        let mut valord = ValordMap::new();
752        valord.insert("qians", OrdByValue::new(123, 1));
753        valord.insert("tedious", OrdByValue::new(412, 2));
754        valord.insert("xuandu", OrdByValue::new(125, 3));
755        valord.insert("xuandu", OrdByValue::new(938, 1));
756
757        let sorted_pairs: Vec<_> = valord.iter().collect();
758
759        assert_eq!(sorted_pairs.len(), 3);
760        assert_eq!(sorted_pairs[0].1.order_by, 1);
761        assert_eq!(sorted_pairs[1].1.order_by, 1);
762        assert_eq!(sorted_pairs[2], (&"tedious", &OrdByValue::new(412, 2)));
763    }
764
765    #[test]
766    fn test_valord_remove_non_existent() {
767        let mut valord = ValordMap::new();
768        valord.insert(1, "a");
769        valord.insert(2, "b");
770
771        let removed_value = valord.remove(&3);
772        assert_eq!(removed_value, None);
773        assert_eq!(valord.get(&3), None);
774    }
775
776    #[test]
777    fn test_valord_multiple_insert_and_remove() {
778        let mut valord = ValordMap::new();
779        valord.insert("qians", 1);
780        valord.insert("tedious", 2);
781        valord.insert("xuandu", 3);
782
783        assert_eq!(valord.remove(&"tedious"), Some(2));
784        assert_eq!(valord.remove(&"qians"), Some(1));
785
786        valord.insert("x", 2);
787        valord.insert("y", 4);
788
789        let sorted_pairs: Vec<_> = valord.iter().collect();
790        println!("sorted_pairs: {sorted_pairs:?}");
791        assert_eq!(sorted_pairs.len(), 3);
792        assert_eq!(sorted_pairs[0], (&"x", &2));
793        assert_eq!(sorted_pairs[1], (&"xuandu", &3));
794        assert_eq!(sorted_pairs[2], (&"y", &4));
795    }
796
797    #[test]
798    fn re_order() {
799        let mut valord = ValordMap::new();
800        valord.insert("qians", Cell::new(1));
801        valord.insert("tedious", Cell::new(2));
802        valord.insert("xuandu", Cell::new(3));
803
804        valord
805            .iter()
806            .enumerate()
807            .for_each(|(i, (_, v))| v.set(5 - i));
808
809        assert_eq!(
810            valord.iter().collect::<Vec<_>>(),
811            vec![
812                (&"qians", &Cell::new(5)),
813                (&"tedious", &Cell::new(4)),
814                (&"xuandu", &Cell::new(3))
815            ]
816        );
817
818        valord.re_order();
819
820        assert_eq!(
821            valord.iter().collect::<Vec<_>>(),
822            vec![
823                (&"xuandu", &Cell::new(3)),
824                (&"tedious", &Cell::new(4)),
825                (&"qians", &Cell::new(5)),
826            ]
827        );
828    }
829}