One of the main purposes of the ink! Mapping is to allow storing a lot of values.
NOTE
There are many additional data structures accessible under ink::prelude::collections, such as HashMap or BTreeMap (to name a few). Note that these data structures all exhibit Packed storage loading behavior, as opposed to the ink! Mapping!
Each Mapping value lives under it's own storage key. Briefly, this means that Mappings are lazily loaded in ink!. In other words, if your message only accesses a single key of a mapping, it will not load the whole mapping but only the value being accessed.
// This causes only a single storage access and the decoding of a single "MyValue" struct,// no matter how many elements there are inside the mapping.let foo:MyValue= my_mapping.get(0)?;for n in0..5 {// This causes a storage access and a decoding operation for each loop iteration.// It is not possible to "fetch" all key/value pairs directly at once.let bar:MyValue= my_mapping.get(n)?;}
Furthermore, it follows that mapping values do not have a contiguous storage layout, and it is not possible to iterate over the contents of a map.
The attentive reader may have noticed that accessing mapping values via the Mapping::get() method will result in an owned value (a local copy), as opposed to a direct reference into the storage. Changes to this value won't be reflected in the contract's storage "automatically". To avoid this common pitfall, the value must be inserted again at the same key after it was modified. The transfer function from above example illustrates this:
pubfntransfer(&mut self) {let caller = self.env().caller();// `balance` is a local value and not a reference to the value on storage!let balance = self.balances.get(caller).unwrap_or(0);let endowment = self.env().transferred_value();// The following line of code would have no effect to the balance of the// caller stored in contract storage://// balance += endowment;//// Instead, we use the `insert` function to write it back like so: self.balances.insert(caller, &(balance + endowment));}