Skip to content

Commit

Permalink
feat(corelib): ByteArray impl Hash trait
Browse files Browse the repository at this point in the history
  • Loading branch information
hudem1 committed Jan 9, 2025
1 parent 2f79247 commit 1380127
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
13 changes: 13 additions & 0 deletions corelib/src/hash.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,16 @@ impl TupleNextHash<
state.update_with(head).update_with(rest)
}
}

impl ByteArrayHash<S, +HashStateTrait<S>, +Drop<S>> of Hash<ByteArray, S> {
fn update_state(mut state: S, value: ByteArray) -> S {
state = state.update(value.data.len().into());

for word_index in 0..value.data.len() {
let word_in_data = (*value.data.at(word_index)).into();
state = state.update(word_in_data);
};

state.update(value.pending_word_len.into()).update(value.pending_word)
}
}
21 changes: 21 additions & 0 deletions corelib/src/test/hash_test.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,24 @@ fn test_user_defined_hash() {
'Bad hash of StructForHash',
);
}

#[test]
fn test_byte_array_hash() {
let byte_array: ByteArray = "This is a sentence that is longer than 31 characters.";

let word_1 = 'This is a sentence that is long';
let data_length = 1;
let pending_word = 'er than 31 characters.';
let pending_word_len = 22;

assert_eq(
@PoseidonTrait::new().update_with(byte_array).finalize(),
@PoseidonTrait::new()
.update(data_length)
.update(word_1)
.update(pending_word_len)
.update(pending_word)
.finalize(),
'Bad hash for ByteArray',
);
}

0 comments on commit 1380127

Please sign in to comment.