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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/*
==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--

CLD

Copyright (C) 2019-2023  Anonymous

There are several releases over multiple years,
they are listed as ranges, such as: "2019-2023".

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

This program 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 Lesser General Public License for more details.

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

::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
*/

//! # Command line duration

use {
    core::{
        cmp::Ordering,
        fmt::{self, Display, Formatter},
        ops::Deref,
        str::FromStr,
        time::Duration,
    },
    crate::Error,
};

mod parser;

/// # One minute in seconds
pub const MINUTE: u64 = 60;

/// # An hour in seconds
pub const HOUR: u64 = 60 * MINUTE;

/// # One day in seconds
pub const DAY: u64 = 24 * HOUR;

/// # One week in seconds
pub const WEEK: u64 = 7 * DAY;

/// # Command line duration
///
/// ## Notes
///
/// - [`Display`][trait:Display] implementation is only for human presentation. The result should ***not*** be parsed.
///
/// - Support 2 forms for parsing from strings:
///
///     + With unit.
///     + `hour:minute:second`.
///
///     Length of the string must be equal to or smaller than 64 bytes. It's for protection against flood attack.
///
/// ## Units
///
/// | Unit | Description |
/// |-----:|------------- |
/// | `ns` | Nanosecond |
/// | `mc` | Microsecond |
/// | `ms` | Millisecond |
/// | `s`  | Second |
/// | `m`  | Minute |
/// | `h`  | Hour |
/// | `d`  | Day |
/// | `w`  | Week |
///
/// # Examples
///
/// ```rust
/// use core::{
///     str::FromStr,
///     time::Duration,
/// };
///
/// use cld::ClDuration;
///
/// assert_eq!(ClDuration::from_str("9s")?, Duration::from_secs(9));
/// assert_eq!(ClDuration::from_str("2d")?, Duration::from_secs(60 * 60 * 24 * 2));
///
/// assert_eq!(
///     ClDuration::from_str("99:59:59")?,
///     Duration::from_secs((99 * 60 * 60) + (59 * 60) + 59),
/// );
///
/// # Ok::<_, cld::Error>(())
/// ```
///
/// [trait:Display]: https://doc.rust-lang.org/core/fmt/trait.Display.html
#[derive(Debug, Eq, PartialEq, Hash, Ord, PartialOrd, Clone, Copy)]
pub struct ClDuration {
    duration: Duration,
}

impl From<ClDuration> for Duration {

    fn from(cld: ClDuration) -> Self {
        cld.duration
    }

}

impl From<Duration> for ClDuration {

    fn from(duration: Duration) -> Self {
        new(duration)
    }

}

impl Display for ClDuration {

    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        let (d, h, m, s) = duration_to_dhms(&self.duration);
        let hms = format!("{h:02}:{m:02}:{s:02}", h=h, m=m, s=s);
        match d {
            0 => {
                f.write_str(&hms)?;
                if h == 0 && m == 0 && s == 0 {
                    let subsec_millis = self.duration.subsec_millis();
                    if subsec_millis > 0 {
                        write!(f, ".{:03}", subsec_millis)?;
                    }
                }
                Ok(())
            },
            _ => {
                let days = format!("{d}{unit}", d=d, unit=parser::DAY_UNIT);
                match (h, m, s) {
                    (0, 0, 0) => f.write_str(&days),
                    _ => write!(f, "{days}, {hms}", days=days, hms=hms),
                }
            },
        }
    }

}

/// # Converts duration to days, hours, minutes, seconds.
fn duration_to_dhms(duration: &Duration) -> (u64, u64, u64, u64) {
    let seconds = duration.as_secs();
    let (minutes, seconds) = {
        let minutes = seconds / 60;
        (minutes, seconds - minutes * 60)
    };
    let (hours, minutes) = {
        let hours = minutes / 60;
        (hours, minutes - hours * 60)
    };
    let (days, hours) = {
        let days = hours / 24;
        (days, hours - days * 24)
    };

    (days, hours, minutes, seconds)
}

impl FromStr for ClDuration {

    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        const MAX_LEN: usize = 64;

        if s.len() > MAX_LEN {
            return Err(err!("String is too long, max length supported: {} bytes", MAX_LEN));
        }

        let s = s.trim();
        if s.contains(parser::HH_MM_SS_SEPARATOR) {
            parser::parse_hh_mm_ss_form(s)
        } else {
            parser::parse_unit_form(s)
        }
    }

}

impl PartialEq<ClDuration> for Duration {

    fn eq(&self, cld: &ClDuration) -> bool {
        self == &cld.duration
    }

}

impl PartialEq<Duration> for ClDuration {

    fn eq(&self, duration: &Duration) -> bool {
        &self.duration == duration
    }

}

impl Deref for ClDuration {

    type Target = Duration;

    fn deref(&self) -> &Self::Target {
        &self.duration
    }

}

impl PartialOrd<Duration> for ClDuration {

    fn partial_cmp(&self, duration: &Duration) -> Option<Ordering> {
        self.duration.partial_cmp(duration)
    }

}

impl PartialOrd<ClDuration> for Duration {

    fn partial_cmp(&self, cld: &ClDuration) -> Option<Ordering> {
        self.partial_cmp(&cld.duration)
    }

}

/// # Makes new duration from [`Duration`][struct:core/time/Duration]
///
/// [struct:core/time/Duration]: https://doc.rust-lang.org/core/time/struct.Duration.html
pub const fn new(duration: Duration) -> ClDuration {
    ClDuration {
        duration,
    }
}

/// # Makes new duration from nanoseconds
pub const fn from_nanos(nanos: u64) -> ClDuration {
    new(Duration::from_nanos(nanos))
}

/// # Makes new duration from microseconds
pub const fn from_micros(micros: u64) -> ClDuration {
    new(Duration::from_micros(micros))
}

/// # Makes new duration from milliseconds
pub const fn from_millis(millis: u64) -> ClDuration {
    new(Duration::from_millis(millis))
}

/// # Makes new duration from seconds
pub const fn from_secs(secs: u64) -> ClDuration {
    new(Duration::from_secs(secs))
}