Skip to content

Commit

Permalink
feat: vec index trait (#92)
Browse files Browse the repository at this point in the history
## Pull Request type

<!-- Please try to limit your pull request to one type; submit multiple
pull requests if needed. -->

Please check the type of change your PR introduces:

- [ ] Bugfix
- [x] Feature
- [ ] Code style update (formatting, renaming)
- [ ] Refactoring (no functional changes, no API changes)
- [ ] Build-related changes
- [ ] Documentation content changes
- [ ] Other (please describe):

## What is the current behavior?

To fetch an element at a particular index in a `Vec`, one has to use
`at`

Issue Number: N/A

## What is the new behavior?

PR implements the `Index` trait to allow for using `[]` operator when
fetching Vec elements:

```
let element_at_2 = a_vec[2];
```

## Does this introduce a breaking change?

- [ ] Yes
- [x] No

<!-- If this does introduce a breaking change, please describe the
impact and migration path for existing applications below. -->

## Other information

<!-- Any other information that is important to this PR, such as
screenshots of how the component looks before and after the change. -->
  • Loading branch information
milancermak authored May 24, 2023
1 parent e6fd5b5 commit fc1de03
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
20 changes: 18 additions & 2 deletions alexandria/data_structures/src/tests/vec_test.cairo
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Core lib imports
use array::ArrayTrait;
use traits::Into;
use traits::TryInto;
use traits::{Index, Into, TryInto};
use option::OptionTrait;
use result::ResultTrait;
use dict::Felt252DictTrait;
Expand Down Expand Up @@ -88,3 +87,20 @@ fn vec_set_test_expect_error() {
vec.set(1, 2)
}

#[test]
#[available_gas(2000000)]
fn vec_index_trait_test() {
let mut vec = VecTrait::<u128>::new();
vec.push(42);
vec.push(0x1337);
assert(vec[0] == 42, 'vec[0] != 42');
assert(vec[1] == 0x1337, 'vec[1] != 0x1337');
}

#[test]
#[available_gas(2000000)]
#[should_panic(expected: ('Index out of bounds', ))]
fn vec_index_trait_out_of_bounds_test() {
let mut vec = VecTrait::<u128>::new();
vec[0];
}
9 changes: 8 additions & 1 deletion alexandria/data_structures/src/vec.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
// Core lib imports
use dict::Felt252DictTrait;
use option::OptionTrait;
use traits::Into;
use traits::{Index, Into};

struct Vec<T> {
items: Felt252Dict<T>,
Expand Down Expand Up @@ -114,3 +114,10 @@ impl TFelt252DictValue: Felt252DictValue<T>> of VecTrait<T> {
*(self.len)
}
}

impl VecIndex<T, impl VecTraitImpl: VecTrait<T>> of Index<Vec<T>, usize, T> {
#[inline(always)]
fn index(ref self: Vec<T>, index: usize) -> T {
self.at(index)
}
}

0 comments on commit fc1de03

Please sign in to comment.