alpm_types/date.rs
1use time::OffsetDateTime;
2
3/// A build date in seconds since the epoch
4///
5/// This is a type alias for [`i64`].
6///
7/// # Examples
8/// ```
9/// use std::{num::IntErrorKind, str::FromStr};
10///
11/// use alpm_types::{BuildDate, Error, FromOffsetDateTime};
12/// use time::OffsetDateTime;
13///
14/// # fn main() -> testresult::TestResult {
15/// // create BuildDate from OffsetDateTime
16/// let datetime = BuildDate::from_offset_datetime(OffsetDateTime::from_unix_timestamp(1)?);
17/// assert_eq!(1, datetime);
18///
19/// // create BuildDate from &str
20/// assert_eq!(BuildDate::from_str("1"), Ok(1));
21/// assert!(BuildDate::from_str("foo").is_err());
22/// # Ok(())
23/// # }
24/// ```
25pub type BuildDate = i64;
26
27/// A trait for allowing conversion from an [`OffsetDateTime`] to a type.
28pub trait FromOffsetDateTime {
29 /// Converts an [`OffsetDateTime`] into a type.
30 fn from_offset_datetime(input: OffsetDateTime) -> Self;
31}
32
33impl FromOffsetDateTime for BuildDate {
34 /// Converts a [`OffsetDateTime`] into a [`BuildDate`].
35 ///
36 /// Uses the unix timestamp of the [`OffsetDateTime`].
37 fn from_offset_datetime(input: OffsetDateTime) -> Self {
38 input.unix_timestamp()
39 }
40}
41
42#[cfg(test)]
43mod tests {
44 use rstest::rstest;
45 use testresult::TestResult;
46
47 use super::*;
48
49 #[rstest]
50 fn datetime_into_builddate() -> TestResult {
51 let builddate = 1;
52 let offset_datetime = OffsetDateTime::from_unix_timestamp(1)?;
53 let datetime: BuildDate = BuildDate::from_offset_datetime(offset_datetime);
54 assert_eq!(builddate, datetime);
55
56 Ok(())
57 }
58}