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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
use super::parse_error::ParseError;
use crate::{interval_norm::IntervalNorm, Interval};

use super::{
    scale_date, scale_time, DAYS_PER_MONTH, HOURS_PER_DAY, MICROS_PER_SECOND, MINUTES_PER_HOUR,
    MONTHS_PER_YEAR, SECONDS_PER_MIN,
};

impl Interval {
     pub fn from_postgres(iso_str: &str) -> Result<Interval, ParseError> {
        let mut delim = vec![
            "years", "months", "mons", "days", "hours", "minutes", "seconds",
        ];
        let mut time_tokens = iso_str.split(' ').collect::<Vec<&str>>();        // clean up empty values caused by n spaces between values.
        time_tokens.retain(|&token| !token.is_empty());
        // since there might not be space between the delim and the
        // value we need to scan each token.
        let mut final_tokens = Vec::with_capacity(time_tokens.len());
        for token in time_tokens {
            if is_token_alphanumeric(token)? {
                let (val, unit) = split_token(token)?;
                final_tokens.push(val);
                final_tokens.push(unit);
            } else {
                final_tokens.push(token.to_owned());
            }
        }
        if final_tokens.len() % 2 != 0 {
            return Err(ParseError::from_invalid_interval(
                "Invalid amount tokens were found.",
            ));
        }
        // Consume our tokens and build up the
        // normalized interval.
        let mut val = 0.0;
        let mut is_numeric = true;
        let mut interval = IntervalNorm::default();
        for token in final_tokens {
            if is_numeric {
                val = token.parse::<f64>()?;
                is_numeric = false;
            } else {
                consume_token(&mut interval, val, token, &mut delim)?;
                is_numeric = true;
            }
        }
        interval.try_into_interval()
    }
}

/// Does the token contain both alphabetic and numeric characters?
fn is_token_alphanumeric(val: &str) -> Result<bool, ParseError> {
    let mut has_numeric = false;
    let mut has_alpha = false;
    for character in val.chars() {
        if character.is_numeric() || character == '-' || character == '.' {
            has_numeric = true;
        } else if character.is_alphabetic() {
            has_alpha = true;
        } else {
            return Err(ParseError::from_invalid_interval(
                "String can only contain alpha numeric characters.",
            ));
        }
    }
    Ok(has_numeric && has_alpha)
}

/// Split the token into two tokens as they might of not been
/// seperated by a space.
fn split_token(val: &str) -> Result<(String, String), ParseError> {
    let mut is_numeric_done = false;
    let mut value = String::new();
    let mut delim = String::new();
    for character in val.chars() {
        if (character.is_numeric() || character == '-' || character == '.') && !is_numeric_done {
            value.push(character);
        } else if character.is_alphabetic() {
            is_numeric_done = true;
            delim.push(character)
        } else {
            return Err(ParseError::from_invalid_interval(
                "String can only contain alpha numeric characters.",
            ));
        }
    }
    Ok((value, delim))
}

/// Consume the token parts and add to the normalized interval.
fn consume_token<'a>(
    interval: &mut IntervalNorm,
    val: f64,
    delim: String,
    delim_list: &mut Vec<&'a str>,
) -> Result<(), ParseError> {
    // Unlike iso8601 the delimiter can only appear once
    // so we need to check if the token can be found in
    // the deliminator list.
    if delim_list.contains(&&*delim) {
        match &*delim {
            "years" => {
                let (year, month) = scale_date(val, MONTHS_PER_YEAR);
                interval.years += year;
                interval.months += month;
                delim_list.retain(|x| *x != "years");
                Ok(())
            }
            "months" | "mons" => {
                let (month, day) = scale_date(val, DAYS_PER_MONTH);
                interval.months += month;
                interval.days += day;
                delim_list.retain(|x| *x != "months" && *x != "mons");
                Ok(())
            }
            "days" => {
                let (days, hours) = scale_date(val, HOURS_PER_DAY);
                interval.days += days;
                interval.hours += hours as i64;
                delim_list.retain(|x| *x != "days");
                Ok(())
            }
            "hours" => {
                let (hours, minutes) = scale_time(val, MINUTES_PER_HOUR);
                interval.hours += hours;
                interval.minutes += minutes;
                delim_list.retain(|x| *x != "hours");
                Ok(())
            }
            "minutes" => {
                let (minutes, seconds) = scale_time(val, SECONDS_PER_MIN);
                interval.minutes += minutes;
                interval.seconds += seconds;
                delim_list.retain(|x| *x != "minutes");
                Ok(())
            }
            "seconds" => {
                let (seconds, microseconds) = scale_time(val, MICROS_PER_SECOND);
                interval.seconds += seconds;
                interval.microseconds += microseconds;
                delim_list.retain(|x| *x != "seconds");
                Ok(())
            }
            _ => unreachable!(),
        }
    } else {
        Err(ParseError::from_invalid_interval(&format!(
            "Unknown or duplicate deliminator \"{}\"",
            delim
        )))
    }
}

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

    #[test]
    fn test_from_postgres_1() {
        let interval = Interval::from_postgres("1 years").unwrap();
        let interval_exp = Interval::new(12, 0, 0);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_2() {
        let interval = Interval::from_postgres("1years").unwrap();
        let interval_exp = Interval::new(12, 0, 0);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_3() {
        let interval = Interval::from_postgres("1 years 1 months").unwrap();
        let interval_exp = Interval::new(13, 0, 0);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_4() {
        let interval = Interval::from_postgres("1years 1months").unwrap();
        let interval_exp = Interval::new(13, 0, 0);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_5() {
        let interval = Interval::from_postgres("1 years 1 mons 1 days").unwrap();
        let interval_exp = Interval::new(13, 1, 0);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_6() {
        let interval = Interval::from_postgres("1years 1mons 1days").unwrap();
        let interval_exp = Interval::new(13, 1, 0);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_7() {
        let interval = Interval::from_postgres("1 years 1 months 1 days 1 hours").unwrap();
        let interval_exp = Interval::new(13, 1, 3600000000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_8() {
        let interval = Interval::from_postgres("1years 1months 1days 1hours").unwrap();
        let interval_exp = Interval::new(13, 1, 3600000000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_9() {
        let interval =
            Interval::from_postgres("1 years 1 months 1 days 1 hours 10 minutes").unwrap();
        let interval_exp = Interval::new(13, 1, 4200000000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_10() {
        let interval =
            Interval::from_postgres("1 years 1 months 1 days 1 hours 10 minutes 15 seconds")
                .unwrap();
        let interval_exp = Interval::new(13, 1, 4215000000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_11() {
        let interval = Interval::from_postgres("1 hours").unwrap();
        let interval_exp = Interval::new(0, 0, 3600000000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_12() {
        let interval = Interval::from_postgres("1 hours 10 minutes").unwrap();
        let interval_exp = Interval::new(0, 0, 4200000000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_13() {
        let interval = Interval::from_postgres("1 hours 10 minutes 15 seconds").unwrap();
        let interval_exp = Interval::new(0, 0, 4215000000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_14() {
        let interval = Interval::from_postgres("-1 years").unwrap();
        let interval_exp = Interval::new(-12, 0, 0);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_15() {
        let interval = Interval::from_postgres("-1years").unwrap();
        let interval_exp = Interval::new(-12, 0, 0);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_16() {
        let interval = Interval::from_postgres("-1 years -1 months").unwrap();
        let interval_exp = Interval::new(-13, 0, 0);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_17() {
        let interval = Interval::from_postgres("-1 years -1months -1 days").unwrap();
        let interval_exp = Interval::new(-13, -1, 0);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_18() {
        let interval = Interval::from_postgres("-1 years -1 months -1 days -1 hours").unwrap();
        let interval_exp = Interval::new(-13, -1, -3600000000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_19() {
        let interval =
            Interval::from_postgres("-1 years -1 months -1days -1hours -10minutes").unwrap();
        let interval_exp = Interval::new(-13, -1, -4200000000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_20() {
        let interval =
            Interval::from_postgres("-1years -1 mons -1 days -1hours -10minutes -15seconds")
                .unwrap();
        let interval_exp = Interval::new(-13, -1, -4215000000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_21() {
        let interval = Interval::from_postgres("-1 hours").unwrap();
        let interval_exp = Interval::new(0, 0, -3600000000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_22() {
        let interval = Interval::from_postgres("-1 hours -10minutes").unwrap();
        let interval_exp = Interval::new(0, 0, -4200000000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_23() {
        let interval = Interval::from_postgres("-1 hours -10minutes -15 seconds").unwrap();
        let interval_exp = Interval::new(0, 0, -4215000000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_24() {
        let interval = Interval::from_postgres("years 1");
        assert_eq!(interval.is_err(), true);
    }

    #[test]
    fn test_from_postgres_25() {
        let interval = Interval::from_postgres("- years");
        assert_eq!(interval.is_err(), true);
    }

    #[test]
    fn test_from_postgres_26() {
        let interval = Interval::from_postgres("10");
        assert_eq!(interval.is_err(), true);
    }

    #[test]
    fn test_from_postgres_27() {
        let interval = Interval::from_postgres("1.2 years").unwrap();
        let interval_exp = Interval::new(14, 0, 0);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_28() {
        let interval = Interval::from_postgres("1.2 months").unwrap();
        let interval_exp = Interval::new(1, 6, 0);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_29() {
        let interval = Interval::from_postgres("1.2 seconds").unwrap();
        let interval_exp = Interval::new(0, 0, 1_200_000);
        assert_eq!(interval, interval_exp);
    }

    #[test]
    fn test_from_postgres_30() {
        let interval = Interval::from_postgres("!");
        assert_eq!(interval.is_err(), true);
    }

}