ako 0.0.3

Ako is a Rust crate that offers a practical and human-friendly approach to creating, manipulating, formatting and converting dates, times and timestamps.
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use core::time::Duration;

use crate::error::{ErrorKind, ResultExt};
use crate::{AsTime, Error};

const SECONDS_PER_DAY: i64 = 86_400;
const HOURS_PER_DAY: i64 = 24;
const SECONDS_PER_HOUR: i64 = 3_600;
const MINUTES_PER_HOUR: i64 = 60;
const SECONDS_PER_MINUTE: i64 = 60;
const MILLISECONDS_PER_SECOND: i64 = 1_000;
const MICROSECONDS_PER_SECOND: i64 = 1_000_000;
const NANOSECONDS_PER_SECOND: i64 = 1_000_000_000;
const NANOSECONDS_PER_MICROSECOND: i128 = 1_000;
const NANOSECONDS_PER_MILLISECOND: i128 = 1_000_000;

/// An **interval** of time, with nanosecond precision, between two moments
/// on the time-line.
///
/// Each [`TimeInterval`] is composed of a whole number of seconds and a fractional
/// part represented in nanoseconds.
///
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct TimeInterval {
    secs: i64,
    nsec: i32,
}

// Constants
impl TimeInterval {
    /// The maximum value supported by [`TimeInterval`].
    ///
    /// # Examples
    ///
    /// ```
    /// use ako::TimeInterval;
    ///
    /// assert_eq!(TimeInterval::MAX.as_total_seconds(), i64::MAX);
    /// assert_eq!(TimeInterval::MAX.nanoseconds(), 999_999_999);
    /// # assert_eq!(TimeInterval::MAX.as_total_nanoseconds(), (i64::MAX as i128) * 1_000_000_000 + 999_999_999);
    /// # assert_eq!(TimeInterval::MAX.as_total_minutes(), 153_722_867_280_912_930);
    /// # assert_eq!(TimeInterval::MAX.as_total_hours(), 1_011_703_407);
    /// # assert_eq!(TimeInterval::MAX.as_total_days_f64(), 106_751_991_167_300.64);
    /// # assert_eq!(TimeInterval::MAX.days(), 106_751_991_167_300);
    /// # assert_eq!(TimeInterval::MAX.hours(), 15);
    /// # assert_eq!(TimeInterval::MAX.minutes(), 30);
    /// # assert_eq!(TimeInterval::MAX.seconds(), 7);
    /// ```
    ///
    pub const MAX: Self = Self {
        secs: i64::MAX,
        nsec: (NANOSECONDS_PER_SECOND - 1) as i32,
    };

    /// The minimum (largest negative) value supported by [`TimeInterval`].
    ///
    /// # Examples
    ///
    /// ```
    /// use ako::TimeInterval;
    ///
    /// assert_eq!(TimeInterval::MIN.as_total_seconds(), i64::MIN);
    /// assert_eq!(TimeInterval::MIN.nanoseconds(), -999_999_999);
    /// # assert_eq!(TimeInterval::MIN.as_total_nanoseconds(), (i64::MIN as i128) * 1_000_000_000 - 999_999_999);
    /// # assert_eq!(TimeInterval::MIN.as_total_minutes(), -153_722_867_280_912_930);
    /// # assert_eq!(TimeInterval::MIN.as_total_hours(), -1_011_703_407);
    /// # assert_eq!(TimeInterval::MIN.as_total_days_f64(), -106_751_991_167_300.64);
    /// # assert_eq!(TimeInterval::MIN.days(), -106_751_991_167_300);
    /// # assert_eq!(TimeInterval::MIN.hours(), -15);
    /// # assert_eq!(TimeInterval::MIN.minutes(), -30);
    /// # assert_eq!(TimeInterval::MIN.seconds(), -8);
    /// ```
    ///
    pub const MIN: Self = Self {
        secs: i64::MIN,
        nsec: (1 - NANOSECONDS_PER_SECOND) as i32,
    };

    /// An interval of no time.
    ///
    /// ```rust
    /// use ako::TimeInterval;
    ///
    /// assert!(TimeInterval::ZERO.is_zero());
    /// assert_eq!(TimeInterval::ZERO.as_total_nanoseconds(), 0);
    /// ```
    ///
    pub const ZERO: Self = Self::new(0, 0);
}

// Constructor
impl TimeInterval {
    /// Creates a new [`TimeInterval`] from the specified number
    /// of whole seconds and additional nanoseconds.
    ///
    /// If the number of nanoseconds is more/less than ±999,999,999 (the number of nanoseconds
    /// in one second), then it will carry over into the seconds provided.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::TimeInterval;
    ///
    /// let five_seconds = TimeInterval::new(5, 0);
    /// # assert_eq!(five_seconds.seconds(), 5);
    /// # assert_eq!(five_seconds.as_total_seconds(), 5);
    /// ```
    ///
    #[must_use]
    pub const fn new(mut seconds: i64, mut nanoseconds: i32) -> Self {
        seconds = opt_expect!(
            seconds.checked_add(nanoseconds as i64 / NANOSECONDS_PER_SECOND),
            "overflow in TimeInterval::new"
        );

        nanoseconds %= NANOSECONDS_PER_SECOND as i32;

        // shift components to ensure they have matching signs by overflowing into seconds
        if seconds.is_positive() && nanoseconds.is_negative() {
            seconds -= 1;
            nanoseconds += NANOSECONDS_PER_SECOND as i32;
        } else if seconds.is_negative() && nanoseconds.is_positive() {
            seconds += 1;
            nanoseconds -= NANOSECONDS_PER_SECOND as i32;
        }

        Self {
            secs: seconds,
            nsec: nanoseconds,
        }
    }

    /// Calculates the precise difference between two times.
    ///
    /// May be called with any type that implements [`AsTime`],
    /// which can be expressed as a time or timestamp.
    ///
    /// # Panics
    ///
    /// Panics if the difference in seconds between the given times cannot
    /// be represented as an `i64`.
    ///
    #[must_use]
    pub fn between<T: AsTime>(start: T, end: T) -> Self {
        let (start_secs, start_nsec) = start.as_timestamp();
        let (end_secs, end_nsec) = end.as_timestamp();

        let secs = end_secs
            .checked_sub(start_secs)
            .expect("overflow when subtracting timestamps");

        let nsec = end_nsec as i32 - start_nsec as i32;

        Self::new(secs, nsec)
    }
}

// Conversion From
impl TimeInterval {
    /// Creates a new [`TimeInterval`] from the specified total number of whole minutes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::TimeInterval;
    ///
    /// let ti = TimeInterval::from_hours(6);
    ///
    /// assert_eq!(6 * 60 * 60, ti.as_total_seconds());
    /// assert_eq!(0, ti.nanoseconds());
    /// ```
    ///
    #[must_use]
    pub const fn from_hours(hours: i32) -> Self {
        let secs = opt_expect!(
            (hours as i64).checked_mul(SECONDS_PER_HOUR),
            "overflow in TimeInterval::from_hours"
        );

        Self::from_seconds(secs)
    }

    /// Creates a new [`TimeInterval`] from the specified total number of whole minutes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::TimeInterval;
    ///
    /// let ti = TimeInterval::from_minutes(10);
    ///
    /// assert_eq!(10 * 60, ti.as_total_seconds());
    /// assert_eq!(0, ti.nanoseconds());
    /// ```
    ///
    #[must_use]
    pub const fn from_minutes(minutes: i64) -> Self {
        let secs = opt_expect!(
            minutes.checked_mul(SECONDS_PER_MINUTE),
            "overflow in TimeInterval::from_minutes"
        );

        Self::from_seconds(secs)
    }

    /// Creates a new [`TimeInterval`] from the specified total number of whole seconds.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::TimeInterval;
    ///
    /// let ti = TimeInterval::from_seconds(5);
    ///
    /// assert_eq!(5, ti.seconds());
    /// assert_eq!(0, ti.nanoseconds());
    /// ```
    ///
    #[must_use]
    pub const fn from_seconds(seconds: i64) -> Self {
        Self {
            secs: seconds,
            nsec: 0,
        }
    }

    /// Creates a new [`TimeInterval`] from the specified total number of whole microseconds.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::TimeInterval;
    ///
    /// let ti = TimeInterval::from_milliseconds(2569);
    ///
    /// assert_eq!(2, ti.seconds());
    /// assert_eq!(569_000_000, ti.nanoseconds());
    /// ```
    ///
    #[must_use]
    pub const fn from_milliseconds(milliseconds: i128) -> Self {
        let secs = (milliseconds / MILLISECONDS_PER_SECOND as i128) as i64;
        let nsec =
            ((milliseconds % MILLISECONDS_PER_SECOND as i128) * NANOSECONDS_PER_MILLISECOND) as i32;

        Self { secs, nsec }
    }

    /// Creates a new [`TimeInterval`] from the specified total number of whole microseconds.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::TimeInterval;
    ///
    /// let ti = TimeInterval::from_microseconds(1_000_002);
    ///
    /// assert_eq!(1, ti.seconds());
    /// assert_eq!(2000, ti.nanoseconds());
    /// ```
    ///
    #[must_use]
    pub const fn from_microseconds(microseconds: i128) -> Self {
        let secs = (microseconds / MICROSECONDS_PER_SECOND as i128) as i64;
        let nsec =
            ((microseconds % MICROSECONDS_PER_SECOND as i128) * NANOSECONDS_PER_MICROSECOND) as i32;

        Self { secs, nsec }
    }

    /// Creates a new [`TimeInterval`] from the specified total number of whole nanoseconds.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::TimeInterval;
    ///
    /// let ti = TimeInterval::from_nanoseconds(1_000_000_123);
    ///
    /// assert_eq!(1, ti.seconds());
    /// assert_eq!(123, ti.nanoseconds());
    /// ```
    ///
    #[must_use]
    pub const fn from_nanoseconds(nanoseconds: i128) -> Self {
        let secs = (nanoseconds / NANOSECONDS_PER_SECOND as i128) as i64;
        let nsec = (nanoseconds % NANOSECONDS_PER_SECOND as i128) as i32;

        Self { secs, nsec }
    }
}

// Components
impl TimeInterval {
    /// Gets the number of whole standard days (24 hours) within this time interval.
    #[must_use]
    pub const fn days(self) -> i64 {
        self.secs / SECONDS_PER_DAY
    }

    /// Gets the hour component of this time interval, from zero to ±23.
    #[must_use]
    pub const fn hours(self) -> i8 {
        ((self.secs / SECONDS_PER_HOUR) % HOURS_PER_DAY) as i8
    }

    /// Gets the minute component of this time interval, from zero to ±59.
    #[must_use]
    pub const fn minutes(self) -> i8 {
        ((self.secs / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR) as i8
    }

    /// Gets the second component of this time interval, from zero to ±59.
    #[must_use]
    pub const fn seconds(self) -> i8 {
        (self.secs % SECONDS_PER_MINUTE) as i8
    }

    /// Gets the sub-second component of this time interval, expressed as milliseconds, from zero to ±999.
    #[must_use]
    pub const fn milliseconds(self) -> i16 {
        (self.nanoseconds() / 1_000_000) as i16
    }

    /// Gets the sub-second component of this time interval, expressed as microseconds, from zero to ±999,999.
    #[must_use]
    pub const fn microseconds(self) -> i16 {
        (self.nanoseconds() / 1_000) as i16
    }

    /// Gets the sub-second component of this time interval, expressed as nanoseconds, from zero to ±999,999,999.
    #[must_use]
    pub const fn nanoseconds(self) -> i32 {
        self.nsec
    }
}

// Getters
impl TimeInterval {
    /// Returns `true` if this [`TimeInterval`] spans no time.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::TimeInterval;
    ///
    /// assert!(TimeInterval::ZERO.is_zero());
    /// assert!(TimeInterval::new(0, 0).is_zero());
    /// ```
    ///
    #[must_use]
    pub const fn is_zero(self) -> bool {
        self.secs == 0 && self.nsec == 0
    }

    /// Returns `true` if this [`TimeInterval`] is positive.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::TimeInterval;
    ///
    /// assert!(TimeInterval::new(1, 0).is_positive());
    /// assert!(TimeInterval::new(0, 1).is_positive());
    /// ```
    ///
    #[must_use]
    pub const fn is_positive(self) -> bool {
        // signs should be consistent or 0
        self.secs.is_positive() || self.nsec.is_positive()
    }

    /// Returns `true` if this [`TimeInterval`] is negative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::TimeInterval;
    ///
    /// assert!(TimeInterval::new(-1, 0).is_negative());
    /// assert!(TimeInterval::new(0, -1).is_negative());
    /// ```
    ///
    #[must_use]
    pub const fn is_negative(self) -> bool {
        // signs should be consistent or 0
        self.secs.is_negative() || self.nsec.is_negative()
    }

    /// Gets the absolute value of this time interval.
    #[must_use]
    pub const fn abs(self) -> Self {
        match self.secs.checked_abs() {
            Some(secs) => Self::new(secs, self.nsec.abs()),
            None => Self::MAX,
        }
    }
}

// Conversion To
impl TimeInterval {
    /// Gets the total number of days within this interval, as a [`f64`].
    ///
    /// The returned value includes the fractional (nanosecond) part
    /// of the interval.
    ///
    #[must_use]
    pub fn as_total_days_f64(self) -> f64 {
        self.as_total_seconds_f64() / SECONDS_PER_DAY as f64
    }

    /// Gets the total number of _whole_ hours within this interval.
    #[must_use]
    pub const fn as_total_hours(self) -> i32 {
        (self.secs / SECONDS_PER_HOUR) as i32
    }

    /// Gets the total number of _whole_ minutes within this interval.
    #[must_use]
    pub const fn as_total_minutes(self) -> i64 {
        self.secs / SECONDS_PER_MINUTE
    }

    /// Gets the total number of _whole_ seconds within this interval.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::TimeInterval;
    ///
    /// let interval = TimeInterval::new(5, 730023852);
    /// assert_eq!(interval.as_total_seconds(), 5);
    /// ```
    ///
    #[must_use]
    pub const fn as_total_seconds(self) -> i64 {
        self.secs
    }

    /// Gets the total number of seconds within this interval, as a [`f64`].
    ///
    /// The returned value includes the fractional (nanosecond) part
    /// of the interval.
    ///
    #[must_use]
    pub fn as_total_seconds_f64(self) -> f64 {
        self.secs as f64 + self.nsec as f64 / NANOSECONDS_PER_SECOND as f64
    }

    /// Gets the total number of whole milliseconds within this interval.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ako::TimeInterval;
    ///
    /// let interval = TimeInterval::new(5, 730023852);
    /// assert_eq!(interval.as_total_milliseconds(), 5730);
    /// ```
    ///
    #[must_use]
    pub const fn as_total_milliseconds(self) -> i128 {
        self.as_total_nanoseconds() / 1_000_000
    }

    /// Gets the total number of whole microseconds within this interval.
    #[must_use]
    pub const fn as_total_microseconds(self) -> i128 {
        self.as_total_nanoseconds() / 1_000
    }

    /// Gets the total number of whole nanoseconds within this interval.
    #[must_use]
    pub const fn as_total_nanoseconds(self) -> i128 {
        (self.secs as i128 * NANOSECONDS_PER_SECOND as i128) + self.nsec as i128
    }
}

impl TryFrom<Duration> for TimeInterval {
    type Error = Error;

    fn try_from(value: Duration) -> Result<Self, Self::Error> {
        let secs: i64 = value.as_secs().try_into().context(ErrorKind::OutOfRange)?;

        // SAFETY: range returned from `subsec_nanos` is 0 ..= 999,999,999
        let nsec = value.subsec_nanos() as i32;

        Ok(Self { secs, nsec })
    }
}

impl TryFrom<TimeInterval> for Duration {
    type Error = Error;

    fn try_from(value: TimeInterval) -> Result<Self, Self::Error> {
        let secs: u64 = value.secs.try_into().context(ErrorKind::OutOfRange)?;
        let nsec: u32 = value.nsec.try_into().context(ErrorKind::OutOfRange)?;

        Ok(Self::new(secs, nsec))
    }
}

#[cfg(test)]
mod tests {
    use float_cmp::assert_approx_eq;
    use test_case::test_case;

    use crate::interval::TimeInterval;

    #[test_case(0, 0, 0)]
    #[test_case(23_567_894, 23_567, 23)]
    #[test_case(2_335_325_235_567_894, 2_335_325_235_567, 2_335_325_235)]
    fn nanoseconds_to_totals(nanos: i128, micros: i128, millis: i128) {
        let interval = TimeInterval::from_nanoseconds(nanos);

        assert_eq!(interval.as_total_nanoseconds(), nanos);
        assert_eq!(interval.as_total_microseconds(), micros);
        assert_eq!(interval.as_total_milliseconds(), millis);
    }

    #[test_case(-23_567_894, -23_567, -23)]
    #[test_case(-2_335_325_235_567_894, -2_335_325_235_567, -2_335_325_235)]
    fn negative_nanoseconds_to_totals(nanos: i128, micros: i128, millis: i128) {
        let interval = TimeInterval::from_nanoseconds(nanos);

        assert_eq!(interval.as_total_nanoseconds(), nanos);
        assert_eq!(interval.as_total_microseconds(), micros);
        assert_eq!(interval.as_total_milliseconds(), millis);
    }

    #[test_case(0, 0.0)]
    #[test_case(23567894, 0.023567894)]
    #[test_case(2335325235567894, 2335325.235567894)]
    fn nanoseconds_to_total_seconds_f64(nanoseconds: i128, seconds: f64) {
        let interval = TimeInterval::from_nanoseconds(nanoseconds);

        assert_approx_eq!(f64, interval.as_total_seconds_f64(), seconds);
    }

    #[test_case(-23567894, -0.023567894000000034)]
    #[test_case(-2335325235567894, -2335325.235567894)]
    fn negative_nanoseconds_to_total_seconds_f64(nanoseconds: i128, seconds: f64) {
        let interval = TimeInterval::from_nanoseconds(nanoseconds);

        assert_approx_eq!(f64, interval.as_total_seconds_f64(), seconds);
    }

    #[test_case(0, (0, 0, 0))]
    #[test_case(50, (0, 0, 50))]
    #[test_case(1229, (0, 20, 29))]
    #[test_case(4189, (1, 9, 49))]
    #[test_case(23567894, (6546, 38, 14))]
    fn seconds_to_components(seconds: i64, components: (i32, i8, i8)) {
        let interval = TimeInterval::from_seconds(seconds);

        assert_eq!(
            (
                interval.as_total_hours(),
                interval.minutes(),
                interval.seconds()
            ),
            components
        );
    }

    #[test_case(-50, (0, 0, -50))]
    #[test_case(-1229, (0, -20, -29))]
    #[test_case(-4189, (-1, -9, -49))]
    #[test_case(-23567894, (-6546, -38, -14))]
    fn negative_seconds_to_components(seconds: i64, components: (i32, i8, i8)) {
        let interval = TimeInterval::from_seconds(seconds);

        assert_eq!(
            (
                interval.as_total_hours(),
                interval.minutes(),
                interval.seconds()
            ),
            components
        );
    }

    #[test_case(0, (0, 0, 0, 0))]
    #[test_case(23_567_894, (0, 0, 0, 23_567_894))]
    #[test_case(2_335_325_235_567_894, (648, 42, 5, 235_567_894))]
    fn nanoseconds_to_components(nanos: i128, components: (i32, i8, i8, i32)) {
        let interval = TimeInterval::from_nanoseconds(nanos);

        assert_eq!(
            (
                interval.as_total_hours(),
                interval.minutes(),
                interval.seconds(),
                interval.nanoseconds()
            ),
            components
        );
    }

    #[test_case(-23_567_894, (0, 0, 0, -23_567_894))]
    #[test_case(-2_335_325_235_567_894, (-648, -42, -5, -235_567_894))]
    fn negative_nanoseconds_to_components(nanos: i128, components: (i32, i8, i8, i32)) {
        let interval = TimeInterval::from_nanoseconds(nanos);

        assert_eq!(
            (
                interval.as_total_hours(),
                interval.minutes(),
                interval.seconds(),
                interval.nanoseconds()
            ),
            components
        );
    }
}