lox-core 0.1.0-alpha.10

Common data types and utilities for the Lox ecosystem
Documentation
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// SPDX-FileCopyrightText: 2024 Angus Morrison <github@angus-morrison.com>
// SPDX-FileCopyrightText: 2024 Helge Eichhorn <git@helgeeichhorn.de>
//
// SPDX-License-Identifier: MPL-2.0

/*!
    Module `time_of_day` exposes the concrete representation of a time of day with leap second
    support, [TimeOfDay].

    The [CivilTime] trait supports arbitrary time representations to express themselves as a
    human-readable time of day.
*/

use std::fmt::Display;
use std::str::FromStr;
use std::{cmp::Ordering, sync::OnceLock};

use crate::units::Angle;
use num::ToPrimitive;
use regex::Regex;
use thiserror::Error;

use super::subsecond::Subsecond;
use crate::i64::consts::{
    SECONDS_PER_DAY, SECONDS_PER_HALF_DAY, SECONDS_PER_HOUR, SECONDS_PER_MINUTE,
};

fn iso_regex() -> &'static Regex {
    static ISO: OnceLock<Regex> = OnceLock::new();
    ISO.get_or_init(|| {
        Regex::new(r"(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(?<subsecond>\.\d+)?").unwrap()
    })
}

/// Error type returned when attempting to construct a [TimeOfDay] with a greater number of
/// floating-point seconds than are in a day.
#[derive(Debug, Copy, Clone, Error)]
#[error("seconds must be in the range [0.0..86401.0) but was {0}")]
pub struct InvalidSeconds(f64);

impl PartialEq for InvalidSeconds {
    fn eq(&self, other: &Self) -> bool {
        self.0.total_cmp(&other.0) == Ordering::Equal
    }
}

impl Eq for InvalidSeconds {}

/// Error type returned when attempting to construct a [TimeOfDay] from invalid components.
#[derive(Debug, Clone, Error, PartialEq, Eq)]
pub enum TimeOfDayError {
    /// Hour is outside the valid range `[0, 24)`.
    #[error("hour must be in the range [0..24) but was {0}")]
    InvalidHour(u8),
    /// Minute is outside the valid range `[0, 60)`.
    #[error("minute must be in the range [0..60) but was {0}")]
    InvalidMinute(u8),
    /// Second is outside the valid range `[0, 61)`.
    #[error("second must be in the range [0..61) but was {0}")]
    InvalidSecond(u8),
    /// Second of day is outside the valid range `[0, 86401)`.
    #[error("second must be in the range [0..86401) but was {0}")]
    InvalidSecondOfDay(u64),
    /// Floating-point seconds value is out of range.
    #[error(transparent)]
    InvalidSeconds(#[from] InvalidSeconds),
    /// A leap second was specified at a time other than the end of the day.
    #[error("leap seconds are only valid at the end of the day")]
    InvalidLeapSecond,
    /// The input string is not a valid ISO 8601 time.
    #[error("invalid ISO string `{0}`")]
    InvalidIsoString(String),
}

/// `CivilTime` is the trait by which high-precision time representations expose human-readable time
/// components.
pub trait CivilTime {
    /// Returns the time-of-day component.
    fn time(&self) -> TimeOfDay;

    /// Returns the hour (0–23).
    fn hour(&self) -> u8 {
        self.time().hour()
    }

    /// Returns the minute (0–59).
    fn minute(&self) -> u8 {
        self.time().minute()
    }

    /// Returns the second (0–60, where 60 represents a leap second).
    fn second(&self) -> u8 {
        self.time().second()
    }

    /// Returns the second including the subsecond fraction as an `f64`.
    fn as_seconds_f64(&self) -> f64 {
        self.time().subsecond().as_seconds_f64() + self.time().second() as f64
    }

    /// Returns the millisecond component (0–999).
    fn millisecond(&self) -> u32 {
        self.time().subsecond().milliseconds()
    }

    /// Returns the microsecond component (0–999).
    fn microsecond(&self) -> u32 {
        self.time().subsecond().microseconds()
    }

    /// Returns the nanosecond component (0–999).
    fn nanosecond(&self) -> u32 {
        self.time().subsecond().nanoseconds()
    }

    /// Returns the picosecond component (0–999).
    fn picosecond(&self) -> u32 {
        self.time().subsecond().picoseconds()
    }

    /// Returns the femtosecond component (0–999).
    fn femtosecond(&self) -> u32 {
        self.time().subsecond().femtoseconds()
    }
}

/// A human-readable time representation with support for representing leap seconds.
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TimeOfDay {
    hour: u8,
    minute: u8,
    second: u8,
    subsecond: Subsecond,
}

impl TimeOfDay {
    /// Midnight (00:00:00.000).
    pub const MIDNIGHT: Self = TimeOfDay {
        hour: 0,
        minute: 0,
        second: 0,
        subsecond: Subsecond::ZERO,
    };

    /// Noon (12:00:00.000).
    pub const NOON: Self = TimeOfDay {
        hour: 12,
        minute: 0,
        second: 0,
        subsecond: Subsecond::ZERO,
    };
    /// Constructs a new `TimeOfDay` instance from the given hour, minute, and second components.
    ///
    /// # Errors
    ///
    /// - [TimeOfDayError::InvalidHour] if `hour` is not in the range `0..24`.
    /// - [TimeOfDayError::InvalidMinute] if `minute` is not in the range `0..60`.
    /// - [TimeOfDayError::InvalidSecond] if `second` is not in the range `0..61`.
    pub fn new(hour: u8, minute: u8, second: u8) -> Result<Self, TimeOfDayError> {
        if !(0..24).contains(&hour) {
            return Err(TimeOfDayError::InvalidHour(hour));
        }
        if !(0..60).contains(&minute) {
            return Err(TimeOfDayError::InvalidMinute(minute));
        }
        if !(0..61).contains(&second) {
            return Err(TimeOfDayError::InvalidSecond(second));
        }
        Ok(Self {
            hour,
            minute,
            second,
            subsecond: Subsecond::default(),
        })
    }

    /// Constructs a new `TimeOfDay` instance from an ISO 8601 time string.
    ///
    /// # Errors
    ///
    /// - [TimeOfDayError::InvalidIsoString] if the input string is not a valid ISO 8601 time
    ///   string.
    /// - [TimeOfDayError::InvalidHour] if the hour component is not in the range `0..24`.
    /// - [TimeOfDayError::InvalidMinute] if the minute component is not in the range `0..60`.
    /// - [TimeOfDayError::InvalidSecond] if the second component is not in the range `0..61`.
    pub fn from_iso(iso: &str) -> Result<Self, TimeOfDayError> {
        let caps = iso_regex()
            .captures(iso)
            .ok_or(TimeOfDayError::InvalidIsoString(iso.to_owned()))?;
        let hour: u8 = caps["hour"]
            .parse()
            .map_err(|_| TimeOfDayError::InvalidIsoString(iso.to_owned()))?;
        let minute: u8 = caps["minute"]
            .parse()
            .map_err(|_| TimeOfDayError::InvalidIsoString(iso.to_owned()))?;
        let second: u8 = caps["second"]
            .parse()
            .map_err(|_| TimeOfDayError::InvalidIsoString(iso.to_owned()))?;
        let mut time = TimeOfDay::new(hour, minute, second)?;
        if let Some(subsecond) = caps.name("subsecond") {
            let subsecond_str = subsecond.as_str().trim_start_matches('.');
            let subsecond: Subsecond = subsecond_str
                .parse()
                .map_err(|_| TimeOfDayError::InvalidIsoString(iso.to_owned()))?;
            time.with_subsecond(subsecond);
        }
        Ok(time)
    }

    /// Constructs a `TimeOfDay` from an hour only (minute and second default to zero).
    pub fn from_hour(hour: u8) -> Result<Self, TimeOfDayError> {
        Self::new(hour, 0, 0)
    }

    /// Constructs a `TimeOfDay` from hour and minute (second defaults to zero).
    pub fn from_hour_and_minute(hour: u8, minute: u8) -> Result<Self, TimeOfDayError> {
        Self::new(hour, minute, 0)
    }

    /// Constructs a new `TimeOfDay` instance from the given hour, minute, and floating-point second
    /// components.
    ///
    /// # Errors
    ///
    /// - [TimeOfDayError::InvalidHour] if `hour` is not in the range `0..24`.
    /// - [TimeOfDayError::InvalidMinute] if `minute` is not in the range `0..60`.
    /// - [TimeOfDayError::InvalidSeconds] if `seconds` is not in the range `0.0..86401.0`.
    pub fn from_hms(hour: u8, minute: u8, seconds: f64) -> Result<Self, TimeOfDayError> {
        if !(0.0..86401.0).contains(&seconds) {
            return Err(TimeOfDayError::InvalidSeconds(InvalidSeconds(seconds)));
        }
        let second = seconds.trunc() as u8;
        let fraction = seconds.fract();
        let subsecond = Subsecond::from_f64(fraction)
            .ok_or(TimeOfDayError::InvalidSeconds(InvalidSeconds(seconds)))?;
        Ok(Self::new(hour, minute, second)?.with_subsecond(subsecond))
    }

    /// Constructs a new `TimeOfDay` instance from the given second of a day.
    ///
    /// # Errors
    ///
    /// - [TimeOfDayError::InvalidSecondOfDay] if `second_of_day` is not in the range `0..86401`.
    pub fn from_second_of_day(second_of_day: u64) -> Result<Self, TimeOfDayError> {
        if !(0..86401).contains(&second_of_day) {
            return Err(TimeOfDayError::InvalidSecondOfDay(second_of_day));
        }
        if second_of_day == SECONDS_PER_DAY as u64 {
            return Self::new(23, 59, 60);
        }
        let hour = (second_of_day / 3600) as u8;
        let minute = ((second_of_day % 3600) / 60) as u8;
        let second = (second_of_day % 60) as u8;
        Self::new(hour, minute, second)
    }

    /// Constructs a new `TimeOfDay` instance from an integral number of seconds since J2000.
    ///
    /// Note that this constructor is not leap-second aware.
    pub fn from_seconds_since_j2000(seconds: i64) -> Self {
        let mut second_of_day = (seconds + SECONDS_PER_HALF_DAY) % SECONDS_PER_DAY;
        if second_of_day.is_negative() {
            second_of_day += SECONDS_PER_DAY;
        }
        Self::from_second_of_day(
            second_of_day
                .to_u64()
                .unwrap_or_else(|| unreachable!("second of day should be positive")),
        )
        .unwrap_or_else(|_| unreachable!("second of day should be in range"))
    }

    /// Sets the [TimeOfDay]'s subsecond component.
    pub fn with_subsecond(&mut self, subsecond: Subsecond) -> Self {
        self.subsecond = subsecond;
        *self
    }

    /// Returns the hour (0–23).
    pub fn hour(&self) -> u8 {
        self.hour
    }

    /// Returns the minute (0–59).
    pub fn minute(&self) -> u8 {
        self.minute
    }

    /// Returns the second (0–60, where 60 represents a leap second).
    pub fn second(&self) -> u8 {
        self.second
    }

    /// Returns the subsecond component.
    pub fn subsecond(&self) -> Subsecond {
        self.subsecond
    }

    /// Returns the second including the subsecond fraction as an `f64`.
    pub fn seconds_f64(&self) -> f64 {
        self.subsecond.as_seconds_f64() + self.second as f64
    }

    /// Returns the number of integral seconds since the start of the day.
    pub fn second_of_day(&self) -> i64 {
        self.hour as i64 * SECONDS_PER_HOUR
            + self.minute as i64 * SECONDS_PER_MINUTE
            + self.second as i64
    }

    /// Converts the time of day to an [`Angle`] (hour angle representation).
    pub fn to_angle(&self) -> Angle {
        Angle::from_hms(self.hour as i64, self.minute, self.seconds_f64())
    }
}

impl Display for TimeOfDay {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let precision = f.precision().unwrap_or(3);
        write!(
            f,
            "{:02}:{:02}:{:02}{}",
            self.hour,
            self.minute,
            self.second,
            format!("{:.*}", precision, self.subsecond).trim_start_matches('0')
        )
    }
}

impl FromStr for TimeOfDay {
    type Err = TimeOfDayError;

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

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

    use super::*;

    #[rstest]
    #[case(43201, TimeOfDay::new(12, 0, 1))]
    #[case(86399, TimeOfDay::new(23, 59, 59))]
    #[case(86400, TimeOfDay::new(23, 59, 60))]
    fn test_time_of_day_from_second_of_day(
        #[case] second_of_day: u64,
        #[case] expected: Result<TimeOfDay, TimeOfDayError>,
    ) {
        let actual = TimeOfDay::from_second_of_day(second_of_day);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_time_of_day_display() {
        let subsecond: Subsecond = "123456789123456".parse().unwrap();
        let time = TimeOfDay::new(12, 0, 0).unwrap().with_subsecond(subsecond);
        assert_eq!(format!("{time}"), "12:00:00.123");
        assert_eq!(format!("{time:.15}"), "12:00:00.123456789123456");
    }

    #[rstest]
    #[case(TimeOfDay::new(24, 0, 0), Err(TimeOfDayError::InvalidHour(24)))]
    #[case(TimeOfDay::new(0, 60, 0), Err(TimeOfDayError::InvalidMinute(60)))]
    #[case(TimeOfDay::new(0, 0, 61), Err(TimeOfDayError::InvalidSecond(61)))]
    #[case(
        TimeOfDay::from_second_of_day(86401),
        Err(TimeOfDayError::InvalidSecondOfDay(86401))
    )]
    #[case(TimeOfDay::from_hms(12, 0, -0.123), Err(TimeOfDayError::InvalidSeconds(InvalidSeconds(-0.123))))]
    fn test_time_of_day_error(
        #[case] actual: Result<TimeOfDay, TimeOfDayError>,
        #[case] expected: Result<TimeOfDay, TimeOfDayError>,
    ) {
        assert_eq!(actual, expected);
    }

    #[rstest]
    #[case("12:13:14", Ok(TimeOfDay::new(12, 13, 14).unwrap()))]
    #[case("12:13:14.123", Ok(TimeOfDay::new(12, 13, 14).unwrap().with_subsecond("123".parse().unwrap())))]
    #[case("2:13:14.123", Err(TimeOfDayError::InvalidIsoString("2:13:14.123".to_string())))]
    #[case("12:3:14.123", Err(TimeOfDayError::InvalidIsoString("12:3:14.123".to_string())))]
    #[case("12:13:4.123", Err(TimeOfDayError::InvalidIsoString("12:13:4.123".to_string())))]
    fn test_time_of_day_from_string(
        #[case] iso: &str,
        #[case] expected: Result<TimeOfDay, TimeOfDayError>,
    ) {
        let actual: Result<TimeOfDay, TimeOfDayError> = iso.parse();
        assert_eq!(actual, expected)
    }

    #[test]
    fn test_invalid_seconds_eq() {
        let a = InvalidSeconds(-f64::NAN);
        let b = InvalidSeconds(f64::NAN);
        // NaN values with different signs should not be equal
        assert_ne!(a, b);
        // Same NaN values should be equal
        let c = InvalidSeconds(f64::NAN);
        let d = InvalidSeconds(f64::NAN);
        assert_eq!(c, d);
    }
}