0

I want to rust read-fonts within a browser using wasm.

Please see the following github repository with the code:

https://github.com/moontypespace/hello_wasm/tree/main

I get the following error:

hello_wasm_bg.wasm:0x5117 Uncaught (in promise) RuntimeError: unreachable
    at hello_wasm_bg.wasm:0x5117
    at hello_wasm_bg.wasm:0x5ebe
    at hello_wasm_bg.wasm:0x5872
    at hello_wasm_bg.wasm:0x2e10
    at mod_os2_us_weight_class (hello_wasm.js:96:10)
    at index.html:12:9

I am able to reach the rust function mod_os2_us_weight_class and run it without any issues, if there is only an alert with some text. As shown in the following demo:
https://developer.mozilla.org/en-US/docs/WebAssembly/Rust_to_Wasm

But when I want to make use of read-fonts to load a font and get it's data, I get the mentioned error. The rust code seems to work. For reference please see the following:
How do I modify a font and save it with Rust 'write-fonts'?

Please make sure to replace the font paths when you play with the github repository.


Edit: Code to reproduce issue:

The following Rust code

use wasm_bindgen::prelude::*;
use read_fonts::{FontRead, FontRef, TableProvider, TopLevelTable};

#[wasm_bindgen]
extern {
    pub fn alert(s: &str);
}

#[wasm_bindgen]
pub fn mod_os2_us_weight_class(input_path: &str, output_path: &str, value_str: &str,) {
    let value: u16 = value_str.parse().unwrap();

    let font_data = std::fs::read(input_path).unwrap();
    let font = FontRef::new(&font_data).unwrap();

    let os2 = font.os2().expect("missing OS/2 table");
    alert(&format!("os2.us_weight_class(): {}!", os2.us_weight_class()));

}

is invoked from JS

import init, { greet, mod_os2_us_weight_class } from "./pkg/hello_wasm.js";
init().then(() => {
    mod_os2_us_weight_class("/Users/ollimeier/Documents/Vary-Black.otf", "/Users/ollimeier/Documents/Vary-Black_mod20230607.otf", "666");
});

Caesar
  • 6,733
  • 4
  • 38
  • 44
  • 1
    Hi. Please do not provide links to external sources of code. Instead write here a full minimal reproducible example. – Aleksander Krauze Jun 07 '23 at 20:43
  • 2
    You simply can't use `std::fs::read` in `web_sys` environments. And the `unreachable` is likely reached through the panic you cause by using `unwrap`. Proper error handling would be nice, but [`unwrap_throw`](https://docs.rs/wasm-bindgen/latest/wasm_bindgen/trait.UnwrapThrowExt.html#method.unwrap_throw) should do as a stopgap. – Caesar Jun 07 '23 at 23:05

0 Answers0