use sp_core::offchain::Timestamp;
use std::time::{Duration, SystemTime};
pub fn now() -> Timestamp {
let now = SystemTime::now();
let epoch_duration = now.duration_since(SystemTime::UNIX_EPOCH);
match epoch_duration {
Err(_) => {
Timestamp::from_unix_millis(0)
},
Ok(d) => {
let duration = d.as_millis();
Timestamp::from_unix_millis(
duration
.try_into()
.expect("epoch milliseconds won't overflow u64 for hundreds of years; qed"),
)
},
}
}
pub fn timestamp_from_now(timestamp: Timestamp) -> Duration {
Duration::from_millis(timestamp.diff(&now()).millis())
}
pub fn deadline_to_future(
deadline: Option<Timestamp>,
) -> futures::future::MaybeDone<impl futures::Future<Output = ()>> {
use futures::future::{self, Either};
future::maybe_done(match deadline.map(timestamp_from_now) {
None => Either::Left(future::pending()),
Some(duration) if duration <= Duration::from_secs(0) => {
Either::Right(Either::Left(future::ready(())))
},
Some(duration) => Either::Right(Either::Right(futures_timer::Delay::new(duration))),
})
}