Skip to content

Commit 5ffc1d6

Browse files
authored
Fix undefined behavior in screenshots on WASM (#22077)
# Objective Currently the screenshot example on https://bevy.org/examples/window/screenshot/ gives invalid PNG files when I tried it. Looking at them they have some of the right bytes, but also a bunch of garbage. The example works on native. I narrowed it down to the one unsafe block in sight (thanks Rust!). I don't fully understand why the code stopped working or if it was ever valid, but in the meantime since it was written a safe API has been added, and using it made the problem go away. ## Solution Bump `js-sys`, use the safe API. ## Testing I ran the example with `bevy run --example screenshot web`
1 parent 6684682 commit 5ffc1d6

File tree

2 files changed

+8
-6
lines changed

2 files changed

+8
-6
lines changed

crates/bevy_render/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ send_wrapper = { version = "0.6.0" }
125125
proptest = "1"
126126

127127
[target.'cfg(target_arch = "wasm32")'.dependencies]
128-
js-sys = "0.3"
128+
js-sys = "0.3.83"
129129
web-sys = { version = "0.3.67", features = [
130130
'Blob',
131131
'Document',

crates/bevy_render/src/view/window/screenshot.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -151,11 +151,13 @@ pub fn save_to_disk(path: impl AsRef<Path>) -> impl FnMut(On<ScreenshotCaptured>
151151
let mut image_buffer = std::io::Cursor::new(Vec::new());
152152
img.write_to(&mut image_buffer, format)
153153
.map_err(|e| JsValue::from_str(&format!("{e}")))?;
154-
// SAFETY: `image_buffer` only exist in this closure, and is not used after this line
155-
let parts = js_sys::Array::of1(&unsafe {
156-
js_sys::Uint8Array::view(image_buffer.into_inner().as_bytes())
157-
.into()
158-
});
154+
155+
let parts = js_sys::Array::of1(
156+
&js_sys::Uint8Array::new_from_slice(
157+
image_buffer.into_inner().as_bytes(),
158+
)
159+
.into(),
160+
);
159161
let blob = web_sys::Blob::new_with_u8_array_sequence(&parts)?;
160162
let url = web_sys::Url::create_object_url_with_blob(&blob)?;
161163
let window = web_sys::window().unwrap();

0 commit comments

Comments
 (0)