1use crate::{OrdBy, ValordMap};
2
3use std::hash::Hash;
4use std::ops::{Deref, DerefMut};
5
6pub struct RawEntry<'v, T, K, V>
7where
8 T: Ord + Clone,
9 K: Hash + Eq,
10 V: OrdBy<Target = T>,
11{
12 pub(crate) index: usize,
13 pub(crate) valord: &'v mut ValordMap<T, K, V>,
14}
15
16impl<'v, T, K, V> RawEntry<'v, T, K, V>
17where
18 T: Ord + Clone,
19 K: Hash + Eq,
20 V: OrdBy<Target = T>,
21{
22 pub(crate) fn try_new_by_key<'a: 'v>(
23 valord: &'a mut ValordMap<T, K, V>,
24 key: &K,
25 ) -> Option<RawEntry<'v, T, K, V>> {
26 let (index, _, v) = valord.map.get_full(key)?;
27 v.as_ref()?;
28 Some(Self { index, valord })
29 }
30
31 pub(crate) fn try_new_by_index<'a: 'v>(
32 valord: &'a mut ValordMap<T, K, V>,
33 index: usize,
34 ) -> Option<RawEntry<'v, T, K, V>> {
35 valord.get_by_index(index)?;
36 Some(Self { index, valord })
37 }
38
39 pub(crate) fn insert(&mut self, value: V) -> &mut V {
40 let v = self
41 .valord
42 .map
43 .get_index_mut(self.index)
44 .map(|(_, v)| {
45 if let Some(ref v) = v {
46 ValordMap::<T, K, V>::remove_from_indexs(
47 &mut self.valord.sorted_indexs,
48 &v.ord_by(),
49 self.index,
50 );
51 }
52 v.insert(value)
53 })
54 .unwrap();
55 v
56 }
57
58 pub(crate) fn insert_with_key<F: FnOnce(&K) -> V>(&mut self, value: F) -> &mut V {
59 let v = self
60 .valord
61 .map
62 .get_index_mut(self.index)
63 .map(|(k, v)| {
64 if let Some(ref v) = v {
65 ValordMap::<T, K, V>::remove_from_indexs(
66 &mut self.valord.sorted_indexs,
67 &v.ord_by(),
68 self.index,
69 );
70 }
71 v.insert(value(k))
72 })
73 .unwrap();
74 v
75 }
76
77 pub fn get_mut_with_key(&mut self) -> (&K, &mut V) {
78 let (k, v) = self
79 .valord
80 .map
81 .get_index_mut(self.index)
82 .map(|(k, v)| (k, v.as_mut().unwrap()))
83 .unwrap();
84 ValordMap::<T, K, V>::remove_from_indexs(
85 &mut self.valord.sorted_indexs,
86 &v.ord_by(),
87 self.index,
88 );
89
90 (k, v)
91 }
92}
93
94impl<'a, T, K, V> Deref for RawEntry<'a, T, K, V>
95where
96 T: Ord + Clone,
97 K: Hash + Eq,
98 V: OrdBy<Target = T>,
99{
100 type Target = V;
101
102 fn deref(&self) -> &Self::Target {
103 self.valord
105 .get_by_index(self.index)
106 .map(|(_, v)| v)
107 .unwrap()
108 }
109}
110
111impl<'a, T, K, V> DerefMut for RawEntry<'a, T, K, V>
112where
113 T: Ord + Clone,
114 K: Hash + Eq,
115 V: OrdBy<Target = T>,
116{
117 fn deref_mut(&mut self) -> &mut Self::Target {
118 self.get_mut_with_key().1
120 }
121}
122
123impl<'a, T, K, V> Drop for RawEntry<'a, T, K, V>
124where
125 T: Ord + Clone,
126 K: Hash + Eq,
127 V: OrdBy<Target = T>,
128{
129 fn drop(&mut self) {
130 if let Some(ord_by) = self
131 .valord
132 .get_by_index(self.index)
133 .map(|(_, v)| v.ord_by().clone())
134 {
135 self.valord
136 .sorted_indexs
137 .entry(ord_by)
138 .or_default()
139 .insert(self.index);
140 };
141 }
142}