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

Add clear and is_empty methods to Map #803

Merged
merged 5 commits into from Sep 26, 2022
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
71 changes: 71 additions & 0 deletions packages/storage-plus/src/map.rs
Expand Up @@ -260,6 +260,41 @@ where
}
}

#[cfg(feature = "iterator")]
impl<'a, K, T> Map<'a, K, T>
where
T: Serialize + DeserializeOwned,
K: PrimaryKey<'a>,
{
/// Clears the map, removing all elements.
pub fn clear(&self, store: &mut dyn Storage) {
const TAKE: usize = 10;
let prefix = self.no_prefix_raw();
let mut cleared = false;

while !cleared {
let paths = prefix
.keys_raw(store, None, None, cosmwasm_std::Order::Ascending)
ueco-jb marked this conversation as resolved.
Show resolved Hide resolved
.map(|raw_key| Path::<T>::new(self.namespace, &[raw_key.as_slice()]))
// Take just TAKE elements to prevent possible heap overflow if the Map is big.
.take(TAKE)
.collect::<Vec<_>>();

paths.iter().for_each(|path| store.remove(path));

cleared = paths.len() < TAKE;
}
}

/// Returns `true` if the map is empty.
pub fn is_empty(&self, store: &dyn Storage) -> bool {
self.no_prefix_raw()
.keys_raw(store, None, None, cosmwasm_std::Order::Ascending)
.next()
.is_none()
}
}

#[cfg(test)]
mod test {
use super::*;
Expand Down Expand Up @@ -1511,4 +1546,40 @@ mod test {
assert_eq!(include.len(), 1);
assert_eq!(include, vec![456]);
}

#[test]
#[cfg(feature = "iterator")]
fn clear_works() {
const TEST_MAP: Map<&str, u32> = Map::new("test_map");

let mut storage = MockStorage::new();
TEST_MAP.save(&mut storage, "key0", &0u32).unwrap();
TEST_MAP.save(&mut storage, "key1", &1u32).unwrap();
TEST_MAP.save(&mut storage, "key2", &2u32).unwrap();
TEST_MAP.save(&mut storage, "key3", &3u32).unwrap();
TEST_MAP.save(&mut storage, "key4", &4u32).unwrap();

TEST_MAP.clear(&mut storage);

assert!(!TEST_MAP.has(&storage, "key0"));
assert!(!TEST_MAP.has(&storage, "key1"));
assert!(!TEST_MAP.has(&storage, "key2"));
assert!(!TEST_MAP.has(&storage, "key3"));
assert!(!TEST_MAP.has(&storage, "key4"));
}

#[test]
#[cfg(feature = "iterator")]
fn is_empty_works() {
const TEST_MAP: Map<&str, u32> = Map::new("test_map");

let mut storage = MockStorage::new();

assert!(TEST_MAP.is_empty(&storage));

TEST_MAP.save(&mut storage, "key1", &1u32).unwrap();
TEST_MAP.save(&mut storage, "key2", &2u32).unwrap();

assert!(!TEST_MAP.is_empty(&storage));
}
}