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
//! This module is used to parse [`RFC3339`] datetime string
//!
//! # Example
//! ```
//! use humanize_rs::time::{Time, TimeZone};
//!
//! assert_eq!(
//!     "2018-09-21T16:56:44.234867232+08:00".parse::<Time>(),
//!     Ok(Time::from_timetuple(
//!         2018,
//!         9,
//!         21,
//!         16,
//!         56,
//!         44,
//!         234867232,
//!         TimeZone::new(8).unwrap(),
//!     ).unwrap())
//! );
//! ```
//!
//! [`RFC3339`]: https://tools.ietf.org/html/rfc3339

mod timezone;

pub use self::timezone::*;

use std::cmp::Ordering;
use std::str::{from_utf8, FromStr};
use std::time::{Duration, SystemTime};
use ParseError;

const MAX_SECONDS: u64 = 315569433600;
const UNIX_EPOCH: Time = Time {
    sec: 62167132800,
    nano: 0,
};

const SECS_PER_MINUTE: u64 = 60;
const SECS_PER_HOUR: u64 = 60 * SECS_PER_MINUTE;
const SECS_PER_DAY: u64 = 24 * SECS_PER_HOUR;
const DAYS_PER_400_YEARS: u32 = 365 * 400 + 97;
const DAYS_PER_100_YEARS: u32 = 365 * 100 + 24;
const DAYS_PER_4_YEARS: u32 = 365 * 4 + 1;
const DAYS_BEFORE: [u32; 13] = [
    0,
    31,
    31 + 28,
    31 + 28 + 31,
    31 + 28 + 31 + 30,
    31 + 28 + 31 + 30 + 31,
    31 + 28 + 31 + 30 + 31 + 30,
    31 + 28 + 31 + 30 + 31 + 30 + 31,
    31 + 28 + 31 + 30 + 31 + 30 + 31 + 31,
    31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
    31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
    31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30,
    31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31,
];

const DATE_TIME_FORMAT_MIN_LENGTH: usize = 10; // "2006-01-02"
const DATE_TIME_FORMAT_WITH_TIME: usize = 19; // "2006-01-02T15:04:05"
const DATE_TIME_FORMAT_MAX_LENGTH: usize = 35; // "2006-01-02T15:04:05.999999999Z07:00"

/// Represents a time in range [0000-01-01T00:00:00Z, 10000-01-01T00:00:00Z)
#[derive(Debug, Eq, PartialEq)]
pub struct Time {
    sec: u64,
    nano: u32,
}

impl Time {
    /// Represents `1970-01-01 00:00:00Z`
    pub const UNIX_EPOCH: Time = UNIX_EPOCH;

    /// Returns a Time with the given time tuple
    pub fn from_timetuple(
        year: u32,
        month: u32,
        day: u32,
        hour: u32,
        minute: u32,
        second: u32,
        nano: u32,
        timezone: TimeZone,
    ) -> Option<Time> {
        if !in_range(year, 0, 10000)
            || !in_range(month, 1, 12)
            || !in_range(day, 1, 31)
            || !in_range(hour, 0, 23)
            || !in_range(minute, 0, 59)
            || !in_range(second, 0, 59)
            || !in_range(nano, 0, 1_000_000_000 - 1)
        {
            return None;
        }

        let is_leap = is_leap_year(year);

        if !is_day_validate(is_leap, month, day) {
            return None;
        }

        let mut d: u32 = 0;

        let mut y = year;

        let mut n: u32 = y / 400;
        y -= 400 * n;
        d += DAYS_PER_400_YEARS * n;

        n = y / 100;
        y -= n * 100;
        d += DAYS_PER_100_YEARS * n;

        n = y / 4;
        y -= n * 4;
        d += DAYS_PER_4_YEARS * n;

        n = y;
        d += 365 * n;

        d += DAYS_BEFORE[(month - 1) as usize];
        // already calculated in DAYS_PER_XX_YEARS
        if year > 0 && is_leap && month <= 2 {
            d -= 1;
        }

        d += day - 1;

        let mut sec: u64 = d as u64 * SECS_PER_DAY
            + hour as u64 * SECS_PER_HOUR
            + minute as u64 * SECS_PER_MINUTE
            + second as u64;

        let offset = timezone.offset();
        if offset >= 0 {
            let minus = offset as u64;
            if minus > sec {
                return None;
            }

            sec -= minus;
        } else {
            sec += (-offset) as u64;
        }

        if sec >= MAX_SECONDS {
            return None;
        }

        Some(Time {
            sec: sec,
            nano: nano,
        })
    }

    /// Convert the time to SystemTime, returns None if the time is before unix epoch
    pub fn to_system_time(&self) -> Option<SystemTime> {
        if let Some(d) = self.since(&UNIX_EPOCH) {
            return Some(SystemTime::UNIX_EPOCH + d);
        }

        None
    }

    /// Returns the duration since an earlier time, and None if earlier is not before self.
    pub fn since(&self, earlier: &Time) -> Option<Duration> {
        if self < earlier {
            return None;
        }

        let mut sec = self.sec - earlier.sec;
        let mut nano = self.nano;
        if nano < earlier.nano {
            sec -= 1;
            nano += 1_000_000_000;
        }
        nano -= earlier.nano;

        Some(Duration::new(sec, nano))
    }
}

fn is_leap_year(y: u32) -> bool {
    return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
}

fn in_range(n: u32, min: u32, max: u32) -> bool {
    return min <= n && n <= max;
}

fn is_day_validate(is_leap: bool, m: u32, d: u32) -> bool {
    match m {
        2 if is_leap => d <= 29,
        2 => d <= 28,
        4 | 6 | 9 | 11 => d <= 30,
        _ => d <= 31,
    }
}

impl FromStr for Time {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        parse_rfc3339(s)
    }
}

impl PartialOrd for Time {
    fn partial_cmp(&self, other: &Time) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Time {
    fn cmp(&self, other: &Time) -> Ordering {
        let ord = self.sec.cmp(&other.sec);
        match ord {
            Ordering::Equal => self.nano.cmp(&other.nano),
            _ => ord,
        }
    }
}

/// Parses a [`RFC3339`] datetime string
///
/// [`RFC3339`]: https://tools.ietf.org/html/rfc3339
pub fn parse_rfc3339(s: &str) -> Result<Time, ParseError> {
    let bs = s.trim().as_bytes();
    let size = bs.len();
    if size == 0 {
        return Err(ParseError::EmptyInput);
    }

    if size < DATE_TIME_FORMAT_MIN_LENGTH
        || (size > DATE_TIME_FORMAT_MIN_LENGTH && size < DATE_TIME_FORMAT_WITH_TIME)
    {
        return Err(ParseError::TooShort);
    }

    if size > DATE_TIME_FORMAT_MAX_LENGTH {
        return Err(ParseError::TooLong);
    }

    if !check_pattern(bs) {
        return Err(ParseError::Malformed);
    }

    let year = read_u32(&bs[0..4])?;
    let month = read_u32(&bs[5..7])?;
    let day = read_u32(&bs[8..10])?;

    let hour: u32;
    let minute: u32;
    let second: u32;
    if size > DATE_TIME_FORMAT_MIN_LENGTH {
        hour = read_u32(&bs[DATE_TIME_FORMAT_MIN_LENGTH + 1..DATE_TIME_FORMAT_MIN_LENGTH + 3])?;
        minute = read_u32(&bs[DATE_TIME_FORMAT_MIN_LENGTH + 4..DATE_TIME_FORMAT_MIN_LENGTH + 6])?;
        second = read_u32(&bs[DATE_TIME_FORMAT_MIN_LENGTH + 7..DATE_TIME_FORMAT_MIN_LENGTH + 9])?;
    } else {
        hour = 0;
        minute = 0;
        second = 0;
    }

    let nano: u32;
    let tzstr: &str;
    if size > DATE_TIME_FORMAT_WITH_TIME {
        let tz_start: usize;
        if bs[DATE_TIME_FORMAT_WITH_TIME] == b'.' {
            let (v, read) = read_nano(&bs[DATE_TIME_FORMAT_WITH_TIME + 1..]);
            if read == 0 {
                return Err(ParseError::MissingValue);
            }
            nano = v;
            tz_start = DATE_TIME_FORMAT_WITH_TIME + 1 + read;
        } else {
            nano = 0;
            tz_start = DATE_TIME_FORMAT_WITH_TIME;
        }

        tzstr = from_utf8(&bs[tz_start..]).or(Err(ParseError::InvalidTimezone))?;
    } else {
        nano = 0;
        tzstr = "";
    }

    let tz = tzstr.parse::<TimeZone>()?;

    Time::from_timetuple(year, month, day, hour, minute, second, nano, tz)
        .ok_or(ParseError::Overflow)
}

fn check_pattern(bs: &[u8]) -> bool {
    if bs[4] != b'-' || bs[7] != b'-' {
        return false;
    }

    if bs.len() > DATE_TIME_FORMAT_MIN_LENGTH {
        if (bs[DATE_TIME_FORMAT_MIN_LENGTH] != b'T' && bs[DATE_TIME_FORMAT_MIN_LENGTH] != b' ')
            || bs[DATE_TIME_FORMAT_MIN_LENGTH + 3] != b':'
            || bs[DATE_TIME_FORMAT_MIN_LENGTH + 6] != b':'
        {
            return false;
        }
    }

    if bs.len() > DATE_TIME_FORMAT_WITH_TIME {
        if bs[DATE_TIME_FORMAT_WITH_TIME] != b'.'
            && bs[DATE_TIME_FORMAT_WITH_TIME] != b'Z'
            && bs[DATE_TIME_FORMAT_WITH_TIME] != b'+'
            && bs[DATE_TIME_FORMAT_WITH_TIME] != b'-'
        {
            return false;
        }
    }

    true
}

fn read_u32(bs: &[u8]) -> Result<u32, ParseError> {
    let mut read: usize = 0;
    let mut n: u32 = 0;

    while read < bs.len() {
        let c = bs[read];
        if c < b'0' || c > b'9' {
            return Err(ParseError::InvalidValue);
        }

        n = n * 10;
        n += (c - b'0') as u32;

        read += 1;
    }

    Ok(n)
}

fn read_nano(bs: &[u8]) -> (u32, usize) {
    let mut read: usize = 0;
    let mut n: u32 = 0;

    while read < bs.len() && read <= 9 {
        let c = bs[read];
        if c < b'0' || c > b'9' {
            break;
        }

        n = n * 10;
        n += (c - b'0') as u32;

        read += 1;
    }

    if read < 9 {
        n = n * 10_u32.pow((9 - read) as u32);
    }

    (n, read)
}

#[cfg(test)]
mod tests;