Skip to main content
Version: v0.22.0

Vectors

caution

This feature is experimental. You should expect it to change in future versions, cause unexpected behavior, or simply not work at all.

A vector is a collection type similar to Rust's Vector type. It's convenient way to use slices as mutable arrays.

Example:

use dep::std::collections::vec::Vec;

let mut vector: Vec<Field> = Vec::new();
for i in 0..5 {
vector.push(i);
}
assert(vector.len() == 5);

Methods

new

Creates a new, empty vector.

pub fn new() -> Self {
Self { slice: [] }
}

Example:

let empty_vector: Vec<Field> = Vec::new();
assert(empty_vector.len() == 0);

from_slice

Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice.

pub fn from_slice(slice: [T]) -> Self {
Self { slice }
}

Example:

let arr: [Field] = [1, 2, 3];
let vector_from_slice = Vec::from_slice(arr);
assert(vector_from_slice.len() == 3);

get

Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end.

pub fn get(self, index: Field) -> T {
self.slice[index]
}

Example:

let vector: Vec<Field> = Vec::from_slice([10, 20, 30]);
assert(vector.get(1) == 20);

push

Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector.

pub fn push(&mut self, elem: T) {
self.slice = self.slice.push_back(elem);
}

Example:

let mut vector: Vec<Field> = Vec::new();
vector.push(10);
assert(vector.len() == 1);

pop

Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero.

pub fn pop(&mut self) -> T {
let (popped_slice, last_elem) = self.slice.pop_back();
self.slice = popped_slice;
last_elem
}

Example:

let mut vector = Vec::from_slice([10, 20]);
let popped_elem = vector.pop();
assert(popped_elem == 20);
assert(vector.len() == 1);

insert

Inserts an element at a specified index, shifting subsequent elements to the right.

pub fn insert(&mut self, index: Field, elem: T) {
self.slice = self.slice.insert(index, elem);
}

Example:

let mut vector = Vec::from_slice([10, 30]);
vector.insert(1, 20);
assert(vector.get(1) == 20);

remove

Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element.

pub fn remove(&mut self, index: Field) -> T {
let (new_slice, elem) = self.slice.remove(index);
self.slice = new_slice;
elem
}

Example:

let mut vector = Vec::from_slice([10, 20, 30]);
let removed_elem = vector.remove(1);
assert(removed_elem == 20);
assert(vector.len() == 2);

len

Returns the number of elements in the vector.

pub fn len(self) -> Field {
self.slice.len()
}

Example:

let empty_vector: Vec<Field> = Vec::new();
assert(empty_vector.len() == 0);