• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

baoyachi / shadow-rs / 7138288028

08 Dec 2023 06:43AM UTC coverage: 23.122% (-1.0%) from 24.1%
7138288028

push

github

web-flow
Merge pull request #144 from baoyachi/wasm_example

add wasm example

594 of 2569 relevant lines covered (23.12%)

0.33 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

15.86
/src/date_time.rs
1
use crate::Format;
2
use std::error::Error;
3
use time::format_description::well_known::{Rfc2822, Rfc3339};
4
#[cfg(feature = "tzdb")]
5
use time::UtcOffset;
6
use time::{format_description, OffsetDateTime};
7

8
pub enum DateTime {
9
    Local(OffsetDateTime),
10
    Utc(OffsetDateTime),
11
}
12

13
pub fn now_date_time() -> DateTime {
1✔
14
    // Enable reproducibility for uses of `now_date_time` by respecting the
15
    // `SOURCE_DATE_EPOCH` env variable.
16
    //
17
    // https://reproducible-builds.org/docs/source-date-epoch/
18
    println!("cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH");
1✔
19
    match std::env::var_os("SOURCE_DATE_EPOCH") {
1✔
20
        None => DateTime::now(),
×
21
        Some(timestamp) => {
1✔
22
            let epoch = timestamp
2✔
23
                .into_string()
24
                .expect("Input SOURCE_DATE_EPOCH could not be parsed")
25
                .parse::<i64>()
26
                .expect("Input SOURCE_DATE_EPOCH could not be cast to a number");
27
            DateTime::Utc(OffsetDateTime::from_unix_timestamp(epoch).unwrap())
1✔
28
        }
29
    }
30
}
31

32
impl Default for DateTime {
33
    fn default() -> Self {
×
34
        Self::now()
×
35
    }
36
}
37

38
impl DateTime {
39
    pub fn now() -> Self {
1✔
40
        Self::local_now().unwrap_or_else(|_| DateTime::Utc(OffsetDateTime::now_utc()))
1✔
41
    }
42

43
    pub fn offset_datetime() -> OffsetDateTime {
×
44
        let date_time = Self::now();
×
45
        match date_time {
×
46
            DateTime::Local(time) | DateTime::Utc(time) => time,
×
47
        }
48
    }
49

50
    #[cfg(not(feature = "tzdb"))]
51
    pub fn local_now() -> Result<Self, Box<dyn Error>> {
×
52
        // Warning: This attempts to create a new OffsetDateTime with the current date and time in the local offset, which may fail.
53
        // Currently, it always fails on MacOS.
54
        // This issue does not exist with the "tzdb" feature (see below), which should be used instead.
55
        OffsetDateTime::now_local()
×
56
            .map(DateTime::Local)
×
57
            .map_err(|e| e.into())
×
58
    }
59

60
    #[cfg(feature = "tzdb")]
61
    pub fn local_now() -> Result<Self, Box<dyn Error>> {
1✔
62
        let local_time = tzdb::now::local()?;
1✔
63
        let time_zone_offset =
2✔
64
            UtcOffset::from_whole_seconds(local_time.local_time_type().ut_offset())?;
×
65
        let local_date_time = OffsetDateTime::from_unix_timestamp(local_time.unix_time())?
2✔
66
            .to_offset(time_zone_offset);
×
67
        Ok(DateTime::Local(local_date_time))
1✔
68
    }
69

70
    pub fn timestamp_2_utc(time_stamp: i64) -> Self {
1✔
71
        let time = OffsetDateTime::from_unix_timestamp(time_stamp).unwrap();
1✔
72
        DateTime::Utc(time)
1✔
73
    }
74

75
    pub fn to_rfc2822(&self) -> String {
1✔
76
        match self {
1✔
77
            DateTime::Local(dt) | DateTime::Utc(dt) => dt.format(&Rfc2822).unwrap(),
1✔
78
        }
79
    }
80

81
    pub fn to_rfc3339(&self) -> String {
1✔
82
        match self {
1✔
83
            DateTime::Local(dt) | DateTime::Utc(dt) => dt.format(&Rfc3339).unwrap(),
1✔
84
        }
85
    }
86
}
87

88
impl Format for DateTime {
89
    fn human_format(&self) -> String {
1✔
90
        match self {
2✔
91
            DateTime::Local(dt) | DateTime::Utc(dt) => dt.human_format(),
2✔
92
        }
93
    }
94
}
95

96
impl Format for OffsetDateTime {
97
    fn human_format(&self) -> String {
1✔
98
        let fmt = format_description::parse(
99
            "[year]-[month]-[day] [hour]:[minute]:[second] [offset_hour \
100
         sign:mandatory]:[offset_minute]",
101
        )
102
        .unwrap();
103
        self.format(&fmt).unwrap()
2✔
104
    }
105
}
106

107
#[cfg(test)]
108
mod tests {
109
    use super::*;
110
    use regex::Regex;
111

112
    #[test]
113
    fn test_source_date_epoch() {
3✔
114
        std::env::set_var("SOURCE_DATE_EPOCH", "1628080443");
115
        let time = now_date_time();
1✔
116
        assert_eq!(time.human_format(), "2021-08-04 12:34:03 +00:00");
1✔
117
    }
118

119
    #[test]
120
    fn test_local_now_human_format() {
4✔
121
        let time = DateTime::local_now().unwrap().human_format();
1✔
122
        #[cfg(unix)]
123
        assert!(!std::fs::read("/etc/localtime").unwrap().is_empty());
2✔
124

125
        let regex = Regex::new(
126
            r"^[0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[+][0-9]{2}:[0-9]{2}",
127
        )
128
        .unwrap();
129
        assert!(regex.is_match(&time));
2✔
130

131
        println!("local now:{time}"); // 2022-07-14 00:40:05 +08:00
1✔
132
        assert_eq!(time.len(), 26);
1✔
133
    }
134

135
    #[test]
136
    fn test_timestamp_2_utc() {
3✔
137
        let time = DateTime::timestamp_2_utc(1628080443);
1✔
138
        assert_eq!(time.to_rfc2822(), "Wed, 04 Aug 2021 12:34:03 +0000");
1✔
139
        assert_eq!(time.to_rfc3339(), "2021-08-04T12:34:03Z");
1✔
140
        assert_eq!(time.human_format(), "2021-08-04 12:34:03 +00:00");
1✔
141
    }
142
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc