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..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"; @@ -126,8 +125,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();