From c1f0959992264be4cc62f55012a5133ad0e29a4b Mon Sep 17 00:00:00 2001 From: Michael Kefeder Date: Sun, 17 May 2020 21:05:31 +0200 Subject: [PATCH 1/2] use js_sys::Uint8Array instead of as_ptr() --- Cargo.toml | 1 + src/lib.rs | 20 ++++++++------------ www/index.js | 3 +-- 3 files changed, 10 insertions(+), 14 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e55f7af..614f311 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ default = ["console_error_panic_hook"] [dependencies] cfg-if = "0.1.2" wasm-bindgen = "0.2" +js-sys = "0.3" # The `console_error_panic_hook` crate provides better debugging of panics by # logging them with `console.error`. This is great for development, but requires diff --git a/src/lib.rs b/src/lib.rs index 4ee0f69..b921778 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ extern crate web_sys; mod utils; use std::fmt; +use std::mem; use wasm_bindgen::prelude::*; use web_sys::console; @@ -71,17 +72,9 @@ impl Universe { fn live_neighbor_count(&self, row: u32, column: u32) -> u8 { let mut count = 0; - let north = if row == 0 { - self.height - 1 - } else { - row - 1 - }; + let north = if row == 0 { self.height - 1 } else { row - 1 }; - let south = if row == self.height - 1 { - 0 - } else { - row + 1 - }; + let south = if row == self.height - 1 { 0 } else { row + 1 }; let west = if column == 0 { self.width - 1 @@ -208,8 +201,11 @@ impl Universe { self.cells = (0..self.width * height).map(|_i| Cell::Dead).collect(); } - pub fn cells(&self) -> *const Cell { - self.cells.as_ptr() + pub fn cells(&self) -> js_sys::Uint8Array { + unsafe { + let u8_cells = mem::transmute::<&Vec, &Vec>(&self.cells); + js_sys::Uint8Array::view(&u8_cells) + } } pub fn toggle_cell(&mut self, row: u32, column: u32) { diff --git a/www/index.js b/www/index.js index 6f1c15f..11c6167 100644 --- a/www/index.js +++ b/www/index.js @@ -126,8 +126,7 @@ const getIndex = (row, column) => { }; const drawCells = () => { - const cellsPtr = universe.cells(); - const cells = new Uint8Array(memory.buffer, cellsPtr, width * height); + const cells = universe.cells(); ctx.beginPath(); From ce4efde3782b94b145b839fd9f55b69dc857929f Mon Sep 17 00:00:00 2001 From: Michael Kefeder Date: Sun, 17 May 2020 21:16:51 +0200 Subject: [PATCH 2/2] import of linear memory is not needed --- www/index.js | 1 - 1 file changed, 1 deletion(-) diff --git a/www/index.js b/www/index.js index 11c6167..1015361 100644 --- a/www/index.js +++ b/www/index.js @@ -1,5 +1,4 @@ import { Universe, Cell } from "wasm-game-of-life"; -import { memory } from "wasm-game-of-life/wasm_game_of_life_bg"; const CELL_SIZE = 5; // px const GRID_COLOR = "#CCCCCC";