use core::{fmt, ops};
#[cfg(feature = "serde-support")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "coarsetime-support")]
use coarsetime::Clock;
#[cfg(feature = "coarsetime-support")]
pub fn coarsetime_update() {
coarsetime::Clock::update();
}
#[cfg(feature = "coarsetime-support")]
pub fn coarsetime_init_updater() {
coarsetime::Updater::new(1).start().expect("Failed to start coarsetime updater");
}
#[repr(transparent)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
pub struct Timestamp(u64);
impl fmt::Display for Timestamp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
chrono::DateTime::<chrono::Utc>::from(*self).fmt(f)
}
}
impl fmt::Debug for Timestamp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Timestamp({})", self.0)
}
}
impl From<chrono::DateTime<chrono::Utc>> for Timestamp {
fn from(other: chrono::DateTime<chrono::Utc>) -> Self {
let nanos = other.timestamp_nanos_opt().unwrap_or(0);
if nanos < 0 {
Self(0) } else {
Self(nanos as u64)
}
}
}
impl From<Timestamp> for chrono::DateTime<chrono::Utc> {
fn from(other: Timestamp) -> Self {
let nanoseconds_u64 = other.0;
let nanos_in_sec: u64 = 1_000_000_000;
let sec_i64: i64 = nanoseconds_u64
.checked_div(nanos_in_sec)
.and_then(|s| s.try_into().ok())
.unwrap_or(i64::MAX);
let ns_u32: u32 = nanoseconds_u64
.checked_rem(nanos_in_sec)
.and_then(|n| n.try_into().ok())
.unwrap_or(0);
chrono::DateTime::<chrono::Utc>::from_timestamp(sec_i64, ns_u32).unwrap_or_else(|| {
chrono::DateTime::<chrono::Utc>::from_timestamp(0, 0).expect("0,0 is a valid timestamp")
})
}
}
impl Timestamp {
#[inline]
pub const fn zero() -> Self {
Timestamp(0)
}
#[cfg(not(feature = "coarsetime-support"))]
pub fn now() -> Self {
let nanos = chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0);
if nanos < 0 {
Self(0)
} else {
Self(nanos as u64)
}
}
#[cfg(feature = "coarsetime-support")]
pub fn now() -> Self {
Self(Clock::recent_since_epoch().as_nanos())
}
#[cfg(not(feature = "coarsetime-support"))]
pub fn fetch_chrono_utc_now() -> chrono::DateTime<chrono::Utc> {
chrono::Utc::now()
}
#[cfg(feature = "coarsetime-support")]
pub fn fetch_chrono_utc_now() -> chrono::DateTime<chrono::Utc> {
let nanos = coarsetime::Clock::recent_since_epoch().as_nanos();
Timestamp(nanos).into()
}
#[inline]
pub const fn from_milliseconds(int: u64) -> Self {
Timestamp(int * 1_000_000)
}
#[inline]
pub const fn from_seconds(int: u64) -> Self {
Timestamp(int * 1_000_000_000)
}
#[inline]
pub fn from_nanoseconds(int: u64) -> Self {
Timestamp(int)
}
#[inline]
pub const fn as_milliseconds(self) -> u64 {
self.0 / 1_000_000
}
#[inline]
pub const fn as_nanoseconds(self) -> u64 {
self.0
}
pub const fn align_to(self, freq: TimeDelta) -> Timestamp {
self.align_to_anchored(Timestamp::zero(), freq)
}
pub const fn align_to_anchored(self, anchor: Timestamp, freq: TimeDelta) -> Timestamp {
let self_i64 = self.0 as i64;
let anchor_i64 = anchor.0 as i64;
let freq_i64 = freq.0;
let aligned_i64 = (self_i64 - anchor_i64) / freq_i64 * freq_i64 + anchor_i64;
Self(if aligned_i64 < 0 { 0 } else { aligned_i64 as u64 }) }
#[inline]
pub const fn is_zero(self) -> bool {
self.0 == 0
}
}
impl ops::Add<TimeDelta> for Timestamp {
type Output = Timestamp;
fn add(self, rhs: TimeDelta) -> Self::Output {
let result_i64 = (self.0 as i64) + rhs.0;
Self(result_i64.max(0) as u64)
}
}
impl ops::AddAssign<TimeDelta> for Timestamp {
fn add_assign(&mut self, rhs: TimeDelta) {
*self = *self + rhs;
}
}
impl ops::Sub<TimeDelta> for Timestamp {
type Output = Timestamp;
fn sub(self, rhs: TimeDelta) -> Self::Output {
let result_i64 = (self.0 as i64) - rhs.0;
Self(result_i64.max(0) as u64)
}
}
impl ops::SubAssign<TimeDelta> for Timestamp {
fn sub_assign(&mut self, rhs: TimeDelta) {
*self = *self - rhs;
}
}
impl ops::Sub<Timestamp> for Timestamp {
type Output = TimeDelta;
fn sub(self, rhs: Timestamp) -> Self::Output {
TimeDelta((self.0 as i64) - (rhs.0 as i64))
}
}
#[repr(transparent)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
pub struct TimeDelta(i64);
impl fmt::Display for TimeDelta {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
chrono::Duration::from(*self).fmt(f)
}
}
impl From<chrono::Duration> for TimeDelta {
fn from(other: chrono::Duration) -> Self {
Self(other.num_nanoseconds().unwrap_or(0))
}
}
impl From<TimeDelta> for chrono::Duration {
fn from(other: TimeDelta) -> Self {
chrono::Duration::nanoseconds(other.0)
}
}
impl ops::Add<TimeDelta> for TimeDelta {
type Output = TimeDelta;
fn add(self, rhs: TimeDelta) -> Self::Output {
TimeDelta(self.0 + rhs.0)
}
}
impl ops::Sub<TimeDelta> for TimeDelta {
type Output = TimeDelta;
fn sub(self, rhs: TimeDelta) -> Self::Output {
TimeDelta(self.0 - rhs.0)
}
}
impl ops::Mul<i64> for TimeDelta {
type Output = TimeDelta;
fn mul(self, rhs: i64) -> Self::Output {
TimeDelta(self.0 * rhs)
}
}
impl ops::Div<i64> for TimeDelta {
type Output = TimeDelta;
fn div(self, rhs: i64) -> Self::Output {
TimeDelta(self.0 / rhs)
}
}
impl ops::Div<TimeDelta> for TimeDelta {
type Output = i64;
fn div(self, rhs: TimeDelta) -> Self::Output {
self.0 / rhs.0
}
}
impl ops::Rem<TimeDelta> for TimeDelta {
type Output = TimeDelta;
fn rem(self, rhs: TimeDelta) -> Self::Output {
TimeDelta(self.0 % rhs.0)
}
}
impl TimeDelta {
#[inline]
pub const fn zero() -> Self {
TimeDelta(0)
}
#[inline]
pub const fn from_hours(int: i64) -> Self {
TimeDelta(int * 60 * 60 * 1_000_000_000)
}
#[inline]
pub const fn from_minutes(int: i64) -> Self {
TimeDelta(int * 60 * 1_000_000_000)
}
#[inline]
pub const fn from_seconds(int: i64) -> Self {
TimeDelta(int * 1_000_000_000)
}
#[inline]
pub const fn from_milliseconds(int: i64) -> Self {
TimeDelta(int * 1_000_000)
}
#[inline]
pub const fn from_nanoseconds(int: i64) -> Self {
TimeDelta(int)
}
#[inline]
pub const fn as_milliseconds(self) -> i64 {
self.0 / 1_000_000
}
#[inline]
pub const fn as_nanoseconds(self) -> i64 {
self.0
}
}
#[derive(Debug)]
pub struct TimeRange {
cur: Timestamp,
end: Timestamp,
step: TimeDelta,
right_closed: bool,
}
impl TimeRange {
pub fn right_closed(
start: impl Into<Timestamp>,
end: impl Into<Timestamp>,
step: impl Into<TimeDelta>,
) -> Self {
TimeRange {
cur: start.into(),
end: end.into(),
step: step.into(),
right_closed: true,
}
}
pub fn right_open(
start: impl Into<Timestamp>,
end: impl Into<Timestamp>,
step: impl Into<TimeDelta>,
) -> Self {
TimeRange {
cur: start.into(),
end: end.into(),
step: step.into(),
right_closed: false,
}
}
}
impl Iterator for TimeRange {
type Item = Timestamp;
fn next(&mut self) -> Option<Self::Item> {
let exhausted = if self.right_closed {
self.cur > self.end
} else {
self.cur >= self.end
};
if exhausted {
None
} else {
let cur = self.cur;
self.cur += self.step;
Some(cur)
}
}
}
#[cfg(test)]
mod tests {
use crate::*;
use chrono::{offset::TimeZone, Duration, Utc};
#[test]
fn open_time_range() {
let start = Utc.with_ymd_and_hms(2019, 4, 14, 0, 0, 0).unwrap();
let end = Utc.with_ymd_and_hms(2019, 4, 16, 0, 0, 0).unwrap();
let step = Duration::hours(12);
let tr: Vec<_> = Iterator::collect(TimeRange::right_closed(start, end, step));
assert_eq!(tr, vec![
Utc.with_ymd_and_hms(2019, 4, 14, 0, 0, 0).unwrap().into(),
Utc.with_ymd_and_hms(2019, 4, 14, 12, 0, 0).unwrap().into(),
Utc.with_ymd_and_hms(2019, 4, 15, 0, 0, 0).unwrap().into(),
Utc.with_ymd_and_hms(2019, 4, 15, 12, 0, 0).unwrap().into(),
Utc.with_ymd_and_hms(2019, 4, 16, 0, 0, 0).unwrap().into(),
]);
}
#[test]
fn timestamp_and_delta_vs_chrono() {
let c_dt = Utc.with_ymd_and_hms(2019, 3, 13, 16, 14, 9).unwrap();
let c_td = Duration::nanoseconds(123456000000);
let my_dt = Timestamp::from(c_dt.clone());
let my_td = TimeDelta::from_nanoseconds(123456000000); assert_eq!(TimeDelta::from(c_td.clone()), my_td);
let c_result = c_dt + c_td * 555;
let my_result = my_dt + my_td * 555;
assert_eq!(Timestamp::from(c_result.clone()), my_result);
}
#[test]
fn timestamp_ord_eq() {
let ts1: Timestamp = Timestamp::from_nanoseconds(111);
let ts2: Timestamp = Timestamp::from_nanoseconds(222);
let ts3: Timestamp = Timestamp::from_nanoseconds(222);
assert!(ts1 < ts2);
assert!(ts2 > ts1);
assert!(ts1 <= ts2);
assert!(ts2 >= ts3);
assert!(ts2 <= ts3);
assert!(ts2 >= ts3);
assert_eq!(ts2, ts3);
assert_ne!(ts1, ts3);
}
#[test]
fn align_to_anchored() {
let day_naive = chrono::NaiveDate::from_ymd_opt(2020, 9, 28).unwrap();
let ts: Timestamp = chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
day_naive.and_hms_opt(19, 32, 51).unwrap(),
chrono::Utc,
).into();
assert_eq!(
ts.align_to_anchored(
chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
day_naive.and_hms_opt(0, 0, 0).unwrap(),
chrono::Utc,
).into(),
TimeDelta::from_seconds(60 * 5)
),
chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
day_naive.and_hms_opt(19, 30, 0).unwrap(),
chrono::Utc,
).into(),
);
assert_eq!(
ts.align_to_anchored(
chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
day_naive.and_hms_opt(9 , 1, 3).unwrap(),
chrono::Utc,
).into(),
TimeDelta::from_seconds(60 * 5)
),
chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
day_naive.and_hms_opt(19, 31, 3).unwrap(),
chrono::Utc,
).into(),
);
}
#[test]
fn align_to_anchored_eq() {
let day_naive = chrono::NaiveDate::from_ymd_opt(2020, 1, 1).unwrap();
let anchor: Timestamp = chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
day_naive.and_hms_opt(0, 0, 0).unwrap(),
chrono::Utc,
).into();
let freq = TimeDelta::from_seconds(5 * 60);
let ts1: Timestamp = chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
day_naive.and_hms_opt(12, 1, 11).unwrap(),
chrono::Utc,
).into();
let ts2: Timestamp = chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
day_naive.and_hms_opt(12, 4, 11).unwrap(),
chrono::Utc,
).into();
assert_eq!(
ts1.align_to_anchored(anchor, freq),
ts2.align_to_anchored(anchor, freq),
);
}
#[cfg(feature = "coarsetime-support")]
#[test]
fn coarsetime_now_test() {
use core::time::Duration;
coarsetime::Clock::update();
let coarsetime_now = Timestamp::now();
std::thread::sleep(Duration::from_millis(10));
let chrono_now = chrono::Utc::now();
let diff = (chrono_now.timestamp_nanos_opt().unwrap_or(0) - (coarsetime_now.as_nanoseconds() as i64)).abs();
assert!(diff < 50_000_000, "Difference was: {}", diff);
}
#[test]
fn test_fetch_chrono_utc_now() {
use chrono::Utc;
#[cfg(feature = "coarsetime-support")]
coarsetime::Clock::update();
let now = Timestamp::fetch_chrono_utc_now();
let chrono_now = Utc::now();
let diff = (chrono_now.timestamp_nanos_opt().unwrap_or(0) - now.timestamp_nanos_opt().unwrap_or(0)).abs();
assert!(diff < 50_000_000, "Difference was: {}", diff);
}
}