Skip to main content

browser_forensic_core/
timestamp.rs

1// crates/browser-forensic-core/src/timestamp.rs
2
3pub use forensicnomicon::heuristics::{CORE_DATA_EPOCH_OFFSET_SECS, WEBKIT_EPOCH_OFFSET_US};
4
5pub fn webkit_micros_to_unix_nanos(webkit_us: i64) -> i64 {
6    (webkit_us - WEBKIT_EPOCH_OFFSET_US) * 1_000
7}
8
9pub fn core_data_secs_to_unix_nanos(core_data_secs: f64) -> i64 {
10    ((core_data_secs as i64) + CORE_DATA_EPOCH_OFFSET_SECS) * 1_000_000_000
11}
12
13pub fn unix_micros_to_nanos(us: i64) -> i64 {
14    us * 1_000
15}
16
17pub fn unix_millis_to_nanos(ms: i64) -> i64 {
18    ms * 1_000_000
19}
20
21pub fn unix_secs_to_nanos(secs: i64) -> i64 {
22    secs * 1_000_000_000
23}
24
25#[cfg(test)]
26mod tests {
27    use super::*;
28
29    #[test]
30    fn webkit_epoch_at_unix_epoch_returns_zero() {
31        // WebKit epoch value that represents 1970-01-01 00:00:00 UTC
32        let webkit_us = WEBKIT_EPOCH_OFFSET_US;
33        assert_eq!(webkit_micros_to_unix_nanos(webkit_us), 0);
34    }
35
36    #[test]
37    fn webkit_one_second_after_unix_epoch() {
38        let webkit_us = WEBKIT_EPOCH_OFFSET_US + 1_000_000;
39        assert_eq!(webkit_micros_to_unix_nanos(webkit_us), 1_000_000_000);
40    }
41
42    #[test]
43    fn core_data_epoch_at_unix_offset_returns_negative_secs() {
44        // 0.0 in Core Data = 2001-01-01 = 978307200 seconds after Unix epoch
45        assert_eq!(
46            core_data_secs_to_unix_nanos(0.0),
47            CORE_DATA_EPOCH_OFFSET_SECS * 1_000_000_000
48        );
49    }
50
51    #[test]
52    fn core_data_one_second_later() {
53        assert_eq!(
54            core_data_secs_to_unix_nanos(1.0),
55            (CORE_DATA_EPOCH_OFFSET_SECS + 1) * 1_000_000_000
56        );
57    }
58
59    #[test]
60    fn unix_micros_to_nanos_multiplies_by_1000() {
61        assert_eq!(unix_micros_to_nanos(1_000_000), 1_000_000_000);
62        assert_eq!(unix_micros_to_nanos(0), 0);
63    }
64
65    #[test]
66    fn unix_millis_to_nanos_multiplies_by_1_000_000() {
67        assert_eq!(unix_millis_to_nanos(1_000), 1_000_000_000);
68    }
69
70    #[test]
71    fn unix_secs_to_nanos_multiplies_by_1_000_000_000() {
72        assert_eq!(unix_secs_to_nanos(1), 1_000_000_000);
73    }
74}