1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/*<LICENSE>
    This file is part of Memthol.

    Copyright (C) 2020 OCamlPro.

    Memthol is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Memthol is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Memthol.  If not, see <https://www.gnu.org/licenses/>.
*/

//! Generic stuff over durations.

prelude! { time::* }

/// Adds functionalities to the [`Duration`] type.
///
/// [`Duration`]: std::time::Duration
/// (Duration on Rust std)
pub trait DurationExt: From<Duration> {
    /// Retrieves the duration from `Self`.
    fn as_duration(&self) -> &Duration;

    /// Retrieves the chrono duration from `Self`.
    fn to_chrono_duration(&self) -> chrono::Duration {
        let duration = *self.as_duration();
        chrono::Duration::from_std(duration)
            .expect("error while converting duration from std to a chrono duration")
    }

    /// Creates a duration from a timestamp in microseconds.
    fn from_micros(ts: u64) -> Self {
        let secs = ts / 1_000_000;
        let micros = ts - (secs * 1_000_000);
        std::time::Duration::new(secs, convert(micros, "duration_from_micros: micros")).into()
    }

    /// Duration parser from an amount of seconds, seen as a float.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use base::prelude::time::{Duration, DurationExt};
    /// let s_list = vec![
    ///     ("320.74", Duration::new(320, 740_000_000)),
    ///     ("703470.0074", Duration::new(703470, 7_400_000)),
    ///     ("0.2", Duration::new(0, 200_000_000)),
    ///     ("7.0", Duration::new(7, 0)),
    ///     (".003", Duration::new(0, 3_000_000)),
    ///     ("42", Duration::new(42, 0)),
    /// ];
    /// for (s, exp) in s_list {
    ///     let duration = Duration::parse_secs(s).unwrap();
    ///     assert_eq! { duration, exp }
    /// }
    /// ```
    fn parse_secs<Str>(ts: &Str) -> Res<Self>
    where
        Str: ?Sized + AsRef<str>,
    {
        let ts = ts.as_ref();
        let mut subs = ts.split('.');

        macro_rules! err {
            (bail $($stuff:tt)*) => {
                return Err(err!(chain crate::err::Error::from(
                    format!($($stuff)*)
                )))
            };
            (try $e:expr) => {
                err!(chain $e)?
            };
            (chain $e:expr) => {
                $e.chain_err(|| format!("while parsing `{}` as an amount of seconds (float)", ts))
            }
        }

        let duration = match (subs.next(), subs.next()) {
            (Some(secs_str), None) => {
                let secs = err! { try u64::from_str(secs_str) };
                Duration::new(secs, 0)
            }

            (Some(secs_str), Some(mut subsecs_str)) => {
                let original_subsecs_str_len = subsecs_str.len();
                while subsecs_str.len() > 1 {
                    if &subsecs_str[0..1] == "0" {
                        subsecs_str = &subsecs_str[1..]
                    } else {
                        break;
                    }
                }

                let secs = if secs_str.is_empty() {
                    0
                } else {
                    err! { try u64::from_str(secs_str) }
                };

                let nanos = if subsecs_str.is_empty() && !secs_str.is_empty() {
                    0
                } else {
                    let raw = err! { try u32::from_str(subsecs_str) };

                    if original_subsecs_str_len < 9 {
                        raw * 10u32.pow(9 - (original_subsecs_str_len as u32))
                    } else if original_subsecs_str_len == 9 {
                        raw
                    } else {
                        err!(bail
                            "illegal sub-second decimal: \
                            precision above nanoseconds is not supported"
                        )
                    }
                };
                Duration::new(secs, nanos)
            }
            (None, _) => unreachable!("`str::split` never returns an empty iterator"),
        };

        if subs.next().is_some() {
            err!(bail "found more than one `.` character")
        }

        Ok(duration.into())
    }

    /// Pretty displayable version of a duration, millisecond precision.
    fn display_millis<'me>(&'me self) -> DurationDisplay<'me, Self, Millis> {
        self.into()
    }
    /// Pretty displayable version of a duration, microsecond precision.
    fn display_micros<'me>(&'me self) -> DurationDisplay<'me, Self, Micros> {
        self.into()
    }
    /// Pretty displayable version of a duration, nanosecond precision.
    fn display_nanos<'me>(&'me self) -> DurationDisplay<'me, Self, Nanos> {
        self.into()
    }
}

impl DurationExt for Duration {
    fn as_duration(&self) -> &Self {
        self
    }
}

/// Trait implemented by unit-structs representing time precision.
pub trait TimePrecision {
    /// Formats a duration with a given precision.
    fn duration_fmt(duration: &Duration, fmt: &mut fmt::Formatter) -> fmt::Result;
}

/// Nanosecond precision.
pub struct Nanos;
impl TimePrecision for Nanos {
    fn duration_fmt(duration: &Duration, fmt: &mut fmt::Formatter) -> fmt::Result {
        let duration = duration.as_duration();
        write!(
            fmt,
            "{}.{:0>9}",
            duration.as_secs(),
            duration.subsec_nanos()
        )
    }
}

/// Microsecond precision.
pub struct Micros;
impl TimePrecision for Micros {
    fn duration_fmt(duration: &Duration, fmt: &mut fmt::Formatter) -> fmt::Result {
        let duration = duration.as_duration();
        write!(
            fmt,
            "{}.{:0>6}",
            duration.as_secs(),
            duration.subsec_micros()
        )
    }
}

/// Millisecond precision
pub struct Millis;
impl TimePrecision for Millis {
    fn duration_fmt(duration: &Duration, fmt: &mut fmt::Formatter) -> fmt::Result {
        let duration = duration.as_duration();
        write!(
            fmt,
            "{}.{:0>3}",
            duration.as_secs(),
            duration.subsec_millis()
        )
    }
}

/// Thin wrapper around a reference to a duration.
pub struct DurationDisplay<'a, T: DurationExt + ?Sized, Precision: TimePrecision> {
    /// The actual duration.
    duration: &'a T,
    /// Phantom data for the precision.
    _phantom: std::marker::PhantomData<Precision>,
}

impl<'a, T: DurationExt + ?Sized> From<&'a T> for DurationDisplay<'a, T, Nanos> {
    fn from(duration: &'a T) -> Self {
        Self {
            duration,
            _phantom: std::marker::PhantomData,
        }
    }
}
impl<'a, T: DurationExt + ?Sized> From<&'a T> for DurationDisplay<'a, T, Micros> {
    fn from(duration: &'a T) -> Self {
        Self {
            duration,
            _phantom: std::marker::PhantomData,
        }
    }
}
impl<'a, T: DurationExt + ?Sized> From<&'a T> for DurationDisplay<'a, T, Millis> {
    fn from(duration: &'a T) -> Self {
        Self {
            duration,
            _phantom: std::marker::PhantomData,
        }
    }
}
impl<T: DurationExt, Precision: TimePrecision> fmt::Display for DurationDisplay<'_, T, Precision> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        Precision::duration_fmt(self.duration.as_duration(), fmt)
    }
}