der 0.8.0

Pure Rust embedded-friendly implementation of the Distinguished Encoding Rules (DER) for Abstract Syntax Notation One (ASN.1) as described in ITU X.690 with full support for heapless `no_std`/`no_alloc` targets
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
//! Date and time functionality shared between various ASN.1 types
//! (e.g. `GeneralizedTime`, `UTCTime`)

// Adapted from the `humantime` crate.
// Copyright (c) 2016 The humantime Developers
// Released under the MIT OR Apache 2.0 licenses

use crate::{Error, ErrorKind, Result, Tag, Writer};
use core::{fmt, str::FromStr, time::Duration};

#[cfg(feature = "std")]
use std::time::{SystemTime, UNIX_EPOCH};

use const_range::const_contains_u8;
#[cfg(feature = "time")]
use time::PrimitiveDateTime;

/// Minimum year allowed in [`DateTime`] values.
const MIN_YEAR: u16 = 1970;

/// Maximum duration since `UNIX_EPOCH` which can be represented as a
/// [`DateTime`] (non-inclusive).
///
/// This corresponds to: 9999-12-31T23:59:59Z
const MAX_UNIX_DURATION: Duration = Duration::from_secs(253_402_300_799);

/// Date-and-time type shared by multiple ASN.1 types
/// (e.g. `GeneralizedTime`, `UTCTime`).
///
/// Following conventions from RFC 5280, this type is always Z-normalized
/// (i.e. represents a UTC time). However, it isn't named "UTC time" in order
/// to prevent confusion with ASN.1 `UTCTime`.
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct DateTime {
    /// Full year (e.g. 2000).
    ///
    /// Must be >=1970 to permit positive conversions to Unix time.
    year: u16,

    /// Month (1-12)
    month: u8,

    /// Day of the month (1-31)
    day: u8,

    /// Hour (0-23)
    hour: u8,

    /// Minutes (0-59)
    minutes: u8,

    /// Seconds (0-59)
    seconds: u8,

    /// [`Duration`] since the Unix epoch.
    unix_duration: Duration,
}

impl DateTime {
    /// This is the maximum date represented by the [`DateTime`]
    /// This corresponds to: 9999-12-31T23:59:59Z
    pub const INFINITY: DateTime = DateTime {
        year: 9999,
        month: 12,
        day: 31,
        hour: 23,
        minutes: 59,
        seconds: 59,
        unix_duration: MAX_UNIX_DURATION,
    };

    /// Create a new [`DateTime`] from the given UTC time components.
    ///
    /// # Errors
    /// Returns [`Error`] with [`ErrorKind::DateTime`] in the event the date is invalid.
    pub const fn new(
        year: u16,
        month: u8,
        day: u8,
        hour: u8,
        minutes: u8,
        seconds: u8,
    ) -> Result<Self> {
        match Self::from_ymd_hms(year, month, day, hour, minutes, seconds) {
            Some(date) => Ok(date),
            None => Err(Error::from_kind(ErrorKind::DateTime)),
        }
    }

    /// Create a new [`DateTime`] from the given UTC time components.
    ///
    /// Returns `None` if the value is outside the supported date range.
    // TODO(tarcieri): checked arithmetic
    #[allow(clippy::arithmetic_side_effects)]
    pub(crate) const fn from_ymd_hms(
        year: u16,
        month: u8,
        day: u8,
        hour: u8,
        minutes: u8,
        seconds: u8,
    ) -> Option<Self> {
        // Basic validation of the components.
        if year < MIN_YEAR
            || !const_contains_u8(1..=12, month)
            || !const_contains_u8(1..=31, day)
            || !const_contains_u8(0..=23, hour)
            || !const_contains_u8(0..=59, minutes)
            || !const_contains_u8(0..=59, seconds)
        {
            return None;
        }

        let leap_years =
            ((year - 1) - 1968) / 4 - ((year - 1) - 1900) / 100 + ((year - 1) - 1600) / 400;

        let is_leap_year = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);

        let (mut ydays, mdays): (u16, u8) = match month {
            1 => (0, 31),
            2 if is_leap_year => (31, 29),
            2 => (31, 28),
            3 => (59, 31),
            4 => (90, 30),
            5 => (120, 31),
            6 => (151, 30),
            7 => (181, 31),
            8 => (212, 31),
            9 => (243, 30),
            10 => (273, 31),
            11 => (304, 30),
            12 => (334, 31),
            _ => return None,
        };

        if day > mdays || day == 0 {
            return None;
        }

        ydays += day as u16 - 1;

        if is_leap_year && month > 2 {
            ydays += 1;
        }

        let days = ((year - 1970) as u64) * 365 + leap_years as u64 + ydays as u64;
        let time = seconds as u64 + (minutes as u64 * 60) + (hour as u64 * 3600);
        let unix_duration = Duration::from_secs(time + days * 86400);

        if unix_duration.as_secs() > MAX_UNIX_DURATION.as_secs() {
            return None;
        }

        Some(Self {
            year,
            month,
            day,
            hour,
            minutes,
            seconds,
            unix_duration,
        })
    }

    /// Compute a [`DateTime`] from the given [`Duration`] since the `UNIX_EPOCH`.
    ///
    /// # Errors
    /// Returns error if the value is outside the supported date range.
    // TODO(tarcieri): checked arithmetic
    #[allow(clippy::arithmetic_side_effects)]
    pub fn from_unix_duration(unix_duration: Duration) -> Result<Self> {
        if unix_duration > MAX_UNIX_DURATION {
            return Err(ErrorKind::DateTime.into());
        }

        let secs_since_epoch = unix_duration.as_secs();

        /// 2000-03-01 (mod 400 year, immediately after Feb 29)
        const LEAPOCH: i64 = 11017;
        const DAYS_PER_400Y: i64 = 365 * 400 + 97;
        const DAYS_PER_100Y: i64 = 365 * 100 + 24;
        const DAYS_PER_4Y: i64 = 365 * 4 + 1;

        let days = i64::try_from(secs_since_epoch / 86400)? - LEAPOCH;
        let secs_of_day = secs_since_epoch % 86400;

        let mut qc_cycles = days / DAYS_PER_400Y;
        let mut remdays = days % DAYS_PER_400Y;

        if remdays < 0 {
            remdays += DAYS_PER_400Y;
            qc_cycles -= 1;
        }

        let mut c_cycles = remdays / DAYS_PER_100Y;
        if c_cycles == 4 {
            c_cycles -= 1;
        }
        remdays -= c_cycles * DAYS_PER_100Y;

        let mut q_cycles = remdays / DAYS_PER_4Y;
        if q_cycles == 25 {
            q_cycles -= 1;
        }
        remdays -= q_cycles * DAYS_PER_4Y;

        let mut remyears = remdays / 365;
        if remyears == 4 {
            remyears -= 1;
        }
        remdays -= remyears * 365;

        let mut year = 2000 + remyears + 4 * q_cycles + 100 * c_cycles + 400 * qc_cycles;

        let months = [31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29];
        let mut mon = 0;
        for mon_len in months.iter() {
            mon += 1;
            if remdays < *mon_len {
                break;
            }
            remdays -= *mon_len;
        }
        let mday = remdays + 1;
        let mon = if mon + 2 > 12 {
            year += 1;
            mon - 10
        } else {
            mon + 2
        };

        let second = secs_of_day % 60;
        let mins_of_day = secs_of_day / 60;
        let minute = mins_of_day % 60;
        let hour = mins_of_day / 60;

        Self::new(
            year.try_into()?,
            mon,
            mday.try_into()?,
            hour.try_into()?,
            minute.try_into()?,
            second.try_into()?,
        )
    }

    /// Get the year.
    #[must_use]
    pub fn year(&self) -> u16 {
        self.year
    }

    /// Get the month.
    #[must_use]
    pub fn month(&self) -> u8 {
        self.month
    }

    /// Get the day.
    #[must_use]
    pub fn day(&self) -> u8 {
        self.day
    }

    /// Get the hour.
    #[must_use]
    pub fn hour(&self) -> u8 {
        self.hour
    }

    /// Get the minutes.
    #[must_use]
    pub fn minutes(&self) -> u8 {
        self.minutes
    }

    /// Get the seconds.
    #[must_use]
    pub fn seconds(&self) -> u8 {
        self.seconds
    }

    /// Compute [`Duration`] since `UNIX_EPOCH` from the given calendar date.
    #[must_use]
    pub fn unix_duration(&self) -> Duration {
        self.unix_duration
    }

    /// Instantiate from [`SystemTime`].
    ///
    /// # Errors
    /// If a time conversion error occurred.
    #[cfg(feature = "std")]
    pub fn from_system_time(time: SystemTime) -> Result<Self> {
        time.duration_since(UNIX_EPOCH)
            .map_err(|_| ErrorKind::DateTime.into())
            .and_then(Self::from_unix_duration)
    }

    /// Convert to [`SystemTime`].
    #[cfg(feature = "std")]
    #[must_use]
    pub fn to_system_time(&self) -> SystemTime {
        UNIX_EPOCH + self.unix_duration()
    }
}

impl FromStr for DateTime {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        match *s.as_bytes() {
            [
                year1,
                year2,
                year3,
                year4,
                b'-',
                month1,
                month2,
                b'-',
                day1,
                day2,
                b'T',
                hour1,
                hour2,
                b':',
                min1,
                min2,
                b':',
                sec1,
                sec2,
                b'Z',
            ] => {
                let tag = Tag::GeneralizedTime;
                let year = decode_year([year1, year2, year3, year4])?;
                let month = decode_decimal(tag, month1, month2).map_err(|_| ErrorKind::DateTime)?;
                let day = decode_decimal(tag, day1, day2).map_err(|_| ErrorKind::DateTime)?;
                let hour = decode_decimal(tag, hour1, hour2).map_err(|_| ErrorKind::DateTime)?;
                let minutes = decode_decimal(tag, min1, min2).map_err(|_| ErrorKind::DateTime)?;
                let seconds = decode_decimal(tag, sec1, sec2).map_err(|_| ErrorKind::DateTime)?;
                Self::new(year, month, day, hour, minutes, seconds)
            }
            _ => Err(ErrorKind::DateTime.into()),
        }
    }
}

impl fmt::Display for DateTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{:02}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
            self.year, self.month, self.day, self.hour, self.minutes, self.seconds
        )
    }
}

#[cfg(feature = "std")]
impl From<DateTime> for SystemTime {
    fn from(time: DateTime) -> SystemTime {
        time.to_system_time()
    }
}

#[cfg(feature = "std")]
impl From<&DateTime> for SystemTime {
    fn from(time: &DateTime) -> SystemTime {
        time.to_system_time()
    }
}

#[cfg(feature = "std")]
impl TryFrom<SystemTime> for DateTime {
    type Error = Error;

    fn try_from(time: SystemTime) -> Result<DateTime> {
        DateTime::from_system_time(time)
    }
}

#[cfg(feature = "std")]
impl TryFrom<&SystemTime> for DateTime {
    type Error = Error;

    fn try_from(time: &SystemTime) -> Result<DateTime> {
        DateTime::from_system_time(*time)
    }
}

#[cfg(feature = "time")]
impl TryFrom<DateTime> for PrimitiveDateTime {
    type Error = Error;

    fn try_from(time: DateTime) -> Result<PrimitiveDateTime> {
        let month = time.month().try_into()?;
        let date = time::Date::from_calendar_date(i32::from(time.year()), month, time.day())?;
        let time = time::Time::from_hms(time.hour(), time.minutes(), time.seconds())?;

        Ok(PrimitiveDateTime::new(date, time))
    }
}

#[cfg(feature = "time")]
impl TryFrom<PrimitiveDateTime> for DateTime {
    type Error = Error;

    fn try_from(time: PrimitiveDateTime) -> Result<DateTime> {
        DateTime::new(
            time.year().try_into().map_err(|_| ErrorKind::DateTime)?,
            time.month().into(),
            time.day(),
            time.hour(),
            time.minute(),
            time.second(),
        )
    }
}

// Implement by hand because the derive would create invalid values.
// Use the conversion from Duration to create a valid value.
#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for DateTime {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        Self::from_unix_duration(Duration::new(
            u.int_in_range(0..=MAX_UNIX_DURATION.as_secs().saturating_sub(1))?,
            u.int_in_range(0..=999_999_999)?,
        ))
        .map_err(|_| arbitrary::Error::IncorrectFormat)
    }

    fn size_hint(depth: usize) -> (usize, Option<usize>) {
        arbitrary::size_hint::and(u64::size_hint(depth), u32::size_hint(depth))
    }
}

/// Decode 2-digit decimal value
// TODO(tarcieri): checked arithmetic
#[allow(clippy::arithmetic_side_effects)]
pub(crate) fn decode_decimal(tag: Tag, hi: u8, lo: u8) -> Result<u8> {
    if hi.is_ascii_digit() && lo.is_ascii_digit() {
        Ok((hi - b'0') * 10 + (lo - b'0'))
    } else {
        Err(tag.value_error().into())
    }
}

/// Encode 2-digit decimal value
pub(crate) fn encode_decimal<W>(writer: &mut W, tag: Tag, value: u8) -> Result<()>
where
    W: Writer + ?Sized,
{
    let hi_val = value / 10;

    if hi_val >= 10 {
        return Err(tag.value_error().into());
    }

    writer.write_byte(b'0'.checked_add(hi_val).ok_or(ErrorKind::Overflow)?)?;
    writer.write_byte(b'0'.checked_add(value % 10).ok_or(ErrorKind::Overflow)?)
}

/// Decode 4-digit year.
// TODO(tarcieri): checked arithmetic
#[allow(clippy::arithmetic_side_effects)]
fn decode_year(year: [u8; 4]) -> Result<u16> {
    let tag = Tag::GeneralizedTime;
    let hi = decode_decimal(tag, year[0], year[1]).map_err(|_| ErrorKind::DateTime)?;
    let lo = decode_decimal(tag, year[2], year[3]).map_err(|_| ErrorKind::DateTime)?;
    Ok(u16::from(hi) * 100 + u16::from(lo))
}

mod const_range {
    use core::ops::RangeInclusive;

    /// const [`RangeInclusive::contains`]
    #[inline]
    pub const fn const_contains_u8(range: RangeInclusive<u8>, item: u8) -> bool {
        item >= *range.start() && item <= *range.end()
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::DateTime;

    /// Ensure a day is OK
    fn is_date_valid(year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8) -> bool {
        DateTime::new(year, month, day, hour, minute, second).is_ok()
    }

    #[test]
    fn feb_leap_year_handling() {
        assert!(is_date_valid(2000, 2, 29, 0, 0, 0));
        assert!(!is_date_valid(2001, 2, 29, 0, 0, 0));
        assert!(!is_date_valid(2100, 2, 29, 0, 0, 0));
    }

    #[test]
    fn invalid_dates() {
        assert!(!is_date_valid(2, 3, 25, 0, 0, 0));

        assert!(is_date_valid(1970, 1, 26, 0, 0, 0));
        assert!(!is_date_valid(1969, 1, 26, 0, 0, 0));
        assert!(!is_date_valid(1968, 1, 26, 0, 0, 0));
        assert!(!is_date_valid(1600, 1, 26, 0, 0, 0));

        assert!(is_date_valid(2039, 2, 27, 0, 0, 0));
        assert!(!is_date_valid(2039, 2, 27, 255, 0, 0));
        assert!(!is_date_valid(2039, 2, 27, 0, 255, 0));
        assert!(!is_date_valid(2039, 2, 27, 0, 0, 255));

        assert!(is_date_valid(2055, 12, 31, 0, 0, 0));
        assert!(is_date_valid(2055, 12, 31, 23, 0, 0));
        assert!(!is_date_valid(2055, 12, 31, 24, 0, 0));
        assert!(is_date_valid(2055, 12, 31, 0, 59, 0));
        assert!(!is_date_valid(2055, 12, 31, 0, 60, 0));
        assert!(is_date_valid(2055, 12, 31, 0, 0, 59));
        assert!(!is_date_valid(2055, 12, 31, 0, 0, 60));
    }

    #[test]
    fn from_str() {
        let datetime = "2001-01-02T12:13:14Z".parse::<DateTime>().unwrap();
        assert_eq!(datetime.year(), 2001);
        assert_eq!(datetime.month(), 1);
        assert_eq!(datetime.day(), 2);
        assert_eq!(datetime.hour(), 12);
        assert_eq!(datetime.minutes(), 13);
        assert_eq!(datetime.seconds(), 14);
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn display() {
        use alloc::string::ToString;
        let datetime = DateTime::new(2001, 1, 2, 12, 13, 14).unwrap();
        assert_eq!(&datetime.to_string(), "2001-01-02T12:13:14Z");
    }
}