Skip to content

Commit

Permalink
Introducing new methods for instance (#16)
Browse files Browse the repository at this point in the history
* Introducing new methods for instance

* Fixed recursion issues and add checked_duration_since method

* Added tests for micro seconds precision
  • Loading branch information
whizsid authored Oct 11, 2024
1 parent f369eb6 commit e919cb0
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 20 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,6 @@ serde = ["serde_crate"]
wasm-bindgen-test = "0.3.0"
wasm-bindgen-futures = "0.4"
serde_json = "^1.0"

[lib]
crate-type = ["cdylib", "rlib"]
65 changes: 45 additions & 20 deletions src/std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,13 @@ use std::time::Duration;
use crate::js::performance_now;

#[derive(Debug, Copy, Clone)]
pub struct Instant {
/// Unit is milliseconds.
inner: f64,
}
pub struct Instant(Duration);

impl PartialEq for Instant {
fn eq(&self, other: &Instant) -> bool {
// Note that this will most likely only compare equal if we clone an `Instant`,
// but that's ok.
self.inner == other.inner
self.0 == other.0
}
}

Expand All @@ -49,7 +46,7 @@ impl PartialOrd for Instant {

impl Ord for Instant {
fn cmp(&self, other: &Self) -> Ordering {
self.inner.partial_cmp(&other.inner).unwrap()
self.0.partial_cmp(&other.0).unwrap()
}
}

Expand All @@ -65,56 +62,84 @@ impl Instant {
}

pub(crate) fn now_js() -> Instant {
let val = performance_now();
Instant { inner: val }
let val = (performance_now() * 1000.0) as u64;
Instant(Duration::from_micros(val))
}

pub fn duration_since(&self, earlier: Instant) -> Duration {
*self - earlier
self.checked_duration_since(earlier).unwrap_or_default()
}

pub fn elapsed(&self) -> Duration {
Instant::now() - *self
}

pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
self.0.checked_sub(earlier.0)
}

pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
self.checked_duration_since(earlier).unwrap_or_default()
}

pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
self.0.checked_add(duration).map(Instant)
}

pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
self.0.checked_sub(duration).map(Instant)
}
}

impl Add<Duration> for Instant {
type Output = Instant;

/// # Panics
///
/// This function may panic if the resulting point in time cannot be represented by the
/// underlying data structure. See [`Instant::checked_add`] for a version without panic.
fn add(self, other: Duration) -> Instant {
let new_val = self.inner + other.as_millis() as f64;
Instant { inner: new_val }
self.checked_add(other)
.expect("overflow when adding duration to instant")
}
}

impl AddAssign<Duration> for Instant {
fn add_assign(&mut self, rhs: Duration) {
self.inner += rhs.as_millis() as f64;
fn add_assign(&mut self, other: Duration) {
*self = *self + other;
}
}

impl Sub<Duration> for Instant {
type Output = Instant;

fn sub(self, other: Duration) -> Instant {
let new_val = self.inner - other.as_millis() as f64;
Instant { inner: new_val }
self.checked_sub(other)
.expect("overflow when subtracting duration from instant")
}
}

impl SubAssign<Duration> for Instant {
fn sub_assign(&mut self, rhs: Duration) {
self.inner -= rhs.as_millis() as f64;
fn sub_assign(&mut self, other: Duration) {
*self = *self - other;
}
}

impl Sub<Instant> for Instant {
type Output = Duration;

/// Returns the amount of time elapsed from another instant to this one,
/// or zero duration if that instant is later than this one.
///
/// # Panics
///
/// Previous Rust versions panicked when `other` was later than `self`. Currently this
/// method saturates. Future versions may reintroduce the panic in some circumstances.
/// See [Monotonicity].
///
/// [Monotonicity]: Instant#monotonicity
fn sub(self, other: Instant) -> Duration {
let ms = self.inner - other.inner;
assert!(ms >= 0.0);
Duration::from_millis(ms as u64)
self.duration_since(other)
}
}

Expand Down
10 changes: 10 additions & 0 deletions tests/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,16 @@ pub mod tokio_tests {
});
}

#[wasm_bindgen_test]
pub async fn test_micro_second_precision() {
initialize();
let a = Instant::now();
advance(Duration::from_micros(435)).await;
let b = Instant::now();
let diff = b - a;
assert_eq!(diff.as_micros(), 435);
}

pub mod sleep_tests {

use super::*;
Expand Down

0 comments on commit e919cb0

Please sign in to comment.