Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VecMapper update with index #1727

Merged
merged 1 commit into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions framework/base/src/storage/mappers/vec_mapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,16 @@ where
self.set_unchecked(index, item);
}

/// Syntactic sugar, to more compactly express a get, update and set in one line.
/// Takes whatever lies in storage, apples the given closure and saves the final value back to storage.
/// Propagates the return value of the given function.
pub fn update<R, F: FnOnce(&mut T) -> R>(&mut self, index: usize, f: F) -> R {
let mut value = self.get(index);
let result = f(&mut value);
self.set(index, &value);
result
}

/// Keeping `set_unchecked` private on purpose, so developers don't write out of index limits by accident.
fn set_unchecked(&self, index: usize, item: &T) {
storage_set(self.item_key(index).as_ref(), item);
Expand Down
14 changes: 14 additions & 0 deletions framework/scenario/tests/test_vec_mapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,20 @@ fn test_vec_swap_remove() {
check_vec(&vect, vec![42, 45]);
}

#[test]
fn test_vec_update() {
let mut vect = create_vec();

vect.extend_from_slice(&[42, 43, 44, 45, 46]);

assert_eq!(vect.len(), 5);
assert_eq!(vect.get(5), 46);
vect.update(5, |item| *item = 42);
assert_eq!(vect.len(), 5);
assert_eq!(vect.get(5), 42);
check_vec(&vect, vec![42, 43, 44, 45, 42]);
}

#[test]
fn test_vec_iter_processing() {
let mut vect = create_vec();
Expand Down
Loading