Skip to content

Commit

Permalink
feat(corelib): Felt252DictFromIterator (#7137)
Browse files Browse the repository at this point in the history
  • Loading branch information
julio4 authored Jan 23, 2025
1 parent 8739103 commit 51b323b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
15 changes: 15 additions & 0 deletions corelib/src/dict.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -263,3 +263,18 @@ impl Felt252DictIndex<
self.get(index)
}
}

impl Felt252DictFromIterator<
T, +Destruct<T>, +Destruct<Felt252Dict<T>>, +Felt252DictValue<T>,
> of crate::iter::FromIterator<Felt252Dict<T>, (felt252, T)> {
/// Constructs a `Felt252Dict<T>` from an iterator of (felt252, T) key-value pairs.
/// If the iterator contains repeating keys,
/// only the last value in the iterator for each key will be kept.
fn from_iter<I, +Iterator<I>[Item: (felt252, T)], +Destruct<I>>(iter: I) -> Felt252Dict<T> {
let mut dict = Default::default();
for (key, value) in iter {
dict.insert(key, value);
};
dict
}
}
16 changes: 16 additions & 0 deletions corelib/src/test/dict_test.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,19 @@ fn test_array_dict() {
assert(value.is_null(), 'dict[10] == null');
}

#[test]
fn test_dict_from_iterator() {
let mut dict: Felt252Dict<u32> = (0..5_u32).into_iter().map(|x| (x.into(), x)).collect();

assert_eq!(dict[0], 0);
assert_eq!(dict[1], 1);
assert_eq!(dict[2], 2);
assert_eq!(dict[3], 3);
assert_eq!(dict[4], 4);
}

#[test]
fn test_dict_from_iterator_with_duplicate_keys() {
let mut dict = array![(0, 1_u32), (0, 2_u32)].into_iter().collect::<Felt252Dict<_>>();
assert_eq!(dict[0], 2);
}

0 comments on commit 51b323b

Please sign in to comment.