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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// License: see LICENSE file at root directory of `master` branch

//! # Command line duration

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

use crate::Error;

/// # 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;

const NANOSECOND_UNIT: &str = concat!('n', 's');
const MICROSECOND_UNIT: &str = concat!('m', 'c');
const MILLISECOND_UNIT: &str = concat!('m', 's');
const SECOND_UNIT: &str = concat!('s');
const MINUTE_UNIT: &str = concat!('m');
const HOUR_UNIT: &str = concat!('h');
const DAY_UNIT: &str = concat!('d');
const WEEK_UNIT: &str = concat!('w');

#[test]
fn test_constants() {
    assert_eq!(MINUTE, 60);
    assert_eq!(HOUR, 60 * 60);
    assert_eq!(DAY, 24 * 60 * 60);
    assert_eq!(WEEK, 7 * 24 * 60 * 60);

    assert_eq!(NANOSECOND_UNIT, "ns");
    assert_eq!(MICROSECOND_UNIT, "mc");
    assert_eq!(MILLISECOND_UNIT, "ms");
    assert_eq!(SECOND_UNIT, "s");
    assert_eq!(MINUTE_UNIT, "m");
    assert_eq!(HOUR_UNIT, "h");
    assert_eq!(DAY_UNIT, "d");
    assert_eq!(WEEK_UNIT, "w");
}

/// # Command line duration
///
/// # Notes
///
/// - [`Display`][core::fmt/Display] implementation is only for human presentation. The result should ***not*** be parsed.
///
/// - Supported units for parsing from strings:
///
///   | 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").unwrap(), Duration::from_secs(9));
/// assert_eq!(ClDuration::from_str("2d").unwrap(), Duration::from_secs(60 * 60 * 24 * 2));
/// ```
///
/// [core::fmt/Display]: https://doc.rust-lang.org/core/fmt/trait.Display.html
#[derive(Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct ClDuration {
    duration: Duration,
}

impl ClDuration {

    /// # Makes new instance
    pub const fn new(duration: Duration) -> Self {
        Self {
            duration,
        }
    }

}

impl From<ClDuration> for Duration {

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

}

impl From<Duration> for ClDuration {

    fn from(duration: Duration) -> Self {
        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),
            _ => {
                let days = format!("{d}{unit}", d=d, unit=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> {
        let (number, unit) = match s.chars().position(|c| c < '0' || c > '9') {
            Some(pos) => (&s[..pos], &s[pos..]),
            None => return Err(e!("Missing unit")),
        };

        let number = u64::from_str(number).map_err(|_| e!("Invalid duration: {}", s))?;

        let factor = match unit {
            SECOND_UNIT => 1,
            MINUTE_UNIT => MINUTE,
            HOUR_UNIT => HOUR,
            DAY_UNIT => DAY,
            WEEK_UNIT => WEEK,
            _ => {
                let f = match unit {
                    NANOSECOND_UNIT => Duration::from_nanos,
                    MICROSECOND_UNIT => Duration::from_micros,
                    MILLISECOND_UNIT => Duration::from_millis,
                    _ => return Err(e!("Invalid duration unit: {}", unit)),
                };
                return Ok(Self {
                    duration: f(number),
                });
            },
        };
        return Ok(Self {
            duration: Duration::from_secs(number.checked_mul(factor).ok_or_else(|| e!("Invalid duration: {}", 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)
    }

}

#[test]
fn test_from_str_of_duration() -> crate::Result<()> {
    assert_eq!(ClDuration::from_str("2s")?, Duration::from_secs(2));

    assert_eq!(ClDuration::from_str("3ns")?, Duration::from_nanos(3));
    assert_eq!(ClDuration::from_str("4mc")?, Duration::from_micros(4));
    assert_eq!(ClDuration::from_str("5ms")?, Duration::from_millis(5));

    assert_eq!(ClDuration::from_str("6m")?, Duration::from_secs(MINUTE * 6));
    assert_eq!(ClDuration::from_str("7h")?, Duration::from_secs(HOUR * 7));
    assert_eq!(ClDuration::from_str("8d")?, Duration::from_secs(DAY * 8));
    assert_eq!(ClDuration::from_str("9w")?, Duration::from_secs(WEEK * 9));

    [concat!(), concat!('s'), "0", "1s", "2ns", "3mc", "4ms", "5m", "6h", "7d", "8w"].iter().for_each(|s|
        assert!(ClDuration::from_str(&s.to_uppercase()).is_err())
    );

    Ok(())
}

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

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

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

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

#[test]
fn test_from_x() {
    assert_eq!(from_nanos(1), Duration::from_nanos(1));
    assert_eq!(from_micros(2), Duration::from_micros(2));
    assert_eq!(from_millis(3), Duration::from_millis(3));
    assert_eq!(from_secs(4), Duration::from_secs(4));
}