snowflake_ng/
provider.rs

1// Copyright 2024 Krysztal Huang
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use std::time::UNIX_EPOCH;
9
10use crate::TimeProvider;
11
12/// [std::time::SystemTime] based [TimeProvider]
13pub static STD_PROVIDER: StdProvider = StdProvider;
14
15#[cfg(feature = "chrono")]
16/// [chrono::Local] based [TimeProvider]
17pub static CHRONO_PROVIDER: ChronoProvider = ChronoProvider;
18
19#[cfg(feature = "time")]
20/// [time::OffsetDateTime] based [TimeProvider]
21pub static TIME_CRATE_PROVIDER: TimeCrateProvider = TimeCrateProvider;
22
23#[derive(Debug)]
24pub struct StdProvider;
25
26impl TimeProvider for StdProvider {
27    fn timestamp(&self) -> u64 {
28        std::time::SystemTime::now()
29            .duration_since(UNIX_EPOCH)
30            .unwrap()
31            .as_millis() as u64
32    }
33}
34unsafe impl Sync for StdProvider {}
35unsafe impl Send for StdProvider {}
36
37#[cfg(feature = "chrono")]
38#[derive(Debug)]
39pub struct ChronoProvider;
40
41#[cfg(feature = "chrono")]
42impl TimeProvider for ChronoProvider {
43    fn timestamp(&self) -> u64 {
44        chrono::Local::now().timestamp_millis() as u64
45    }
46}
47
48#[cfg(feature = "chrono")]
49unsafe impl Sync for ChronoProvider {}
50#[cfg(feature = "chrono")]
51unsafe impl Send for ChronoProvider {}
52
53#[cfg(feature = "time")]
54#[derive(Debug)]
55pub struct TimeCrateProvider;
56
57#[cfg(feature = "time")]
58impl TimeProvider for TimeCrateProvider {
59    fn timestamp(&self) -> u64 {
60        (time::OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000) as u64
61    }
62}
63
64#[cfg(feature = "time")]
65unsafe impl Sync for TimeCrateProvider {}
66#[cfg(feature = "time")]
67unsafe impl Send for TimeCrateProvider {}