Function std::storage::storage_api::update_slot
pub fn update_slot<T>(slot: b256, offset: u64, value: T) Expand description
Updates a value in storage in a single dynamic slot, placing it at the offset given in bytes.
Additional Information
The value is entirely stored in the slot and never crosses into another slot.
The offset, given in bytes, only determines where in the slot the value is stored.
If the slot already has data stored in it, the value will be written on top of the existing data starting at the offset,
overwriting the existing data at the offset. If the value does not fit in the remaining space in the slot after the offset,
the slot will be expanded to accommodate the entire value.
The offset must be a valid existing offset in the slot or u64::max().
u64::max() is used to store at the end of the currently used portion of the slot, i.e., to append to the slot.
Valid existing offsets are from 0 to the size of the currently used portion of the slot in bytes.
For example, if the slot currently has 10 bytes used, valid offsets are from 0 to 10 and u64::max().
Offsets 0 to 9 are used to store within the currently used portion of the slot.
Offsets 10 and u64::max() will store starting right after the currently used portion of the slot.
An offset greater than the currently used portion of the slot but less than u64::max() is invalid and will cause a revert.
To append to the slot, instead of using update_slot with u64::max(), the more idiomatic way is to use the append_slot function.
If T is a zero-sized type, no storage access will occur. Storage API does not store zero-sized types in storage,
so reading from the slot and offset where a zero-sized type would be stored will return None.
The value is memory-copied into the storage slot. If it contains any pointers or references,
the data they point to will not be stored in storage.
To store dynamic types like Vec, String, or Bytes, use the dedicated storage types provided in the storage module,
like StorageVec, StorageString, and StorageBytes.
Arguments
slot: [b256] - The storage slot at which thevaluewill be stored.offset: [u64] - An offset, in bytes, starting at the beginning ofslotat whichvalueshould be stored.value: [T] - The value to be stored.
Number of Storage Accesses
- Internal preloads:
1 - Writes:
1
Reverts
- If the
offsetis greater than the currently used portion of the slot but less thanu64::max().
Examples
use std::storage::storage_api::{read_slot, update_slot, write_slot};
fn foo() {
let five = 5_u64;
write_slot(b256::zero(), five);
update_slot(b256::zero(), 0, five + 1);
update_slot(b256::zero(), 8, five + 2); // Append 7.
update_slot(b256::zero(), u64::max(), five + 3); // Append 8.
let stored_six = read_slot::<u64>(b256::zero(), 0).unwrap();
assert_eq(five + 1, stored_six);
let stored_seven = read_slot::<u64>(b256::zero(), 8).unwrap();
assert_eq(five + 2, stored_seven);
let stored_eight = read_slot::<u64>(b256::zero(), 16).unwrap();
assert_eq(five + 3, stored_eight);
}