Search code examples
rustwebassemblyrust-chrono

chrono kills my Rust WebAssembly function


I have a Hello World WebAssembly and I tried to add some code to show the time.

The following line appears to kill the function and it returns nothing (no text, no error)

let dt = Utc::now();

If I comment out the line the function runs as before and returns a string.

Is this happening to anyone else?

I have the 2 lines below at the top of my rs file:

extern crate chrono;
use chrono::{Duration, Utc};

I have the following in the dependencies in the toml file:

chrono = "0.4"

Solution

  • To be used in WASM, chrono must be compiled with wasmbind feature.

    I wasn't able to find this in documentation, however. This feature was referenced in source code:

    #[cfg(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind"))]
    pub fn now() -> DateTime<Utc> {
        let now = js_sys::Date::new_0();
        DateTime::<Utc>::from(now)
    }
    

    Also, there's an open issue for documenting this behavior.


    There are several reasons for the behavior you see.

    1. Getting current time is usually a function provided by the standard library. In particular, for non-WASM targets chrono calls the get_time function from the time crate, which then can delegate to the libc or something, depending on the target. However, when you compile to WASM, standard library is rather limited - there are no system calls, for example, and so a bunch of functionality must be provided in some other ways; in particular, aforementioned get_time function is explicitly unimplemented for this target, so that any call to it will panic.
    2. Library authors generally don't want you to force building dependencies you don't need. In particular, if some dependency (here, js-sys) is necessary only for some targets, it will be hidden behind feature flag, so that users of library (here, chrono) on e.g. Windows or Linux will not pull it unnecessarily. That's why you need to enable the feature explicitly, even if without it the library will be unusable on your target.
    3. The last bit of information is the limited error handling in WASM: essentially, the only thing it can do by default is to halt on panic. Some assistance here can be provided by console_error_panic_hook crate, which, if added to your project, would show you the "not yet implemented" error in the console window.