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
use std::time::Duration;

use itertools::{Itertools, PeekingNext};
use thiserror::Error;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Error)]
pub enum DurationParseError {
    #[error("Missing number for suffix {0}")]
    MissingIntegral(String),
    #[error("Duplicate suffix")]
    DoubleSuffix,
    #[error("Duplicate number without identifier")]
    DoubleIntegral,
    #[error("Malformed integral")]
    MalformedIntegral(String),
    #[error("Malformed suffix")]
    MalformedSuffix(String),
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DurationScale {
    Milliseconds,
    Seconds,
    Minutes,
    Hours,
}

impl DurationScale {
    pub fn to_duration(&self, time: f64) -> Duration {
        let scale = match self {
            DurationScale::Milliseconds => 1e-3,
            DurationScale::Seconds => 1.0,
            DurationScale::Minutes => 60.0,
            DurationScale::Hours => 3600.0,
        };

        Duration::from_secs_f64(time * scale)
    }

    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "ms" | "millis" | "millisecond" | "milliseconds" => Some(Self::Milliseconds),
            "s" | "sec" | "second" | "seconds" => Some(Self::Seconds),
            "m" | "min" | "minute" | "minutes" => Some(Self::Minutes),
            "h" | "hour" | "hours" => Some(Self::Hours),
            _ => None,
        }
    }
}

/// Parses a duration in the format of `45` or `45s 1m`. Is overly relaxed and
/// will ignore spaces and mispellings.
pub fn parse_duration(mut s: &str) -> Result<Duration, DurationParseError> {
    let mut num: Option<f64> = None;

    let mut dur = Duration::ZERO;
    while let Some((kind, head, tail)) = tok(s) {
        match (kind, num) {
            (TokenKind::Integral, None) => {
                num = Some(
                    head.parse()
                        .map_err(|_| DurationParseError::MalformedIntegral(head.to_string()))?,
                )
            }
            (TokenKind::Integral, Some(_)) => return Err(DurationParseError::DoubleIntegral),
            (TokenKind::Identifier, None) => {
                return Err(DurationParseError::MissingIntegral(head.to_string()))
            }
            (TokenKind::Identifier, Some(n)) => {
                let scale = DurationScale::parse(head)
                    .ok_or_else(|| DurationParseError::MalformedSuffix(head.to_string()))?;
                dur += scale.to_duration(n);
                num = None;
            }
            (TokenKind::WhiteSpace, _) => {}
        }
        // Consume
        s = tail;
    }

    // Anything without a suffix is considered as seconds
    if let Some(num) = num {
        dur += DurationScale::Seconds.to_duration(num);
    }

    Ok(dur)
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum TokenKind {
    Integral,
    Identifier,
    WhiteSpace,
}

fn consume_integral(
    iter: &mut impl PeekingNext<Item = (usize, char)>,
) -> Option<(TokenKind, usize)> {
    iter.peeking_take_while(|(_, c)| c.is_ascii_digit() || *c == ',' || *c == '.')
        .last()
        .map(|(i, c)| (TokenKind::Integral, i + c.len_utf8()))
}

fn consume_ident(iter: &mut impl PeekingNext<Item = (usize, char)>) -> Option<(TokenKind, usize)> {
    iter.peeking_take_while(|(_, c)| c.is_alphabetic())
        .last()
        .map(|(i, c)| (TokenKind::Identifier, i + c.len_utf8()))
}

fn consume_whitespace(
    iter: &mut impl PeekingNext<Item = (usize, char)>,
) -> Option<(TokenKind, usize)> {
    iter.peeking_take_while(|(_, c)| c.is_whitespace() || matches!(*c, ',' | '.' | ':'))
        .last()
        .map(|(i, c)| (TokenKind::WhiteSpace, i + c.len_utf8()))
}

fn tok(s: &str) -> Option<(TokenKind, &str, &str)> {
    let mut iter = s.char_indices();
    let tok = consume_integral(&mut iter)
        .or_else(|| consume_ident(&mut iter))
        .or_else(|| consume_whitespace(&mut iter));

    if let Some((kind, tok)) = tok {
        let (head, tail) = s.split_at(tok);
        Some((kind, head, tail))
    } else {
        None
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn parse_duration() {
        let input = ["", "1s", "4m", "5m2s"];
        let output = input.into_iter().map(super::parse_duration).collect_vec();
        let expected = [
            Ok(Duration::ZERO),
            Ok(Duration::from_secs(1)),
            Ok(Duration::from_secs(240)),
            Ok(Duration::from_secs(302)),
        ];
        assert_eq!(output, expected);
    }
}