Skip to content

Commit

Permalink
Merge branch 'wasm-pack'
Browse files Browse the repository at this point in the history
  • Loading branch information
lgarron committed Oct 8, 2023
2 parents 38e0310 + 427a905 commit 0fcc971
Show file tree
Hide file tree
Showing 19 changed files with 299 additions and 421 deletions.
416 changes: 61 additions & 355 deletions Cargo.lock

Large diffs are not rendered by default.

15 changes: 14 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ benchmark-rust:

.PHONY: clean
clean:
rm -rf ./.temp ./build ./src/js/generated-wasm/twsearch.* ./*.dwo ./target
rm -rf ./.temp ./build ./dist ./src/js/generated-wasm/twsearch.* ./*.dwo ./target

.PHONY: cpp-clean
cpp-clean:
Expand Down Expand Up @@ -217,3 +217,16 @@ build-rust:
.PHONY: lint-rust
lint-rust:
cargo clippy

# Rust WASM

.PHONY: build-rust-wasm
build-rust-wasm:
wasm-pack build --release --target web --out-dir "../../dist/wasm" src/rs
cat dist/wasm/package.json | jq ".type = \"module\"" > /tmp/twsearch.package.json.temp
mv /tmp/twsearch.package.json.temp dist/wasm/package.json
bun script/node-esm-compat.ts

.PHONY: test-rust-wasm
test-rust-wasm:
node "script/test-dist-wasm.js"
35 changes: 35 additions & 0 deletions script/node-esm-compat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env bun

import { readdir, readFile, writeFile } from "fs/promises";
import { join } from "path";

const filePath = new URL("../dist/wasm/twsearch.js", import.meta.url);

let modified = false; // For idempotence

let contents = await readFile(filePath, "utf-8");
const lines = [
`// Mangled so that bundlers don't try to inline the source.
const node_fs_promises_mangled = "node:-fs/pr-omises";
const node_fs_promises_unmangled = () => node_fs_promises_mangled.replace(/-/g, "");
`,
];
for (const line of contents.split("\n")) {
if (line.trim() === "input = fetch(input);") {
lines.push(` try {
input = await fetch(input);
} catch (e) {
if (!(e instanceof TypeError)) {
throw e;
}
input = await (await import(node_fs_promises_unmangled())).readFile(input);
}`);
modified = true;
} else {
lines.push(line);
}
}
if (modified) {
contents = lines.join("\n");
await writeFile(filePath, contents);
}
15 changes: 15 additions & 0 deletions script/test-dist-wasm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
console.log("loading…");

import {
default as init,
internal_init,
search_test,
} from "../dist/wasm/twsearch.js";

console.log("Initializating WASM");

await init();
await internal_init();

console.log("Initialized!");
console.log("Found alg:", search_test("R U R' U' R' F R2 U' R' U' R U R' F'"));
23 changes: 19 additions & 4 deletions src/rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,40 @@ edition = "2021"

[features]
default = []
console_error_panic_hook = []

[dependencies]
cityhash = "0.1.1"
cityhasher = "0.1.0"
clap = { version = "4.3.24", features = ["derive"] }
clap_complete = "4.3.2"
console_error_panic_hook = "0.1.7"
cubing = { version = "0.7.3" }
derive_more = "0.99.17"
indicatif = "0.17.6"
instant = { version = "0.1.12", features = ["wasm-bindgen"] }
rouille = "3.6.2"
serde = { version = "1.0.186", features = ["derive", "rc"] }
serde_json = "1.0.105"
thousands = "0.2.0"
wasm-bindgen = "0.2.87"

[dev-dependencies]
wait-timeout = "0.2.0"

[lib]
path = "./mod.rs"
crate-type = ["cdylib", "rlib"]

[[bin]]
name = "twsearch"
path = "./cli/main.rs"
[package.metadata.wasm-pack.lib]
path = "./wasm/mod.rs"

[dependencies.getrandom]
features = ["js"]

[package.metadata.wasm-pack.profile.release]
# Tell `rustc` to optimize for small code size.
opt-level = "s"

[package.metadata.wasm-pack.profile.release.wasm-bindgen]
# Should we emit the DWARF debug info custom sections?
dwarf-debug-info = false
5 changes: 2 additions & 3 deletions src/rs/cli/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use std::{
path::{Path, PathBuf},
process::exit,
sync::Arc,
time::Instant,
};

use commands::canonical_algs::canonical_algs;
Expand Down Expand Up @@ -168,7 +167,7 @@ fn search(search_command_args: SearchCommandArgs) -> Result<(), CommandError> {
}),
)?;

let search_start_time = Instant::now();
let search_start_time = instant::Instant::now();
let solutions = idf_search.search(
&scramble_pattern,
IndividualSearchOptions {
Expand All @@ -189,7 +188,7 @@ fn search(search_command_args: SearchCommandArgs) -> Result<(), CommandError> {
}
println!(
"// Entire search duration: {:?}",
Instant::now() - search_start_time
instant::Instant::now() - search_start_time
);

Ok(())
Expand Down
12 changes: 5 additions & 7 deletions src/rs/examples/benchmark.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::time::Instant;

use cubing::{parse_alg, parse_move, puzzles::cube3x3x3_kpuzzle};

use cubing::kpuzzle::{
Expand Down Expand Up @@ -54,7 +52,7 @@ fn test_packed(num_moves: usize) {
];

let mut buffer = PackedKPatternBuffer::from(packed_kpuzzle.default_pattern());
let start = Instant::now();
let start = instant::Instant::now();
for i in 0..num_moves {
buffer.apply_transformation(&move_transformations[i % 18]);
}
Expand All @@ -75,7 +73,7 @@ fn test_packed(num_moves: usize) {
let final_pattern = buffer.current().clone();

let mut pattern = packed_kpuzzle.default_pattern();
let start = Instant::now();
let start = instant::Instant::now();
for i in 0..num_moves {
pattern = pattern.apply_transformation(&move_transformations[i % 18]);
}
Expand All @@ -95,7 +93,7 @@ fn test_packed(num_moves: usize) {
assert_eq!(pattern, final_pattern);

let mut buffer = PackedKPatternBuffer::from(packed_kpuzzle.default_pattern());
let start = Instant::now();
let start = instant::Instant::now();
for i in 0..num_moves {
buffer.apply_transformation(&move_transformations[i % 18]);
_ = buffer.current().hash();
Expand All @@ -116,7 +114,7 @@ fn test_packed(num_moves: usize) {
assert_eq!(buffer.current(), &final_pattern);

let mut pattern = packed_kpuzzle.default_pattern();
let start = Instant::now();
let start = instant::Instant::now();
for i in 0..num_moves {
pattern = pattern.apply_transformation(&move_transformations[i % 18]);
// _ = pattern.hash()
Expand Down Expand Up @@ -166,7 +164,7 @@ fn test_unpacked(num_moves: usize) {
];

let mut pattern = kpuzzle.default_pattern();
let start = Instant::now();
let start = instant::Instant::now();
for i in 0..num_moves {
pattern = pattern.apply_transformation(&move_transformations[i % 18]);
}
Expand Down
6 changes: 3 additions & 3 deletions src/rs/gods_algorithm/gods_algorithm_table.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{collections::HashMap, mem, time::Instant, vec};
use std::{collections::HashMap, mem, vec};

use thousands::Separable;

Expand Down Expand Up @@ -98,7 +98,7 @@ impl GodsAlgorithmSearch {
let mut current_depth = 0;
let mut num_patterns_total = 1;

let start_time = Instant::now();
let start_time = instant::Instant::now();
while !self.table.completed {
let last_depth_patterns: BulkQueue<QueueItem> = mem::replace(
&mut self.bulk_queues[current_depth],
Expand Down Expand Up @@ -204,7 +204,7 @@ impl GodsAlgorithmSearch {
factor_number(num_patterns_total.try_into().unwrap()),
if num_patterns_total == 1 { "" } else { "s" },
max_depth,
Instant::now() - start_time
instant::Instant::now() - start_time
);
}
}
3 changes: 3 additions & 0 deletions src/rs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,6 @@ pub use search::*;

mod serve;
pub use serve::*;

mod wasm;
pub use wasm::*;
1 change: 1 addition & 0 deletions src/rs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{ "type": "module" }
11 changes: 10 additions & 1 deletion src/rs/packed/packed_kpuzzle.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{alloc::Layout, sync::Arc, fmt::Debug};

use cubing::{
alg::Move,
alg::{Move, Alg},
kpuzzle::{
InvalidAlgError, InvalidDefinitionError, KPuzzle, KPuzzleOrbitName, KTransformation, KPattern,
},
Expand Down Expand Up @@ -160,6 +160,15 @@ impl PackedKPuzzle {
self.pack_transformation(&unpacked_ktransformation)
}

// TODO: implement this directly
pub fn transformation_from_alg(
&self,
alg: &Alg,
) -> Result<PackedKTransformation, ConversionError> {
let unpacked_ktransformation = self.data.kpuzzle.transformation_from_alg(alg)?;
self.pack_transformation(&unpacked_ktransformation)
}

pub fn pack_transformation(
&self,
unpacked_ktransformation: &KTransformation,
Expand Down
5 changes: 3 additions & 2 deletions src/rs/packed/packed_ktransformation.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{fmt::Debug, mem::swap};
use std::{fmt::Debug, hash::BuildHasher, mem::swap};

use super::{
byte_conversions::{u8_to_usize, usize_to_u8},
Expand Down Expand Up @@ -126,7 +126,8 @@ impl PackedKTransformation {
}

pub fn hash(&self) -> u64 {
cityhash::city_hash_64(self.byte_slice())
let h = cityhasher::CityHasher::new();
h.hash_one(self.byte_slice())
}

pub fn unpack(&self) -> KTransformation {
Expand Down
5 changes: 3 additions & 2 deletions src/rs/packed/packed_orbit_data.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{
alloc::{alloc, dealloc},
fmt::Debug,
hash::Hash,
hash::{BuildHasher, Hash},
};

use super::{
Expand Down Expand Up @@ -97,7 +97,8 @@ impl PackedOrbitData {
}

pub fn hash(&self) -> u64 {
cityhash::city_hash_64(self.byte_slice())
let h = cityhasher::CityHasher::new();
h.hash_one(self.byte_slice())
}
}

Expand Down
13 changes: 5 additions & 8 deletions src/rs/search/recursive_work_tracker.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use std::{
sync::Arc,
time::{Duration, Instant},
};
use std::{sync::Arc, time::Duration};

use thousands::Separable;

Expand All @@ -12,7 +9,7 @@ pub(crate) struct RecursiveWorkTracker {
// TODO: support custom writes intead of sending to stdout/stderr
latest_depth: usize,
latest_depth_num_recursive_calls: usize,
latest_depth_start_time: Instant,
latest_depth_start_time: instant::Instant,
latest_depth_duration: Duration,
latest_depth_finished: bool,

Expand All @@ -28,7 +25,7 @@ impl RecursiveWorkTracker {
work_name,
latest_depth: 0,
previous_depth_num_recursive_calls: 0,
latest_depth_start_time: Instant::now(),
latest_depth_start_time: instant::Instant::now(),
latest_depth_duration: Duration::ZERO,
latest_depth_finished: true,
latest_depth_num_recursive_calls: 0,
Expand All @@ -43,7 +40,7 @@ impl RecursiveWorkTracker {

// Pass `None` as the message to avoid printing anything.
pub fn start_depth(&mut self, depth: usize, message: Option<&str>) {
self.latest_depth_start_time = Instant::now();
self.latest_depth_start_time = instant::Instant::now();

self.latest_depth = depth;
self.latest_depth_duration = Duration::ZERO;
Expand All @@ -67,7 +64,7 @@ impl RecursiveWorkTracker {
self.latest_depth,
));
}
self.latest_depth_duration = Instant::now() - self.latest_depth_start_time;
self.latest_depth_duration = instant::Instant::now() - self.latest_depth_start_time;
let rate = (self.latest_depth_num_recursive_calls as f64
/ (self.latest_depth_duration).as_secs_f64()) as usize;
self.search_logger.write_info(&format!(
Expand Down
Loading

0 comments on commit 0fcc971

Please sign in to comment.