Skip to content

Commit

Permalink
feat: poseidon_hash_may takes an iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
tdelabro committed Jun 3, 2024
1 parent 9451459 commit 1ba71e3
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions starknet-crypto/src/poseidon_hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,20 +72,29 @@ pub fn poseidon_hash_single(x: FieldElement) -> FieldElement {
/// Computes the Starknet Poseidon hash of an arbitrary number of [FieldElement]s.
///
/// Using this function is the same as using [PoseidonHasher].
pub fn poseidon_hash_many(msgs: &[FieldElement]) -> FieldElement {
pub fn poseidon_hash_many<'a, I: IntoIterator<Item = &'a FieldElement>>(msgs: I) -> FieldElement {
let mut state = [FieldElement::ZERO, FieldElement::ZERO, FieldElement::ZERO];
let mut iter = msgs.chunks_exact(2);
let mut iter = msgs.into_iter();

loop {
match iter.next() {
Some(v) => state[0] += *v,
None => {
state[0] += FieldElement::ONE;
break;
}
}

match iter.next() {
Some(v) => state[1] += *v,
None => {
state[1] += FieldElement::ONE;
break;
}
}

for msg in iter.by_ref() {
state[0] += msg[0];
state[1] += msg[1];
poseidon_permute_comp(&mut state);
}
let r = iter.remainder();
if r.len() == 1 {
state[0] += r[0];
}
state[r.len()] += FieldElement::ONE;
poseidon_permute_comp(&mut state);

state[0]
Expand Down

0 comments on commit 1ba71e3

Please sign in to comment.