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
//
// Wildland Project
//
// Copyright © 2023 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
use std::time::SystemTime;
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
pub struct UnixTimestamp {
    /// Number of seconds that elapsed since the beginning of the UNIX epoch
    pub sec: u64,
    /// fraction of a second expressed in nanoseconds
    pub nano_sec: u32,
}
/// Getter exposed through ffi
impl UnixTimestamp {
    pub fn sec(&self) -> u64 {
        self.sec
    }
    pub fn nano_sec(&self) -> u32 {
        self.nano_sec
    }
    pub fn now() -> UnixTimestamp {
        SystemTime::now().into()
    }
    pub fn from_nanos(nanos: u64) -> UnixTimestamp {
        UnixTimestamp {
            sec: nanos / 1_000_000_000,
            nano_sec: (nanos % 1_000_000_000) as u32,
        }
    }
}
impl From<SystemTime> for UnixTimestamp {
    fn from(value: SystemTime) -> Self {
        value
            .duration_since(SystemTime::UNIX_EPOCH)
            .map(|duration| Self {
                sec: duration.as_secs(),
                nano_sec: duration.subsec_nanos(),
            })
            .unwrap()
    }
}
#[cfg(test)]
mod tests {
    use super::UnixTimestamp;
    #[test]
    fn test_unix_timestamp_from_nanos() {
        let nanos = 123_456_789_123;
        let ut = UnixTimestamp::from_nanos(nanos);
        assert_eq!(
            ut,
            UnixTimestamp {
                sec: 123,
                nano_sec: 456_789_123
            }
        )
    }
}