#[cfg(not(target_arch = "wasm32"))]
use std::time::Duration as StdDuration;
#[cfg(not(target_arch = "wasm32"))]
use tokio::time;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Duration {
millis: u64,
}
impl Duration {
pub fn from_secs(secs: u64) -> Self {
Self {
millis: secs * 1000,
}
}
pub fn from_millis(millis: u64) -> Self {
Self { millis }
}
pub fn as_secs(&self) -> u64 {
self.millis / 1000
}
pub fn as_millis(&self) -> u64 {
self.millis
}
pub fn as_secs_f64(&self) -> f64 {
self.millis as f64 / 1000.0
}
pub fn is_zero(&self) -> bool {
self.millis == 0
}
}
impl Default for Duration {
fn default() -> Self {
Self::from_secs(0)
}
}
impl From<u64> for Duration {
fn from(secs: u64) -> Self {
Self::from_secs(secs)
}
}
#[cfg(not(target_arch = "wasm32"))]
pub async fn sleep(duration: Duration) {
if duration.is_zero() {
return;
}
time::sleep(StdDuration::from_secs(duration.as_secs())).await;
}
#[cfg(target_arch = "wasm32")]
pub async fn sleep(_duration: Duration) {
}
#[derive(Clone, Copy, Debug)]
pub struct Instant {
_marker: (),
}
impl Instant {
pub fn now() -> Self {
Self { _marker: () }
}
pub fn duration_since(&self, _earlier: Instant) -> Duration {
Duration::from_secs(0)
}
pub fn elapsed(&self) -> Duration {
Duration::from_secs(0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_duration_creation() {
let duration = Duration::from_secs(30);
assert_eq!(duration.as_secs(), 30);
assert_eq!(duration.as_millis(), 30000);
assert_eq!(duration.as_secs_f64(), 30.0);
}
#[test]
fn test_duration_from_millis() {
let duration = Duration::from_millis(1500);
assert_eq!(duration.as_secs(), 1);
assert_eq!(duration.as_millis(), 1500);
}
#[test]
fn test_duration_zero() {
let duration = Duration::default();
assert!(duration.is_zero());
let non_zero = Duration::from_secs(1);
assert!(!non_zero.is_zero());
}
#[test]
fn test_duration_ordering() {
let dur1 = Duration::from_secs(10);
let dur2 = Duration::from_secs(20);
assert!(dur1 < dur2);
assert!(dur2 > dur1);
assert_eq!(dur1, dur1);
}
#[test]
fn test_duration_from_u64() {
let duration: Duration = 42u64.into();
assert_eq!(duration.as_secs(), 42);
}
#[test]
fn test_instant_creation() {
let instant = Instant::now();
let duration = instant.elapsed();
assert_eq!(duration.as_secs(), 0); }
#[tokio::test]
async fn test_sleep_functionality() {
let duration = Duration::from_secs(0);
sleep(duration).await; }
}