pdk-classy 1.9.1-alpha.2

PDK Classy
Documentation
use crate::proxy_wasm::hostcalls;
use std::time::{SystemTime, UNIX_EPOCH};

const SECS_IN_MIN: u64 = 60;
const SECS_IN_HOUR: u64 = 3600;

pub enum TimeUnit {
    Hours,
    Minutes,
    Seconds,
    Milliseconds,
    Nanoseconds,
}

pub trait Clock {
    /// Returns current system time.
    fn get_current_time(&self) -> SystemTime;

    fn get_current_time_unit(&self, unit: TimeUnit) -> u128 {
        let current_time = self.get_current_time().duration_since(UNIX_EPOCH).unwrap();
        match unit {
            TimeUnit::Hours => (current_time.as_secs() / SECS_IN_HOUR) as u128,
            TimeUnit::Minutes => (current_time.as_secs() / SECS_IN_MIN) as u128,
            TimeUnit::Seconds => (current_time.as_secs()) as u128,
            TimeUnit::Milliseconds => current_time.as_millis(),
            TimeUnit::Nanoseconds => current_time.as_nanos(),
        }
    }
}

pub struct DefaultClock;

impl Clock for DefaultClock {
    fn get_current_time(&self) -> SystemTime {
        // Unable to use unwrap_or_default!() because
        // SystemTime does not implement Default
        hostcalls::get_current_time().expect("Current time")
    }
}