Skip to content

Instantly share code, notes, and snippets.

@0xNonCents
Last active February 18, 2022 08:19
Show Gist options
  • Save 0xNonCents/11f8488cd800fec49bf4cd89495722b4 to your computer and use it in GitHub Desktop.
Save 0xNonCents/11f8488cd800fec49bf4cd89495722b4 to your computer and use it in GitHub Desktop.
Cairo vector
# @title The beginnings of Vector in Cairo
# @author 0xNonCents
# @notice Please let me know if this will save on gas compared to a @storage array
# MIT License
%builtins pedersen range_check
from starkware.cairo.common.alloc import alloc
from starkware.cairo.common.hash import hash2
from starkware.cairo.common.cairo_builtins import HashBuiltin
from starkware.cairo.common.math import unsigned_div_rem, split_felt, assert_nn, assert_le
from starkware.cairo.common.registers import get_fp_and_pc
# @member s the starting pointer of the vector
# @member e the ending pointer of the vector
# @member size the current size of the vector
struct vector:
member s : felt*
member e : felt*
member size : felt
end
# @notice Appends {value} to the (e)nd of a vector. Increment the end pointer and size by 1 (SIZE of felt)
# @param v The vector which recieves the new element
# @param value The element that is added to the end of the vector
# @return A new vector containing the added element
func push{pedersen_ptr : HashBuiltin*, range_check_ptr}(v : vector, value : felt) -> (res : vector):
let end_ptr = v.e
[end_ptr] = value
let new_v : vector = vector(v.s, end_ptr + 1, v.size + 1)
return (new_v)
end
# @notice Retrieves the element at a given {index}
# @dev Will break if index is out of vector bounds
# @param v The vector
# @param index The index at which to get the desired value
# @return The value of the vector at an index
func at{pedersen_ptr : HashBuiltin*, range_check_ptr}(v : vector, index : felt) -> (res : felt):
let res = v.s[index]
return (res)
end
# @notice the drive function to demonstrate the vector
# @dev To run: cairo-compile ./contracts/vector.cairo --output ./artifacts/vector.json && cairo-run --program=./artifacts/vector.json --layout=all
func main{pedersen_ptr : HashBuiltin*, range_check_ptr}():
alloc_locals
let s : felt* = alloc()
let e : felt* = s + 1
let v : vector = vector(s, e, 4)
let (v_2 : vector) = push(v, 1)
let (res : vector) = push(v_2, 3)
let ptr = res.e
let val = [res.e - 1]
%{ print(ids.ptr) %}
%{ print(ids.val) %}
let (val_at) = at(v_2, 2)
assert 3 = val_at
%{ print(ids.val_at) %}
let (val_at) = at(v_2, 1)
assert 1 = val_at
%{ print(ids.val_at) %}
return ()
end
@milancermak
Copy link

Cheers! If I get rich using this, beer's on me 🍻

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment