multiversx_sc/storage/mappers/
bi_di_mapper.rs

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
use core::marker::PhantomData;

use crate::{
    abi::TypeAbiFrom,
    codec::{
        multi_encode_iter_or_handle_err, multi_types::MultiValue2, EncodeErrorHandler,
        NestedDecode, NestedEncode, TopDecode, TopEncode, TopEncodeMulti, TopEncodeMultiOutput,
    },
    types::ManagedAddress,
};

use super::{
    set_mapper::{CurrentStorage, StorageAddress},
    unordered_set_mapper, StorageMapper, StorageMapperFromAddress, UnorderedSetMapper,
};
use crate::{
    abi::{TypeAbi, TypeDescriptionContainer, TypeName},
    api::StorageMapperApi,
    storage::{storage_set, StorageKey},
    storage_clear,
    types::{ManagedType, MultiValueEncoded},
};

const VALUE_SUFIX: &[u8] = b"_value";
const ID_SUFIX: &[u8] = b"_id";
const VALUE_TO_ID_SUFFIX: &[u8] = b"_value_to_id";
const ID_TO_VALUE_SUFFIX: &[u8] = b"_id_to_value";

type Keys<'a, SA, T, A> = unordered_set_mapper::Iter<'a, SA, T, A>;

/// A bi-directional map, from values to ids and viceversa.
/// The mapper is based on UnorderedSetMapper, reason why the remove is done by swap_remove
pub struct BiDiMapper<SA, K, V, A = CurrentStorage>
where
    SA: StorageMapperApi,
    A: StorageAddress<SA>,
    K: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
    V: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
{
    _phantom_api: PhantomData<SA>,
    address: A,
    id_set_mapper: UnorderedSetMapper<SA, K, A>,
    value_set_mapper: UnorderedSetMapper<SA, V, A>,
    base_key: StorageKey<SA>,
}

impl<SA, K, V> StorageMapper<SA> for BiDiMapper<SA, K, V, CurrentStorage>
where
    SA: StorageMapperApi,
    K: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
    V: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
{
    fn new(base_key: StorageKey<SA>) -> Self {
        let mut id_key = base_key.clone();
        id_key.append_bytes(ID_SUFIX);

        let mut value_key = base_key.clone();
        value_key.append_bytes(VALUE_SUFIX);
        BiDiMapper {
            _phantom_api: PhantomData,
            address: CurrentStorage,
            id_set_mapper: UnorderedSetMapper::<SA, K>::new(id_key),
            value_set_mapper: UnorderedSetMapper::<SA, V>::new(value_key),
            base_key,
        }
    }
}

impl<SA, K, V> StorageMapperFromAddress<SA> for BiDiMapper<SA, K, V, ManagedAddress<SA>>
where
    SA: StorageMapperApi,
    K: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
    V: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
{
    fn new_from_address(address: ManagedAddress<SA>, base_key: StorageKey<SA>) -> Self {
        let mut id_key = base_key.clone();
        id_key.append_bytes(ID_SUFIX);

        let mut value_key = base_key.clone();
        value_key.append_bytes(VALUE_SUFIX);
        BiDiMapper {
            _phantom_api: PhantomData,
            address: address.clone(),
            id_set_mapper: UnorderedSetMapper::new_from_address(address.clone(), id_key),
            value_set_mapper: UnorderedSetMapper::new_from_address(address, value_key),
            base_key,
        }
    }
}

impl<SA, K, V, A> BiDiMapper<SA, K, V, A>
where
    SA: StorageMapperApi,
    A: StorageAddress<SA>,
    K: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
    V: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
{
    fn get_id_key(&self, value: &V) -> StorageKey<SA> {
        let mut key = self.base_key.clone();
        key.append_bytes(VALUE_TO_ID_SUFFIX);
        key.append_item(value);
        key
    }

    fn get_value_key(&self, key: &K) -> StorageKey<SA> {
        let mut value = self.base_key.clone();
        value.append_bytes(ID_TO_VALUE_SUFFIX);
        value.append_item(&key);
        value
    }

    pub fn get_id(&self, value: &V) -> K {
        self.address
            .address_storage_get(self.get_id_key(value).as_ref())
    }

    pub fn get_value(&self, id: &K) -> V {
        self.address
            .address_storage_get(self.get_value_key(id).as_ref())
    }

    pub fn contains_id(&self, id: &K) -> bool {
        self.id_set_mapper.contains(id)
    }

    pub fn contains_value(&self, value: &V) -> bool {
        self.value_set_mapper.contains(value)
    }

    pub fn get_all_values(&self) -> unordered_set_mapper::Iter<SA, V, A> {
        self.value_set_mapper.iter()
    }

    pub fn get_all_ids(&self) -> unordered_set_mapper::Iter<SA, K, A> {
        self.id_set_mapper.iter()
    }

    pub fn iter(&self) -> Iter<SA, K, V, A> {
        Iter::new(self)
    }

    pub fn is_empty(&self) -> bool {
        self.value_set_mapper.is_empty()
    }

    pub fn len(&self) -> usize {
        self.value_set_mapper.len()
    }
}

impl<SA, K, V> BiDiMapper<SA, K, V, CurrentStorage>
where
    SA: StorageMapperApi,
    K: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
    V: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
{
    fn set_id(&mut self, value: &V, id: &K) {
        storage_set(self.get_id_key(value).as_ref(), id);
    }

    fn set_value(&mut self, id: &K, value: &V) {
        storage_set(self.get_value_key(id).as_ref(), value);
    }

    fn clear_id_by_value(&self, value: &V) {
        storage_clear(self.get_id_key(value).as_ref());
    }
    fn clear_value_by_id(&self, id: &K) {
        storage_clear(self.get_value_key(id).as_ref());
    }

    pub fn insert(&mut self, id: K, value: V) -> bool {
        if self.contains_id(&id) || self.contains_value(&value) {
            return false;
        }
        self.set_id(&value, &id);
        self.set_value(&id, &value);

        self.id_set_mapper.insert(id);
        self.value_set_mapper.insert(value);
        true
    }

    pub fn remove_by_id(&mut self, id: &K) -> bool {
        if self.id_set_mapper.swap_remove(id) {
            let value = self.get_value(id);
            self.clear_id_by_value(&value);
            self.clear_value_by_id(id);
            storage_clear(self.get_value_key(id).as_ref());
            self.value_set_mapper.swap_remove(&value);
            return true;
        }
        false
    }
    pub fn remove_by_value(&mut self, value: &V) -> bool {
        if self.value_set_mapper.swap_remove(value) {
            let id = self.get_id(value);
            self.clear_id_by_value(value);
            self.clear_value_by_id(&id);
            self.id_set_mapper.swap_remove(&id);
            return true;
        }
        false
    }

    pub fn remove_all_by_ids<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = K>,
    {
        for item in iter {
            self.remove_by_id(&item);
        }
    }

    pub fn remove_all_by_values<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = V>,
    {
        for item in iter {
            self.remove_by_value(&item);
        }
    }
}

impl<'a, SA, K, V, A> IntoIterator for &'a BiDiMapper<SA, K, V, A>
where
    SA: StorageMapperApi,
    A: StorageAddress<SA>,
    K: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
    V: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
{
    type Item = (K, V);

    type IntoIter = Iter<'a, SA, K, V, A>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

pub struct Iter<'a, SA, K, V, A>
where
    SA: StorageMapperApi,
    A: StorageAddress<SA>,
    K: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
    V: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
{
    key_iter: Keys<'a, SA, K, A>,
    hash_map: &'a BiDiMapper<SA, K, V, A>,
}

impl<'a, SA, K, V, A> Iter<'a, SA, K, V, A>
where
    SA: StorageMapperApi,
    A: StorageAddress<SA>,
    K: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
    V: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
{
    fn new(hash_map: &'a BiDiMapper<SA, K, V, A>) -> Iter<'a, SA, K, V, A> {
        Iter {
            key_iter: hash_map.get_all_ids(),
            hash_map,
        }
    }
}

impl<SA, K, V, A> Iterator for Iter<'_, SA, K, V, A>
where
    SA: StorageMapperApi,
    A: StorageAddress<SA>,
    K: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
    V: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
{
    type Item = (K, V);

    #[inline]
    fn next(&mut self) -> Option<(K, V)> {
        if let Some(key) = self.key_iter.next() {
            let value = self.hash_map.get_value(&key);
            return Some((key, value));
        }
        None
    }
}

impl<SA, K, V> TopEncodeMulti for BiDiMapper<SA, K, V, CurrentStorage>
where
    SA: StorageMapperApi,
    K: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
    V: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
{
    fn multi_encode_or_handle_err<O, H>(&self, output: &mut O, h: H) -> Result<(), H::HandledErr>
    where
        O: TopEncodeMultiOutput,
        H: EncodeErrorHandler,
    {
        let iter = self.iter().map(MultiValue2::<K, V>::from);
        multi_encode_iter_or_handle_err(iter, output, h)
    }
}

impl<SA, K, V> TypeAbiFrom<BiDiMapper<SA, K, V, CurrentStorage>>
    for MultiValueEncoded<SA, MultiValue2<K, V>>
where
    SA: StorageMapperApi,
    K: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
    V: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
{
}

impl<SA, K, V> TypeAbiFrom<Self> for BiDiMapper<SA, K, V, CurrentStorage>
where
    SA: StorageMapperApi,
    K: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
    V: TopEncode + TopDecode + NestedEncode + NestedDecode + 'static + Default + PartialEq,
{
}

impl<SA, K, V> TypeAbi for BiDiMapper<SA, K, V, CurrentStorage>
where
    SA: StorageMapperApi,
    K: TopEncode
        + TopDecode
        + NestedEncode
        + NestedDecode
        + 'static
        + Default
        + PartialEq
        + TypeAbi,
    V: TopEncode
        + TopDecode
        + NestedEncode
        + NestedDecode
        + 'static
        + Default
        + PartialEq
        + TypeAbi,
{
    type Unmanaged = Self;

    fn type_name() -> TypeName {
        MultiValueEncoded::<SA, MultiValue2<K, V>>::type_name()
    }

    fn type_name_rust() -> TypeName {
        MultiValueEncoded::<SA, MultiValue2<K, V>>::type_name_rust()
    }

    fn provide_type_descriptions<TDC: TypeDescriptionContainer>(accumulator: &mut TDC) {
        K::provide_type_descriptions(accumulator);
        V::provide_type_descriptions(accumulator);
    }
    fn is_variadic() -> bool {
        true
    }
}