diff --git a/Cargo.lock b/Cargo.lock index c2ccdc8..c43dfb0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -24,6 +24,17 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "gol" +version = "0.1.0" +dependencies = [ + "cfg-if", + "console_error_panic_hook", + "wasm-bindgen", + "wasm-bindgen-test", + "web-sys", +] + [[package]] name = "greet" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 5b6037f..e013415 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,6 @@ [workspace] members = [ + "gol", "greet", ] resolver = "2" @@ -8,7 +9,7 @@ resolver = "2" version = "0.1.0" authors = ["Hackworth Ltd "] edition = "2021" -license = "0BSD" +license = "Apache-2.0" repository = "https://github.com/hackworthltd/nix-rust-wasm-npm" description = "A boring package used to test Nix, Rust, Wasm, and npm integration." readme = "README.md" diff --git a/LICENSE b/LICENSE index a039785..f433b1a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,14 +1,177 @@ -BSD Zero Clause License -Copyright © 2024 Hackworth Ltd + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/README.md b/README.md index 248c3b2..a48ba20 100644 --- a/README.md +++ b/README.md @@ -7,5 +7,5 @@ exists only for the sake of vetting the tooling. ## License -This project is licensed under the [Zero-Clause BSD ("0BSD") -license](https://opensource.org/license/0bsd). +This project is licensed under the [Apache 2.0 +license](https://opensource.org/license/apache-2-0). diff --git a/flake.nix b/flake.nix index fcdf78e..89e0478 100644 --- a/flake.nix +++ b/flake.nix @@ -116,59 +116,67 @@ doCheck = false; }; - fileSetForCrate = crate: lib.fileset.toSource { - root = ./.; - fileset = lib.fileset.unions [ - ./Cargo.toml - ./Cargo.lock - crate - ]; - }; - - greetCrateArgs = baseArgs: pname: baseArgs // { - inherit pname; - cargoExtraArgs = "${cargoExtraArgs} --package greet"; - src = fileSetForCrate ./greet; - inherit (craneLib.crateNameFromCargoToml { cargoToml = ./greet/Cargo.toml; }) version; - }; - - greet-crate = craneLib.buildPackage (greetCrateArgs individualCrateArgs "${pname}-greet"); - - greet-crate-wasm = craneLibWasm.buildPackage (greetCrateArgs individualCrateArgsWasm "${pname}-greet-wasm"); - - greet-crate-wasm-check = craneLibWasm.mkCargoDerivation ((greetCrateArgs individualCrateArgsWasm "${pname}-greet-wasm-npm") // { + mkWasmNpmPackage = pkgName: crateArgs: craneLibWasm.mkCargoDerivation (crateArgs // { doInstallCargoArtifacts = false; buildPhaseCargoCommand = '' - WASM_PACK_CACHE=.wasm-pack-cache wasm-pack test --chrome --headless --mode no-install --release greet --profile release --frozen --offline + WASM_PACK_CACHE=.wasm-pack-cache wasm-pack build --out-dir $out/pkg --scope "${npm-scope}" --mode no-install --target bundler --release ${pkgName} --profile release --frozen --offline ''; nativeBuildInputs = [ pkgs.binaryen pkgs.wasm-pack wasm-bindgen-cli - - # We would prefer to use `geckodriver`, but it hangs on - # our tests in the Nix sandbox, for some reason. - pkgs.chromedriver - pkgs.chromium ]; }); - greet-crate-wasm-npm = craneLibWasm.mkCargoDerivation ((greetCrateArgs individualCrateArgsWasm "${pname}-greet-wasm-npm") // { + mkWasmCheck = pkgName: crateArgs: craneLibWasm.mkCargoDerivation (crateArgs // { doInstallCargoArtifacts = false; buildPhaseCargoCommand = '' - WASM_PACK_CACHE=.wasm-pack-cache wasm-pack build --out-dir $out/pkg --scope "${npm-scope}" --mode no-install --target bundler --release greet --profile release --frozen --offline + WASM_PACK_CACHE=.wasm-pack-cache wasm-pack test --chrome --headless --mode no-install --release ${pkgName} --profile release --frozen --offline ''; nativeBuildInputs = [ pkgs.binaryen pkgs.wasm-pack wasm-bindgen-cli + + # We would prefer to use `geckodriver`, but it hangs on + # our tests in the Nix sandbox, for some reason. + pkgs.chromedriver + pkgs.chromium ]; }); + greetCrateArgs = baseArgs: pname: baseArgs // { + inherit pname; + cargoExtraArgs = "${cargoExtraArgs} --package greet"; + inherit (craneLib.crateNameFromCargoToml { cargoToml = ./greet/Cargo.toml; }) version; + }; + + golCrateArgs = baseArgs: pname: baseArgs // { + inherit pname; + cargoExtraArgs = "${cargoExtraArgs} --package gol"; + inherit (craneLib.crateNameFromCargoToml { cargoToml = ./gol/Cargo.toml; }) version; + }; + + greet-crate = craneLib.buildPackage (greetCrateArgs individualCrateArgs "${pname}-greet"); + + greet-crate-wasm = craneLibWasm.buildPackage (greetCrateArgs individualCrateArgsWasm "${pname}-greet-wasm"); + + greet-crate-wasm-check = mkWasmCheck "greet" (greetCrateArgs individualCrateArgsWasm "${pname}-greet-wasm-check"); + + greet-crate-wasm-npm = mkWasmNpmPackage "greet" (greetCrateArgs individualCrateArgsWasm "${pname}-greet-wasm-npm"); + + gol-crate = craneLib.buildPackage (golCrateArgs individualCrateArgs "${pname}-gol"); + + gol-crate-wasm = craneLibWasm.buildPackage (golCrateArgs individualCrateArgsWasm "${pname}-gol-wasm"); + + gol-crate-wasm-check = mkWasmCheck "gol" (golCrateArgs individualCrateArgsWasm "${pname}-gol-wasm-check"); + + gol-crate-wasm-npm = mkWasmNpmPackage "gol" (golCrateArgs individualCrateArgsWasm "${pname}-gol-wasm-npm"); + inputsFrom = [ config.treefmt.build.devShell config.pre-commit.devShell @@ -192,13 +200,14 @@ }; } // (pkgs.lib.optionalAttrs (system == "x86_64-linux") { inherit greet-crate-wasm-check; + inherit gol-crate-wasm-check; }); packages = { - default = greet-crate-wasm-npm; - inherit greet-crate; - inherit greet-crate-wasm; - inherit greet-crate-wasm-npm; + default = gol-crate-wasm-npm; + inherit greet-crate gol-crate; + inherit greet-crate-wasm gol-crate-wasm; + inherit greet-crate-wasm-npm gol-crate-wasm-npm; }; treefmt.config = { diff --git a/gol/Cargo.toml b/gol/Cargo.toml new file mode 100644 index 0000000..04cd3a1 --- /dev/null +++ b/gol/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "gol" +version = "0.1.0" +authors = [ + "Nick Fitzgerald ", + "Hackworth Ltd ", +] +edition = "2021" +license = "Apache-2.0" +repository = "https://github.com/hackworthltd/nix-rust-wasm-npm" +description = "The Game of Life in Wasm, from the Rust Wasm tutorial." + +[lib] +crate-type = ["cdylib", "rlib"] + +[features] +default = ["console_error_panic_hook"] + +[dependencies] +cfg-if = "1.0.0" +wasm-bindgen = "0.2.92" + +# The `console_error_panic_hook` crate provides better debugging of panics by +# logging them with `console.error`. This is great for development, but requires +# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for +# code size when deploying. +console_error_panic_hook = { version = "0.1.7", optional = true } + +[dependencies.web-sys] +version = "0.3.69" +features = [ + "console", +] + +[dev-dependencies] +wasm-bindgen-test = "0.3.42" diff --git a/gol/src/lib.rs b/gol/src/lib.rs new file mode 100644 index 0000000..7974174 --- /dev/null +++ b/gol/src/lib.rs @@ -0,0 +1,226 @@ +extern crate cfg_if; +extern crate wasm_bindgen; +extern crate web_sys; + +mod utils; + +use std::fmt; +use wasm_bindgen::prelude::*; +use web_sys::console; + +pub struct Timer<'a> { + name: &'a str, +} + +impl<'a> Timer<'a> { + pub fn new(name: &'a str) -> Timer<'a> { + console::time_with_label(name); + Timer { name } + } +} + +impl<'a> Drop for Timer<'a> { + fn drop(&mut self) { + console::time_end_with_label(self.name); + } +} + +#[wasm_bindgen] +#[repr(u8)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Cell { + Dead = 0, + Alive = 1, +} + +impl Cell { + fn toggle(&mut self) { + *self = match *self { + Cell::Dead => Cell::Alive, + Cell::Alive => Cell::Dead, + }; + } +} + +#[wasm_bindgen] +pub struct Universe { + width: u32, + height: u32, + cells: Vec, +} + +impl Universe { + fn get_index(&self, row: u32, column: u32) -> usize { + (row * self.width + column) as usize + } + + /// Get the dead and alive values of the entire universe. + pub fn get_cells(&self) -> &[Cell] { + &self.cells + } + + /// Set cells to be alive in a universe by passing the row and column + /// of each cell as an array. + pub fn set_cells(&mut self, cells: &[(u32, u32)]) { + for (row, col) in cells.iter().cloned() { + let idx = self.get_index(row, col); + self.cells[idx] = Cell::Alive; + } + } + + 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 south = if row == self.height - 1 { 0 } else { row + 1 }; + + let west = if column == 0 { + self.width - 1 + } else { + column - 1 + }; + + let east = if column == self.width - 1 { + 0 + } else { + column + 1 + }; + + let nw = self.get_index(north, west); + count += self.cells[nw] as u8; + + let n = self.get_index(north, column); + count += self.cells[n] as u8; + + let ne = self.get_index(north, east); + count += self.cells[ne] as u8; + + let w = self.get_index(row, west); + count += self.cells[w] as u8; + + let e = self.get_index(row, east); + count += self.cells[e] as u8; + + let sw = self.get_index(south, west); + count += self.cells[sw] as u8; + + let s = self.get_index(south, column); + count += self.cells[s] as u8; + + let se = self.get_index(south, east); + count += self.cells[se] as u8; + + count + } +} + +/// Public methods, exported to JavaScript. +#[wasm_bindgen] +#[allow(clippy::new_without_default)] +impl Universe { + pub fn tick(&mut self) { + // let _timer = Timer::new("Universe::tick"); + + let mut next = self.cells.clone(); + + for row in 0..self.height { + for col in 0..self.width { + let idx = self.get_index(row, col); + let cell = self.cells[idx]; + let live_neighbors = self.live_neighbor_count(row, col); + + let next_cell = match (cell, live_neighbors) { + // Rule 1: Any live cell with fewer than two live neighbours + // dies, as if caused by underpopulation. + (Cell::Alive, x) if x < 2 => Cell::Dead, + // Rule 2: Any live cell with two or three live neighbours + // lives on to the next generation. + (Cell::Alive, 2) | (Cell::Alive, 3) => Cell::Alive, + // Rule 3: Any live cell with more than three live + // neighbours dies, as if by overpopulation. + (Cell::Alive, x) if x > 3 => Cell::Dead, + // Rule 4: Any dead cell with exactly three live neighbours + // becomes a live cell, as if by reproduction. + (Cell::Dead, 3) => Cell::Alive, + // All other cells remain in the same state. + (otherwise, _) => otherwise, + }; + + next[idx] = next_cell; + } + } + + self.cells = next; + } + + pub fn new() -> Universe { + utils::set_panic_hook(); + + let width = 128; + let height = 128; + + let cells = (0..width * height) + .map(|i| { + if i % 2 == 0 || i % 7 == 0 { + Cell::Alive + } else { + Cell::Dead + } + }) + .collect(); + + Universe { + width, + height, + cells, + } + } + + pub fn width(&self) -> u32 { + self.width + } + + /// Set the width of the universe. + /// + /// Resets all cells to the dead state. + pub fn set_width(&mut self, width: u32) { + self.width = width; + self.cells = (0..width * self.height).map(|_i| Cell::Dead).collect(); + } + + pub fn height(&self) -> u32 { + self.height + } + + /// Set the height of the universe. + /// + /// Resets all cells to the dead state. + pub fn set_height(&mut self, height: u32) { + self.height = height; + self.cells = (0..self.width * height).map(|_i| Cell::Dead).collect(); + } + + pub fn cells(&self) -> *const Cell { + self.cells.as_ptr() + } + + pub fn toggle_cell(&mut self, row: u32, column: u32) { + let idx = self.get_index(row, column); + self.cells[idx].toggle(); + } +} + +impl fmt::Display for Universe { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + for line in self.cells.as_slice().chunks(self.width as usize) { + for &cell in line { + let symbol = if cell == Cell::Dead { '◻' } else { '◼' }; + write!(f, "{}", symbol)?; + } + writeln!(f)?; + } + + Ok(()) + } +} diff --git a/gol/src/utils.rs b/gol/src/utils.rs new file mode 100644 index 0000000..9b1f5e5 --- /dev/null +++ b/gol/src/utils.rs @@ -0,0 +1,13 @@ +use cfg_if::cfg_if; + +cfg_if! { + // When the `console_error_panic_hook` feature is enabled, we can call the + // `set_panic_hook` function to get better error messages if we ever panic. + if #[cfg(feature = "console_error_panic_hook")] { + extern crate console_error_panic_hook; + pub use self::console_error_panic_hook::set_once as set_panic_hook; + } else { + #[inline] + pub fn set_panic_hook() {} + } +} diff --git a/gol/tests/web.rs b/gol/tests/web.rs new file mode 100644 index 0000000..77828ce --- /dev/null +++ b/gol/tests/web.rs @@ -0,0 +1,48 @@ +//! Test suite for the Web and headless browsers. + +#![cfg(target_arch = "wasm32")] + +extern crate wasm_bindgen_test; +use wasm_bindgen_test::*; + +extern crate gol; +use gol::Universe; + +wasm_bindgen_test_configure!(run_in_browser); + +#[wasm_bindgen_test] +fn pass() { + assert_eq!(1 + 1, 2); +} + +#[cfg(test)] +pub fn input_spaceship() -> Universe { + let mut universe = Universe::new(); + universe.set_width(6); + universe.set_height(6); + universe.set_cells(&[(1, 2), (2, 3), (3, 1), (3, 2), (3, 3)]); + universe +} + +#[cfg(test)] +pub fn expected_spaceship() -> Universe { + let mut universe = Universe::new(); + universe.set_width(6); + universe.set_height(6); + universe.set_cells(&[(2, 1), (2, 3), (3, 2), (3, 3), (4, 2)]); + universe +} + +#[wasm_bindgen_test] +pub fn test_tick() { + // Let's create a smaller Universe with a small spaceship to test! + let mut input_universe = input_spaceship(); + + // This is what our spaceship should look like + // after one tick in our universe. + let expected_universe = expected_spaceship(); + + //// Call `tick` and then see if the cells in the `Universe`s are the same. + input_universe.tick(); + assert_eq!(&input_universe.get_cells(), &expected_universe.get_cells()); +} diff --git a/greet/Cargo.toml b/greet/Cargo.toml index 2c94a9c..045da93 100644 --- a/greet/Cargo.toml +++ b/greet/Cargo.toml @@ -3,7 +3,7 @@ name = "greet" version = "0.1.0" authors = ["Hackworth Ltd "] edition = "2021" -license = "0BSD" +license = "Apache-2.0" repository = "https://github.com/hackworthltd/nix-rust-wasm-npm" description = "A boring package used to test Nix, Rust, Wasm, and npm integration."