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

fix(hash): Fix broken handling of non-byte-sized TypedArray views #1012

Merged
merged 4 commits into from
Jul 13, 2021
Merged

fix(hash): Fix broken handling of non-byte-sized TypedArray views #1012

merged 4 commits into from
Jul 13, 2021

Conversation

jeremyBanks
Copy link
Contributor

@jeremyBanks jeremyBanks commented Jul 7, 2021

Currently, hash.update() corrupts input data if it comes from a TypedArray with items larger than a byte. The main source of trouble is:

      if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
        msg = new Uint8Array(data);

If the input is an ArrayBuffer or a Uint8Array, this is correct. However, if it's an Int16Array, this will cause each 16-bit value to be cast to an 8-bit value, and those values will be hashed, as you could see in an example like:

console.log(new Uint8Array(new Int16Array([1000])));
// Uint8Array [232]

Instead, it seems like the intended behaviour should be to hash the underlying bytes that the Int16Array is a view over, instead of a lossy coercion.

This commit updates our implementation to do that, and adds several test cases to make sure that various views of the same data produce the same result. It also avoids creating unnecessary copies of input data when we can instead just use another view of the same data (we consume the input synchronously, so we don't need to worry about it being changed under us).

Co-authored-by: @evanwashere evan@tsu.sh

@jeremyBanks
Copy link
Contributor Author

Marked as draft because this implementation is on top of the unmerged changes in #1010, but if that isn't good to merge I could update this to go first instead.

@jeremyBanks jeremyBanks changed the title fix(hash): Fix broken handling of partial and non-byte-sized TypedArray views fix(hash): Fix broken handling of non-byte-sized TypedArray views Jul 7, 2021
Co-authored-by: evanwashere <evan@tsu.sh>
@jeremyBanks jeremyBanks marked this pull request as ready for review July 8, 2021 20:01
Copy link
Member

@kt3k kt3k left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jeremyBanks Thanks! Nice fix! LGTM

@kt3k kt3k merged commit a501a82 into denoland:main Jul 13, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants