bolt_proto/value/
duration.rs

1use bolt_proto_derive::*;
2
3use crate::value::SIGNATURE_DURATION;
4
5#[bolt_structure(SIGNATURE_DURATION)]
6#[derive(Debug, Clone, Hash, Eq, PartialEq)]
7pub struct Duration {
8    pub(crate) months: i64,
9    pub(crate) days: i64,
10    pub(crate) seconds: i64,
11    pub(crate) nanos: i32,
12}
13
14impl Duration {
15    pub fn new(months: i64, days: i64, seconds: i64, nanos: i32) -> Self {
16        Self {
17            months,
18            days,
19            seconds,
20            nanos,
21        }
22    }
23
24    pub fn months(&self) -> i64 {
25        self.months
26    }
27
28    pub fn days(&self) -> i64 {
29        self.days
30    }
31
32    pub fn seconds(&self) -> i64 {
33        self.seconds
34    }
35
36    pub fn nanos(&self) -> i32 {
37        self.nanos
38    }
39}
40
41impl From<std::time::Duration> for Duration {
42    fn from(duration: std::time::Duration) -> Self {
43        // This fits in an i64 because u64::MAX / (3600 * 24) < i64::MAX
44        let days = (duration.as_secs() / (3600 * 24)) as i64;
45        // This fits in an i64 since it will be less than 3600 * 24
46        let seconds = (duration.as_secs() % (3600 * 24)) as i64;
47        // This fits in an i32 because 0 <= nanos < 1e9 which is less than i32::MAX
48        let nanos = duration.subsec_nanos() as i32;
49
50        // Months are not well-defined in terms of seconds so let's not use them here
51        Self {
52            months: 0,
53            days,
54            seconds,
55            nanos,
56        }
57    }
58}