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

Remove the unnecessary copy in Blob::new #152

Merged
merged 3 commits into from Aug 1, 2021

Conversation

Liamolucko
Copy link
Contributor

Use Uint8Array::view instead of Uint8Array::from to avoid making two copies of slices passed to Blob::new.

Fixes #150

name,
// SAFETY: `Self::new_` doesn't modify the `Uint8Array`,
// or hold on to the reference past the end of the function call.
unsafe { contents.into_jsvalue() },
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think we should pass contents to Self::new_. Currently, someone could change Self::new_ without realizing it this safety requirements. Also, that would reduce the number of places unsafe block is required.

First, I made `new_` take a `BlobContents`, to move the unsafety inside the function to make it easier to check. Then I got rid of it in favour of `new_with_options` since the signature was the same.

That broke `File::slice`, though, since it passed a `Blob` for `contents`, which didn't implement `BlobContents`. Since having `Blob` implement `BlobContents` is useful anyway, I decided to do that and simplify things.

I then also implemented `BlobContents` for `JsString`, so that if you already have one you don't have to go via `&str`.

I then noticed that `Blob` encoded JS strings as UTF-8, which meant that passing `&str` to `new Blob()` by converting it to a JS string meant converting it into UTF-16 and then back to UTF-8. So, I made it instead pass it as bytes, since it's already correctly encoded.
Copy link
Collaborator

@hamza1311 hamza1311 left a comment

Choose a reason for hiding this comment

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

LGTM

@hamza1311 hamza1311 merged commit b7ea958 into rustwasm:master Aug 1, 2021
@Liamolucko Liamolucko deleted the blob-remove-extra-copy branch August 1, 2021 12:18
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.

Blob::new(&[u8]) makes an unnecessary copy
2 participants