7

I have created a simple storage map as follows and I just want to check if it's empty or not. I am comparing it with rust HashMaps, it has the is_empty() method to check. I intend to use this in the same pallet.

#[pallet::storage]
#[pallet::getter(fn check_storage_map)]
pub type SimpleStorageMap<T: Config> =
    StorageMap<_, Blake2_256, u32, u32, ValueQuery>;

I checked the storage map rust doc but could not find any function associated with it. I am new to substrate any advice or help is appreciated.

2 Answers 2

3

There exists the CountedStorageMap that keeps track of the count of elements in the map:

/// A wrapper around a `StorageMap` and a `StorageValue<Value=u32>` to keep track of how many items
/// are in a map, without needing to iterate all the values.
///
/// This storage item has additional storage read and write overhead when manipulating values
/// compared to a regular storage map.
///
/// For functions where we only add or remove a value, a single storage read is needed to check if
/// that value already exists. For mutate functions, two storage reads are used to check if the
/// value existed before and after the mutation.
///
/// Whenever the counter needs to be updated, an additional read and write occurs to update that
/// counter.
pub struct CountedStorageMap;
6

You have multiple options to achieve your requirement. Eventually it boils down to checking for an empty iterator IMO.

You can retrieve two iterators of your StorageMap:

  1. Either the KeyPrefixIterator by calling SimpleStorageMap::<T>::iter_keys()
  2. Or the PrefixIterator by calling SimpleStorageMap::<T>::iter_values()

Then, you could just check whether the first element of your Iterator is None or whether the collection to an arbitrary vector is empty:

assert!(SimpleStorageMap::<T>::iter_keys().next().is_none());

assert!(SimpleStorageMap::<T>::iter_keys().collect::<Vec<_>>().is_empty());
3
  • 2
    assert!(SimpleStorageMap::<T>::iter_keys().collect::<Vec<_>>().is_empty()); That is a really bad idea, just assume you have some big map. Then it would lead to some huge amount of data being read. For a Parachain that would lead to a really huge StorageProof.
    – bkchr
    Mar 23, 2022 at 18:48
  • 1
    Thats true. Using a CountedStorageMap definitely is the best solution for the OP. Mar 23, 2022 at 20:31
  • This does make sense, thanks.
    – salman01z
    Mar 24, 2022 at 6:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.