0019-wasm-康威生命游戏
环境
- Time 2022-05-17
- Rust 1.60.0
- Node 12.22.5
- wasm-pack 0.10.2
前言
说明
参考:https://rustwasm.github.io/docs/book/game-of-life/debugging.html
目标
在上一节的基础上进行。对 wasm_bindgen
进行调试。包括以下两方面:
- 直接在 Rust 中向浏览器控制台输出日志。
- 发生 panic 后,能在浏览器中找到 Rust 中对应的文件和行数。
引入依赖
打印日志需要 web-sys
依赖,并启用 console
特性。
web-sys = {version = "*", features = ["console"]}
定义日志宏
macro_rules! log {
( $( $t:tt )* ) => {
web_sys::console::log_1(&format!( $( $t )* ).into());
}
}
记录日志
pub fn new(width: u32, height: u32) -> Universe {
log!("new universe, width: {}, height: {}", width, height);
let size = (width * height) as usize;
let mut cells = FixedBitSet::with_capacity(size);
(0..size).for_each(|i| cells.set(i, Math::random() < 0.5));
Universe {
width,
height,
cells,
}
}
日志效果
增加 panic
pub fn new(width: u32, height: u32) -> Universe {
// #[cfg(feature = "console_error_panic_hook")]
// console_error_panic_hook::set_once();
log!("new universe, width: {}, height: {}", width, height);
let size = (width * height) as usize;
let mut cells = FixedBitSet::with_capacity(size);
(0..size).for_each(|i| cells.set(i, Math::random() < 0.5));
Universe {
width,
height,
cells,
};
panic!("this is my panic");
}
异常信息
在浏览器中看不到异常信息是什么,出在什么地方。
打开 panic_hook
将注释掉的 panic_hook
打开。
pub fn new(width: u32, height: u32) -> Universe {
#[cfg(feature = "console_error_panic_hook")]
console_error_panic_hook::set_once();
log!("new universe, width: {}, height: {}", width, height);
let size = (width * height) as usize;
let mut cells = FixedBitSet::with_capacity(size);
(0..size).for_each(|i| cells.set(i, Math::random() < 0.5));
Universe {
width,
height,
cells,
};
panic!("this is my panic");
}
debug 构建
C:\Users\jiangbo\workspace\rust\game>wasm-pack build --debug
[INFO]: Checking for the Wasm target...
[INFO]: Compiling to Wasm...
Compiling game v0.1.0 (C:\Users\jiangbo\workspace\rust\game)
Finished dev [unoptimized + debuginfo] target(s) in 0.94s
[WARN]: :-) origin crate has no README
[INFO]: Installing wasm-bindgen...
[INFO]: Optional fields missing from Cargo.toml: 'description', 'repository', and 'license'. These are not necessary, but recommended
[INFO]: :-) Done in 1.87s
[INFO]: :-) Your wasm pkg is ready to publish at C:\Users\jiangbo\workspace\rust\game\pkg.
错误详细信息
总结
对康威生命游戏进行调试,包括打印浏览器日志信息和追踪调用栈信息。