Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wasm: allow Instant to represent instants in past #46

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,14 @@ impl Eq for Instant {}
impl Instant {
#[inline]
pub fn now() -> Self {
Instant(duration_from_f64(now()))
// `performance.now()` starts counting from the creation of the page, which mean that
// instants before the page start are negative.
//
// So, to allow represing past instants using a `Duration` (that can't represent negative
// values), the duration will be increased by 2^63 seconds.

let duration = duration_from_f64(now());
Self(duration + Duration::from_secs(1 << 63))
}

#[inline]
Expand Down
7 changes: 7 additions & 0 deletions tests/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,10 @@ fn test_system_time() {
.is_err());
}

#[wasm_bindgen_test]
fn test_past() {
let hundred_sec = Duration::from_secs(100);
let hundred_seconds_ago = Instant::now() - hundred_sec;
assert!(hundred_seconds_ago.elapsed() >= hundred_sec);
}