aboutsummaryrefslogtreecommitdiffstats
path: root/src/time.rs
diff options
context:
space:
mode:
authorJake McGinty <me@jake.su>2018-02-23 15:45:44 +0000
committerJake McGinty <me@jake.su>2018-02-23 15:45:44 +0000
commit7be7fa67518a5f04bc900b57cb2303c650611757 (patch)
tree2016549c588f99eb9585fcce1badde8f094a4ae4 /src/time.rs
parentuse std::time instead of time crate (diff)
downloadwireguard-rs-7be7fa67518a5f04bc900b57cb2303c650611757.tar.xz
wireguard-rs-7be7fa67518a5f04bc900b57cb2303c650611757.zip
refactor timestamp code a bit
Diffstat (limited to 'src/time.rs')
-rw-r--r--src/time.rs78
1 files changed, 78 insertions, 0 deletions
diff --git a/src/time.rs b/src/time.rs
new file mode 100644
index 0000000..6261573
--- /dev/null
+++ b/src/time.rs
@@ -0,0 +1,78 @@
+use byteorder::{ByteOrder, BigEndian};
+use std::ops::Deref;
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+use std::u64;
+
+const TAI64N_BASE: i64 = 4611686018427387914;
+
+#[derive(PartialEq, PartialOrd)]
+pub struct Tai64n {
+ tai64n: [u8; 12]
+}
+
+impl Tai64n {
+ pub fn now() -> Tai64n {
+ let mut tai64n = [0u8; 12];
+ let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
+ BigEndian::write_i64(&mut tai64n[0..], TAI64N_BASE + now.as_secs() as i64);
+ BigEndian::write_i32(&mut tai64n[8..], now.subsec_nanos() as i32);
+
+ Tai64n { tai64n }
+ }
+}
+
+impl Deref for Tai64n {
+ type Target = [u8; 12];
+
+ fn deref(&self) -> &[u8; 12] {
+ &self.tai64n
+ }
+}
+
+impl From<[u8; 12]> for Tai64n {
+ fn from(tai64n: [u8; 12]) -> Self {
+ Tai64n { tai64n }
+ }
+}
+
+lazy_static! {
+ pub static ref FOREVER: Duration = Duration::from_secs(u64::MAX);
+ pub static ref FOREVER_AGO: Instant = Instant::now() - *FOREVER;
+}
+
+pub struct Timestamp(Option<Instant>);
+
+impl Default for Timestamp {
+ fn default() -> Self {
+ Timestamp(None)
+ }
+}
+
+impl Deref for Timestamp {
+ type Target = Instant;
+
+ fn deref(&self) -> &Self::Target {
+ match self.0 {
+ Some(ref time) => time,
+ None => &*FOREVER_AGO,
+ }
+ }
+}
+
+impl Timestamp {
+ pub fn now() -> Self {
+ Timestamp(Some(Instant::now()))
+ }
+
+ pub fn unset() -> Self {
+ Timestamp(None)
+ }
+
+ pub fn is_set(&self) -> bool {
+ self.0.is_some()
+ }
+
+ pub fn elapsed(&self) -> Duration {
+ Instant::now().duration_since(**self)
+ }
+}