StorageVec
A StorageVec
is a vector that permanently stores its data in storage
. It replicates the functionality of a regular vector however its data is not stored contiguously because it utilizes hashing and generics to find a location to store the value T
.
There is a number of methods in the standard library however we will take a look at pushing and retrieving data.
Declaration
To use a StorageVec
we need to import it from the standard library and while we're at it we'll import the msg_sender()
so that we can use it in the following section.
After the import we initialize our StorageVec
as described in the initialization section.
use std::storage::storage_vec::*;
storage {
// T = u64
balance: StorageVec<u64> = StorageVec {},
// T = (Identity, u64)
user: StorageVec<(Identity, u64)> = StorageVec {},
}
There are two storage
variables: balance
& user
. balance
takes a single value while user
wraps two values into a tuple.
Reading from Storage
Retrieving data from a storage variable is done through the .get(index)
method. That is to say that we state which index by specifying it inside .get()
and appending that to the end of the storage variable.
In this example we look at how we can retrieve a single value balance
and how we can unpack multiple values from user
.
#[storage(read)]
fn reading_from_storage(id: u64) {
let balance = storage.balance.get(id).unwrap();
let (user, value) = storage.user.get(id).unwrap().read();
}
Writing to Storage
Writing to storage is similar to reading. The difference is that we use a different method .push(value)
and we use the read
keyword because the implementation reads the length of the vector to determine where to store the value.
In this example we insert a tuple containing an the Identity
of the caller and some id
into the vector.
#[storage(read, write)]
fn writing_to_storage(id: u64) {
storage.user.push((msg_sender().unwrap(), id));
}