Struct near_sdk::store::vec::Vector

source ·
pub struct Vector<T>
where T: BorshSerialize,
{ /* private fields */ }
Expand description

An iterable implementation of vector that stores its content on the trie. This implementation will load and store values in the underlying storage lazily.

Uses the following map: index -> element. Because the data is sharded to avoid reading/writing large chunks of data, the values cannot be accessed as a contiguous piece of memory.

This implementation will cache all changes and loads and only updates values that are changed in storage after it’s dropped through it’s Drop implementation. These changes can be updated in storage before the variable is dropped by using Vector::flush. During the lifetime of this type, storage will only be read a maximum of one time per index and only written once per index unless specifically flushed.

This type should be a drop in replacement for Vec in most cases and will provide contracts a vector structure which scales much better as the contract data grows.

§Examples

use near_sdk::store::Vector;

let mut vec = Vector::new(b"a");
assert!(vec.is_empty());

vec.push(1);
vec.push(2);

assert_eq!(vec.len(), 2);
assert_eq!(vec[0], 1);

assert_eq!(vec.pop(), Some(2));
assert_eq!(vec.len(), 1);

vec[0] = 7;
assert_eq!(vec[0], 7);

vec.extend([1, 2, 3].iter().copied());
assert!(Iterator::eq(vec.into_iter(), [7, 1, 2, 3].iter()));

Implementations§

source§

impl<T> Vector<T>
where T: BorshSerialize,

source

pub fn len(&self) -> u32

Returns the number of elements in the vector, also referred to as its size. This function returns a u32 rather than the Vec equivalent of usize to have consistency between targets.

§Examples
use near_sdk::store::Vector;

let mut vec = Vector::new(b"a");
vec.push(1);
vec.push(2);
assert_eq!(vec.len(), 2);
source

pub fn is_empty(&self) -> bool

Returns true if the vector contains no elements.

§Examples
use near_sdk::store::Vector;

let mut vec = Vector::new(b"a");
assert!(vec.is_empty());

vec.push(1);
assert!(!vec.is_empty());
source

pub fn new<S>(prefix: S) -> Self
where S: IntoStorageKey,

Create new vector with zero elements. Prefixes storage accesss with the prefix provided.

This prefix can be anything that implements IntoStorageKey. The prefix is used when storing and looking up values in storage to ensure no collisions with other collections.

§Examples
use near_sdk::store::Vector;

let mut vec: Vector<u8> = Vector::new(b"a");
source

pub fn clear(&mut self)

Removes all elements from the collection. This will remove all storage values for the length of the Vector.

§Examples
use near_sdk::store::Vector;

let mut vec = Vector::new(b"a");
vec.push(1);

vec.clear();

assert!(vec.is_empty());
source

pub fn flush(&mut self)

Flushes the cache and writes all modified values to storage.

This operation is performed on Drop, but this method can be called to persist intermediate writes in cases where Drop is not called or to identify storage changes.

source

pub fn set(&mut self, index: u32, value: T)

Sets a value at a given index to the value provided. This does not shift values after the index to the right.

The reason to use this over modifying with Vector::get_mut or IndexMut::index_mut is to avoid loading the existing value from storage. This method will just write the new value.

§Panics

Panics if index is out of bounds.

§Examples
use near_sdk::store::Vector;

let mut vec = Vector::new(b"v");
vec.push("test".to_string());

vec.set(0,"new_value".to_string());

assert_eq!(vec.get(0),Some(&"new_value".to_string()));
source

pub fn push(&mut self, element: T)

Appends an element to the back of the collection.

§Panics

Panics if new length exceeds u32::MAX

§Examples
use near_sdk::store::Vector;

let mut vec = Vector::new(b"v");
vec.push("test".to_string());

assert!(!vec.is_empty());
source§

impl<T> Vector<T>

source

pub fn get(&self, index: u32) -> Option<&T>

Returns the element by index or None if it is not present.

§Examples
use near_sdk::store::Vector;

let mut vec = Vector::new(b"v");
vec.push("test".to_string());

assert_eq!(Some(&"test".to_string()), vec.get(0));
assert_eq!(None, vec.get(3));
source

pub fn get_mut(&mut self, index: u32) -> Option<&mut T>

Returns a mutable reference to the element at the index provided.

§Examples
use near_sdk::store::Vector;

let mut vec = Vector::new(b"v");
let x = vec![0, 1, 2];
vec.extend(x);

if let Some(elem) = vec.get_mut(1) {
    *elem = 42;
}

let actual: Vec<_> = vec.iter().cloned().collect();
assert_eq!(actual, &[0, 42, 2]);
source

pub fn swap_remove(&mut self, index: u32) -> T

Removes an element from the vector and returns it. The removed element is replaced by the last element of the vector. Does not preserve ordering, but is O(1).

§Panics

Panics if index is out of bounds.

§Examples
use near_sdk::store::Vector;

let mut vec: Vector<u8> = Vector::new(b"v");
vec.extend([1, 2, 3, 4]);

assert_eq!(vec.swap_remove(1), 2);
assert_eq!(vec.iter().copied().collect::<Vec<_>>(), &[1, 4, 3]);

assert_eq!(vec.swap_remove(0), 1);
assert_eq!(vec.iter().copied().collect::<Vec<_>>(), &[3, 4]);
source

pub fn pop(&mut self) -> Option<T>

Removes the last element from a vector and returns it, or None if it is empty.

§Examples
use near_sdk::store::Vector;

let mut vec = Vector::new(b"v");
vec.extend([1, 2, 3]);

assert_eq!(vec.pop(), Some(3));
assert_eq!(vec.pop(), Some(2));
source

pub fn replace(&mut self, index: u32, element: T) -> T

Inserts a element at index, returns an evicted element.

§Panics

If index is out of bounds.

§Examples
use near_sdk::store::Vector;

let mut vec = Vector::new(b"v");
vec.push("test".to_string());

vec.replace(0,"replaced".to_string());

assert_eq!(vec.get(0), Some(&"replaced".to_string()));
source

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator over the vector. This iterator will lazily load any values iterated over from storage.

§Examples
use near_sdk::store::Vector;

let mut vec = Vector::new(b"v");
vec.extend([1, 2, 4]);
let mut iterator = vec.iter();

assert_eq!(iterator.next(), Some(&1));
assert_eq!(iterator.next(), Some(&2));
assert_eq!(iterator.next(), Some(&4));
assert_eq!(iterator.next(), None);
source

pub fn iter_mut(&mut self) -> IterMut<'_, T>

Returns an iterator over the Vector that allows modifying each value. This iterator will lazily load any values iterated over from storage.

§Examples
use near_sdk::store::Vector;

let mut vec = Vector::new(b"v");
vec.extend([1u32, 2, 4]);

for elem in vec.iter_mut() {
    *elem += 2;
}
assert_eq!(vec.iter().copied().collect::<Vec<_>>(), &[3u32, 4, 6]);
source

pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
where R: RangeBounds<u32>,

Creates a draining iterator that removes the specified range in the vector and yields the removed items.

When the iterator is dropped, all elements in the range are removed from the vector, even if the iterator was not fully consumed. If the iterator is not dropped (with mem::forget for example), the collection will be left in an inconsistent state.

This will not panic on invalid ranges (end > length or end < start) and instead the iterator will just be empty.

§Examples
use near_sdk::store::Vector;

let mut vec: Vector<u32> = Vector::new(b"v");
vec.extend(vec![1, 2, 3]);

let u: Vec<_> = vec.drain(1..).collect();
assert_eq!(vec.iter().copied().collect::<Vec<_>>(), &[1]);
assert_eq!(u, &[2, 3]);

// A full range clears the vector, like `clear()` does
vec.drain(..);
assert!(vec.is_empty());

Trait Implementations§

source§

impl<T> BorshDeserialize for Vector<T>
where T: BorshSerialize,

source§

fn deserialize_reader<R: Read>(reader: &mut R) -> Result<Self, Error>

source§

fn deserialize(buf: &mut &[u8]) -> Result<Self, Error>

Deserializes this instance from a given slice of bytes. Updates the buffer to point at the remaining bytes.
source§

fn try_from_slice(v: &[u8]) -> Result<Self, Error>

Deserialize this instance from a slice of bytes.
source§

fn try_from_reader<R>(reader: &mut R) -> Result<Self, Error>
where R: Read,

source§

impl<T> BorshSerialize for Vector<T>
where T: BorshSerialize,

source§

fn serialize<W: Write>(&self, writer: &mut W) -> Result<(), Error>

source§

impl<T> Debug for Vector<T>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T> Drop for Vector<T>
where T: BorshSerialize,

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<T> Extend<T> for Vector<T>

source§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = T>,

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T> Index<u32> for Vector<T>

§

type Output = T

The returned type after indexing.
source§

fn index(&self, index: u32) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
source§

impl<T> IndexMut<u32> for Vector<T>

source§

fn index_mut(&mut self, index: u32) -> &mut Self::Output

Performs the mutable indexing (container[index]) operation. Read more
source§

impl<'a, T> IntoIterator for &'a Vector<T>

§

type Item = &'a T

The type of the elements being iterated over.
§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
source§

impl<'a, T> IntoIterator for &'a mut Vector<T>

§

type Item = &'a mut T

The type of the elements being iterated over.
§

type IntoIter = IterMut<'a, T>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for Vector<T>

§

impl<T> Send for Vector<T>
where T: Send,

§

impl<T> !Sync for Vector<T>

§

impl<T> Unpin for Vector<T>

§

impl<T> UnwindSafe for Vector<T>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.