structdb/
timestamp.rs

1use serde::{Deserialize, Serialize};
2use std::collections::hash_map::DefaultHasher;
3use std::hash::{Hash, Hasher};
4use std::time::{SystemTime, UNIX_EPOCH};
5
6pub fn epoch_ns() -> u128 {
7    match SystemTime::now().duration_since(UNIX_EPOCH) {
8        Ok(time) => time.as_nanos(),
9        Err(_) => panic!("Unable to determine time."),
10    }
11}
12
13pub fn epoch_secs() -> u64 {
14    match SystemTime::now().duration_since(UNIX_EPOCH) {
15        Ok(time) => time.as_secs(),
16        Err(_) => panic!("Unable to determine time."),
17    }
18}
19
20#[derive(Serialize, Deserialize, Debug, Clone, Hash, PartialEq, Eq)]
21pub struct Timestamp {
22    pub created_at: u64,
23    pub updated_at: u64,
24}
25
26impl Timestamp {
27    pub fn new() -> Self {
28        Self {
29            created_at: epoch_secs(),
30            updated_at: epoch_secs(),
31        }
32    }
33
34    pub fn hash(&self, name: &str) -> u64 {
35        let mut hasher = DefaultHasher::new();
36
37        let unique = (name, self.created_at);
38        unique.hash(&mut hasher);
39
40        hasher.finish()
41    }
42
43    pub fn update_now(&mut self) {
44        self.updated_at = epoch_secs();
45    }
46}
47
48impl Default for Timestamp {
49    fn default() -> Self {
50        Self::new()
51    }
52}