Possibility of a "global time source" for wasm targets

My idea is having something like the #[global_allocator] macro but for a "time source", and have std::time::Instant::now() use it.

Right now whenever we need to use time on wasm we replace uses of std::time::Instant for a type defined on wasmtimer, web-time, etc, with my suggestion maybe it would be possible to have those crates provide a type that can be used with a #[global_time_source] macro and have std::time::Instant take the time from there

#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;

#[cfg(target_arch = "wasm32")]
#[global_time_source]
static CLOCK: web_time::Clock = web_time::Clock;
// static CLOCK: wasmtimer::Clock = wasmtimer::Clock;

fn main() {
    std::time::Instant::now();
}

Having this option would be very nice for wasm32-unknown-unknown users, including myself, but the problem I see with it is that it only makes sense for wasm32-unknown-unknown users, given the status quo. wasm32-unknown-unknown having a stubbed-out std is an unusual situation; other targets generally either have a non-panicking std (even if, say, all fs operations return errors) or don’t have std at all. But perhaps there are other targets that can’t natively implement Instant that I don’t know of (the source code would take more work to make an exhaustive list out of) or new odd platforms will come along.

In any case, I don’t think this is a bad feature; I’m just unsure whether it has enough use cases for the Rust maintainers to be willing to add this complexity.

What we need is not another special case -- libs-api has talked about not wanting to own more of these -- but some generalized language feature for pluggable implementations for things that allocators could also migrate to.

Imagine some kind of #[magic_pluggable_thing] pub static ALLOCATOR: impl GlobalAlloc; that different crates could provide, say.

We'd then use that for all kinds of things -- float parsing, for example, which is giant in code size so people might want to just always-panic or use a shared implementation between their rust and C code rather than the one in core.

(That'll take a bunch of design work, though, across lots of stuff.) Oh, see below.

1 Like

Isn't that language feature externally implementable items? Tracking Issue for externally implementable items · Issue #125418 · rust-lang/rust · GitHub

2 Likes

fascinating