Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(corelib): ByteArray impl Hash trait #7042

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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',
);
}