forked from Angry-Penguins-Colony/mx-rust-utilities
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vec_mapper_utils.rs
49 lines (42 loc) · 1.28 KB
/
vec_mapper_utils.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
use elrond_wasm::{
api::{ErrorApiImpl, StorageMapperApi},
elrond_codec::{TopDecode, TopEncode},
storage::mappers::VecMapper,
};
pub trait VecMapperUtils<SA, T>
where
SA: StorageMapperApi,
T: TopEncode + TopDecode + 'static,
{
fn find_index(&self, item: &T) -> Option<usize>;
fn has_item(&self, item: &T) -> bool;
fn remove_item(&mut self, item: &T);
}
impl<SA, T> VecMapperUtils<SA, T> for VecMapper<SA, T>
where
SA: StorageMapperApi,
T: TopEncode + TopDecode + 'static + core::cmp::PartialEq,
{
fn find_index(&self, item_to_find: &T) -> Option<usize> {
for (index, curr_item) in self.iter().enumerate() {
if &curr_item == item_to_find {
return Option::Some(index + 1); // we add one because VecMapper index starts at 1, while iter starts at 0
}
}
return Option::None;
}
/**
* Panic if missing items
*/
fn remove_item(&mut self, item: &T) {
let opt_index = self.find_index(item);
if let Some(index) = opt_index {
self.swap_remove(index);
} else {
SA::error_api_impl().signal_error(b"Item not found in VecMapper")
}
}
fn has_item(&self, item: &T) -> bool {
return self.find_index(item).is_some();
}
}