1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use chrono::prelude::DateTime;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::fmt;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub type DtnTime = u64;
const SECONDS1970_TO2K: u64 = 946_684_800;
pub const DTN_TIME_EPOCH: DtnTime = 0;
pub trait DtnTimeHelpers {
fn unix(self) -> u64;
fn string(self) -> String;
}
impl DtnTimeHelpers for DtnTime {
fn unix(self) -> u64 {
self + SECONDS1970_TO2K
}
fn string(self) -> String {
let d = UNIX_EPOCH + Duration::from_secs(self + SECONDS1970_TO2K);
let datetime = DateTime::<Utc>::from(d);
datetime.to_rfc3339()
}
}
pub fn dtn_time_now() -> DtnTime {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards!!")
.as_secs()
- SECONDS1970_TO2K
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
pub struct CreationTimestamp(DtnTime, u64);
impl fmt::Display for CreationTimestamp {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", self.0.string(), self.1)
}
}
impl CreationTimestamp {
pub fn new() -> CreationTimestamp {
Default::default()
}
pub fn with_time_and_seq(t: DtnTime, seqno: u64) -> CreationTimestamp {
CreationTimestamp(t, seqno)
}
pub fn get_seqno(&self) -> u64 {
self.1
}
pub fn get_dtntime(&self) -> DtnTime {
self.0
}
pub fn now() -> CreationTimestamp {
let now = dtn_time_now();
if now != LAST_CREATION_TIMESTAMP.swap(now as usize, Ordering::Relaxed) as u64 {
LAST_CREATION_SEQ.store(0, Ordering::SeqCst)
}
let seq = LAST_CREATION_SEQ.fetch_add(1, Ordering::SeqCst);
CreationTimestamp::with_time_and_seq(now, seq as u64)
}
}
static LAST_CREATION_TIMESTAMP: AtomicUsize = AtomicUsize::new(0);
static LAST_CREATION_SEQ: AtomicUsize = AtomicUsize::new(0);