synta 0.2.3

ASN.1 parser, decoder, and encoder library with DER/BER support and C FFI
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
//! ASN.1 time types

#[cfg(not(feature = "std"))]
use alloc::string::String;

/// ASN.1 UTCTime (YYMMDDHHMMSSZ format)
///
/// UTCTime represents dates from 1950-2049.
/// Format: YYMMDDHHMMSSZ where:
/// - YY: Two-digit year (00-49 = 2000-2049, 50-99 = 1950-1999)
/// - MM: Month (01-12)
/// - DD: Day (01-31)
/// - HH: Hour (00-23)
/// - MM: Minute (00-59)
/// - SS: Second (00-59)
/// - Z: UTC timezone indicator
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UtcTime {
    /// Year (1950-2049)
    pub year: u16,
    /// Month (1-12)
    pub month: u8,
    /// Day (1-31)
    pub day: u8,
    /// Hour (0-23)
    pub hour: u8,
    /// Minute (0-59)
    pub minute: u8,
    /// Second (0-59)
    pub second: u8,
}

impl UtcTime {
    /// Create a new UTCTime
    pub fn new(
        year: u16,
        month: u8,
        day: u8,
        hour: u8,
        minute: u8,
        second: u8,
    ) -> crate::Result<Self> {
        // Validate year range
        if !(1950..=2049).contains(&year) {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        // Validate month
        if !(1..=12).contains(&month) {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        // Validate day (simplified, doesn't check month-specific limits)
        if !(1..=31).contains(&day) {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        // Validate hour
        if hour > 23 {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        // Validate minute
        if minute > 59 {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        // Validate second
        if second > 59 {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        Ok(Self {
            year,
            month,
            day,
            hour,
            minute,
            second,
        })
    }

    /// Parse from string format (YYMMDDHHMMSSZ)
    pub(crate) fn from_str(s: &str) -> crate::Result<Self> {
        if s.len() != 13 {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        if !s.ends_with('Z') {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        let yy = parse_two_digits(&s[0..2])?;
        let mm = parse_two_digits(&s[2..4])?;
        let dd = parse_two_digits(&s[4..6])?;
        let hh = parse_two_digits(&s[6..8])?;
        let min = parse_two_digits(&s[8..10])?;
        let ss = parse_two_digits(&s[10..12])?;

        // Convert two-digit year to four-digit year
        let year = if yy >= 50 {
            1900 + yy as u16
        } else {
            2000 + yy as u16
        };

        Self::new(year, mm, dd, hh, min, ss)
    }
}

// Implement Display trait for UtcTime
#[cfg(feature = "std")]
impl core::fmt::Display for UtcTime {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let yy = (self.year % 100) as u8;
        write!(
            f,
            "{:02}{:02}{:02}{:02}{:02}{:02}Z",
            yy, self.month, self.day, self.hour, self.minute, self.second
        )
    }
}

/// ASN.1 GeneralizedTime (YYYYMMDDHHMMSSZ or YYYYMMDDHHMMSS.fffZ format)
///
/// Format: YYYYMMDDHHMMSSZ or YYYYMMDDHHMMSS.fffZ where:
/// - YYYY: Four-digit year
/// - MM: Month (01-12)
/// - DD: Day (01-31)
/// - HH: Hour (00-23)
/// - MM: Minute (00-59)
/// - SS: Second (00-59)
/// - .fff: Optional fractional seconds
/// - Z: UTC timezone indicator
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GeneralizedTime {
    /// Year
    pub year: u16,
    /// Month (1-12)
    pub month: u8,
    /// Day (1-31)
    pub day: u8,
    /// Hour (0-23)
    pub hour: u8,
    /// Minute (0-59)
    pub minute: u8,
    /// Second (0-59)
    pub second: u8,
    /// Fractional seconds in milliseconds (0-999), optional
    pub milliseconds: Option<u16>,
}

// ── Shared string-parsing helpers ────────────────────────────────────────────

/// Parse exactly 2 ASCII decimal digits from `b` into a `u8`.
///
/// Returns `None` if `b` does not have exactly 2 bytes, or if either byte is
/// not an ASCII digit.
pub fn parse2(b: &[u8]) -> Option<u8> {
    if b.len() != 2 || !b[0].is_ascii_digit() || !b[1].is_ascii_digit() {
        return None;
    }
    Some((b[0] - b'0') * 10 + (b[1] - b'0'))
}

/// Parse exactly 4 ASCII decimal digits from `b` into a `u16`.
///
/// Returns `None` if `b` does not have exactly 4 bytes, or if any byte is not
/// an ASCII digit.
pub fn parse4(b: &[u8]) -> Option<u16> {
    if b.len() != 4 || b.iter().any(|c| !c.is_ascii_digit()) {
        return None;
    }
    Some(
        (b[0] - b'0') as u16 * 1_000
            + (b[1] - b'0') as u16 * 100
            + (b[2] - b'0') as u16 * 10
            + (b[3] - b'0') as u16,
    )
}

/// Expand a two-digit year to a four-digit year per RFC 5280 §4.1.2.5.1.
///
/// | Range | Expansion |
/// |-------|-----------|
/// | 00–49 | 2000–2049 |
/// | 50–99 | 1950–1999 |
pub fn expand_yy(yy: u8) -> u16 {
    if yy >= 50 {
        1900u16 + yy as u16
    } else {
        2000u16 + yy as u16
    }
}

impl GeneralizedTime {
    /// Parse a time string into a `GeneralizedTime`.
    ///
    /// Accepted formats (UTC only; trailing `Z` required):
    ///
    /// | Format | Length | Example |
    /// |--------|--------|---------|
    /// | `YYYYMMDDHHmmssZ` | 15 chars | `"20240101120000Z"` |
    /// | `YYMMDDHHmmssZ` | 13 chars | `"240101120000Z"` — 2-digit year expanded per RFC 5280 |
    ///
    /// For the 13-character form, the year is expanded by
    /// [`expand_yy`]: digits `00`–`49` map to 2000–2049, `50`–`99` to
    /// 1950–1999.
    ///
    /// Unlike the internal `from_str` method (which also handles fractional
    /// seconds), this function strictly requires integer seconds only.
    ///
    /// Returns `Err` with a descriptive message if the string is malformed or
    /// any field value is out of range.
    #[cfg(feature = "std")]
    pub fn parse(s: &str) -> Result<Self, String> {
        let b = s.as_bytes();
        let (year, rest) = if s.len() == 15 && s.ends_with('Z') {
            let year = parse4(&b[0..4]).ok_or_else(|| format!("invalid year in time '{s}'"))?;
            (year, &b[4..])
        } else if s.len() == 13 && s.ends_with('Z') {
            let yy = parse2(&b[0..2]).ok_or_else(|| format!("invalid year in time '{s}'"))?;
            (expand_yy(yy), &b[2..])
        } else {
            return Err(format!(
                "unsupported time format '{s}': expected YYYYMMDDHHmmssZ or YYMMDDHHmmssZ"
            ));
        };
        let month = parse2(&rest[0..2]).ok_or_else(|| format!("invalid month in time '{s}'"))?;
        let day = parse2(&rest[2..4]).ok_or_else(|| format!("invalid day in time '{s}'"))?;
        let hour = parse2(&rest[4..6]).ok_or_else(|| format!("invalid hour in time '{s}'"))?;
        let minute = parse2(&rest[6..8]).ok_or_else(|| format!("invalid minute in time '{s}'"))?;
        let second = parse2(&rest[8..10]).ok_or_else(|| format!("invalid second in time '{s}'"))?;
        Self::new(year, month, day, hour, minute, second, None)
            .map_err(|e| format!("invalid GeneralizedTime '{s}': {e}"))
    }

    /// Convert this `GeneralizedTime` to a Unix timestamp (seconds since
    /// 1970-01-01 00:00:00 UTC).
    ///
    /// Uses the Hinnant algorithm for Gregorian ↔ day-count conversion.
    /// Negative values are returned for dates before the Unix epoch.
    pub fn to_unix(&self) -> i64 {
        let y = self.year as i64;
        let m = self.month as i64;
        let d = self.day as i64;
        let y_adj = y - if m <= 2 { 1 } else { 0 };
        let era = y_adj.div_euclid(400);
        let yoe = y_adj - era * 400;
        let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + d - 1;
        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
        let days = era * 146_097 + doe - 719_468;
        let sod = self.hour as i64 * 3_600 + self.minute as i64 * 60 + self.second as i64;
        days * 86_400 + sod
    }

    /// Convert a Unix timestamp (seconds since 1970-01-01 00:00:00 UTC) to a
    /// `GeneralizedTime`.
    ///
    /// Returns `None` if `secs` maps to a year outside the valid range 1–9999
    /// (i.e. before 0001-01-01 or after 9999-12-31).
    ///
    /// Uses the Hinnant algorithm for Gregorian ↔ day-count conversion —
    /// correct for all calendar dates without special-casing.
    ///
    /// Reference: <https://howardhinnant.github.io/date_algorithms.html>
    pub fn from_unix(secs: i64) -> Option<Self> {
        let days = secs.div_euclid(86_400);
        let sod = secs.rem_euclid(86_400); // seconds within the day, 0..86399

        let z = days + 719_468;
        let era = z.div_euclid(146_097);
        let doe = z - era * 146_097;
        let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
        let y = yoe + era * 400;
        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
        let mp = (5 * doy + 2) / 153;
        let d = doy - (153 * mp + 2) / 5 + 1;
        let m = if mp < 10 { mp + 3 } else { mp - 9 };
        let year = if m <= 2 { y + 1 } else { y };
        let month = m;
        let day = d;

        if !(1..=9999).contains(&year) {
            return None;
        }

        let hour = (sod / 3_600) as u8;
        let minute = ((sod % 3_600) / 60) as u8;
        let second = (sod % 60) as u8;

        Self::new(
            year as u16,
            month as u8,
            day as u8,
            hour,
            minute,
            second,
            None,
        )
        .ok()
    }

    /// Create a new GeneralizedTime
    pub fn new(
        year: u16,
        month: u8,
        day: u8,
        hour: u8,
        minute: u8,
        second: u8,
        milliseconds: Option<u16>,
    ) -> crate::Result<Self> {
        // Validate month
        if !(1..=12).contains(&month) {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        // Validate day (simplified)
        if !(1..=31).contains(&day) {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        // Validate hour
        if hour > 23 {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        // Validate minute
        if minute > 59 {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        // Validate second
        if second > 59 {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        // Validate milliseconds if present
        if let Some(ms) = milliseconds {
            if ms > 999 {
                return Err(crate::Error::InvalidTime { position: 0 });
            }
        }

        Ok(Self {
            year,
            month,
            day,
            hour,
            minute,
            second,
            milliseconds,
        })
    }

    /// Parse from string format (YYYYMMDDHHMMSSZ or YYYYMMDDHHMMSS.fffZ)
    pub(crate) fn from_str(s: &str) -> crate::Result<Self> {
        if !s.ends_with('Z') {
            return Err(crate::Error::InvalidTime { position: 0 });
        }

        // Check if it has fractional seconds
        let has_fraction = s.contains('.');

        if has_fraction {
            // Format: YYYYMMDDHHMMSS.fffZ (minimum length 18: 14 + 1 + 1 + 1 + 1)
            if s.len() < 16 {
                return Err(crate::Error::InvalidTime { position: 0 });
            }

            let yyyy = parse_four_digits(&s[0..4])?;
            let mm = parse_two_digits(&s[4..6])?;
            let dd = parse_two_digits(&s[6..8])?;
            let hh = parse_two_digits(&s[8..10])?;
            let min = parse_two_digits(&s[10..12])?;
            let ss = parse_two_digits(&s[12..14])?;

            // Parse fractional seconds
            let dot_pos = 14;
            if s.as_bytes()[dot_pos] != b'.' {
                return Err(crate::Error::InvalidTime { position: 0 });
            }

            let fraction_str = &s[15..s.len() - 1]; // Skip '.' and 'Z'
            let milliseconds = if fraction_str.is_empty() {
                None
            } else {
                // Parse up to 3 digits for milliseconds
                let ms_str = &fraction_str[..fraction_str.len().min(3)];
                let ms = ms_str
                    .parse::<u16>()
                    .map_err(|_| crate::Error::InvalidTime { position: 0 })?;
                // Adjust for number of digits (e.g., "5" = 500ms, "50" = 500ms, "500" = 500ms)
                let ms = match ms_str.len() {
                    1 => ms * 100,
                    2 => ms * 10,
                    _ => ms,
                };
                Some(ms)
            };

            Self::new(yyyy, mm, dd, hh, min, ss, milliseconds)
        } else {
            // Format: YYYYMMDDHHMMSSZ (length 15)
            if s.len() != 15 {
                return Err(crate::Error::InvalidTime { position: 0 });
            }

            let yyyy = parse_four_digits(&s[0..4])?;
            let mm = parse_two_digits(&s[4..6])?;
            let dd = parse_two_digits(&s[6..8])?;
            let hh = parse_two_digits(&s[8..10])?;
            let min = parse_two_digits(&s[10..12])?;
            let ss = parse_two_digits(&s[12..14])?;

            Self::new(yyyy, mm, dd, hh, min, ss, None)
        }
    }
}

// Implement Display trait for GeneralizedTime
#[cfg(feature = "std")]
impl core::fmt::Display for GeneralizedTime {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        if let Some(ms) = self.milliseconds {
            write!(
                f,
                "{:04}{:02}{:02}{:02}{:02}{:02}.{:03}Z",
                self.year, self.month, self.day, self.hour, self.minute, self.second, ms
            )
        } else {
            write!(
                f,
                "{:04}{:02}{:02}{:02}{:02}{:02}Z",
                self.year, self.month, self.day, self.hour, self.minute, self.second
            )
        }
    }
}

// Helper functions for parsing
fn parse_two_digits(s: &str) -> crate::Result<u8> {
    if s.len() != 2 {
        return Err(crate::Error::InvalidTime { position: 0 });
    }
    s.parse::<u8>()
        .map_err(|_| crate::Error::InvalidTime { position: 0 })
}

fn parse_four_digits(s: &str) -> crate::Result<u16> {
    if s.len() != 4 {
        return Err(crate::Error::InvalidTime { position: 0 });
    }
    s.parse::<u16>()
        .map_err(|_| crate::Error::InvalidTime { position: 0 })
}

// Implement Decode trait for UtcTime
impl crate::traits::Decode<'_> for UtcTime {
    fn decode(decoder: &mut crate::der::decoder::Decoder) -> crate::Result<Self> {
        use crate::tag::TAG_UTC_TIME;

        let tag = decoder.read_tag()?;
        let expected_tag = crate::Tag::universal(TAG_UTC_TIME);

        if tag != expected_tag {
            return Err(crate::Error::UnexpectedTag {
                position: decoder.position(),
                expected: expected_tag,
                actual: tag,
            });
        }

        let length = decoder.read_length()?;
        let len = length.definite()?;

        let bytes = decoder.read_bytes(len)?;

        // Parse as UTF-8 string
        let s = core::str::from_utf8(bytes).map_err(|_| crate::Error::InvalidTime {
            position: decoder.position(),
        })?;

        UtcTime::from_str(s)
    }
}

// Implement Encode trait for UtcTime
impl crate::traits::Encode for UtcTime {
    fn encode(&self, encoder: &mut crate::der::encoder::Encoder) -> crate::Result<()> {
        use crate::tag::TAG_UTC_TIME;

        let tag = crate::Tag::universal(TAG_UTC_TIME);
        encoder.write_tag(tag)?;

        #[cfg(feature = "std")]
        let time_str = self.to_string();
        #[cfg(not(feature = "std"))]
        let time_str = {
            use core::fmt::Write;
            let mut s = String::new();
            let yy = (self.year % 100) as u8;
            write!(
                &mut s,
                "{:02}{:02}{:02}{:02}{:02}{:02}Z",
                yy, self.month, self.day, self.hour, self.minute, self.second
            )
            .map_err(|_| crate::Error::InvalidTime { position: 0 })?;
            s
        };

        encoder.write_length(time_str.len())?;
        encoder.write_bytes(time_str.as_bytes());
        Ok(())
    }

    fn encoded_len(&self) -> crate::Result<usize> {
        let tag_len = 1;
        let content_len = 13; // YYMMDDHHMMSSZ
        let length_len = crate::Length::Definite(content_len).encoded_len()?;
        Ok(tag_len + length_len + content_len)
    }
}

// Implement Tagged trait for UtcTime
impl crate::traits::Tagged for UtcTime {
    fn tag() -> crate::Tag {
        crate::Tag::universal(crate::tag::TAG_UTC_TIME)
    }
}

// Implement Decode trait for GeneralizedTime
impl crate::traits::Decode<'_> for GeneralizedTime {
    fn decode(decoder: &mut crate::der::decoder::Decoder) -> crate::Result<Self> {
        use crate::tag::TAG_GENERALIZED_TIME;

        let tag = decoder.read_tag()?;
        let expected_tag = crate::Tag::universal(TAG_GENERALIZED_TIME);

        if tag != expected_tag {
            return Err(crate::Error::UnexpectedTag {
                position: decoder.position(),
                expected: expected_tag,
                actual: tag,
            });
        }

        let length = decoder.read_length()?;
        let len = length.definite()?;

        let bytes = decoder.read_bytes(len)?;

        // Parse as UTF-8 string
        let s = core::str::from_utf8(bytes).map_err(|_| crate::Error::InvalidTime {
            position: decoder.position(),
        })?;

        GeneralizedTime::from_str(s)
    }
}

// Implement Encode trait for GeneralizedTime
impl crate::traits::Encode for GeneralizedTime {
    fn encode(&self, encoder: &mut crate::der::encoder::Encoder) -> crate::Result<()> {
        use crate::tag::TAG_GENERALIZED_TIME;

        let tag = crate::Tag::universal(TAG_GENERALIZED_TIME);
        encoder.write_tag(tag)?;

        #[cfg(feature = "std")]
        let time_str = self.to_string();
        #[cfg(not(feature = "std"))]
        let time_str = {
            use core::fmt::Write;
            let mut s = String::new();
            if let Some(ms) = self.milliseconds {
                write!(
                    &mut s,
                    "{:04}{:02}{:02}{:02}{:02}{:02}.{:03}Z",
                    self.year, self.month, self.day, self.hour, self.minute, self.second, ms
                )
                .map_err(|_| crate::Error::InvalidTime { position: 0 })?;
            } else {
                write!(
                    &mut s,
                    "{:04}{:02}{:02}{:02}{:02}{:02}Z",
                    self.year, self.month, self.day, self.hour, self.minute, self.second
                )
                .map_err(|_| crate::Error::InvalidTime { position: 0 })?;
            }
            s
        };

        encoder.write_length(time_str.len())?;
        encoder.write_bytes(time_str.as_bytes());
        Ok(())
    }

    fn encoded_len(&self) -> crate::Result<usize> {
        let tag_len = 1;
        let content_len = if self.milliseconds.is_some() {
            19 // YYYYMMDDHHMMSS.fffZ
        } else {
            15 // YYYYMMDDHHMMSSZ
        };
        let length_len = crate::Length::Definite(content_len).encoded_len()?;
        Ok(tag_len + length_len + content_len)
    }
}

// Implement Tagged trait for GeneralizedTime
impl crate::traits::Tagged for GeneralizedTime {
    fn tag() -> crate::Tag {
        crate::Tag::universal(crate::tag::TAG_GENERALIZED_TIME)
    }
}

// ---- serde support ----

/// `UtcTime` serializes as a string in `YYMMDDHHMMSSZ` format.
#[cfg(feature = "serde")]
impl serde::Serialize for UtcTime {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        use core::fmt::Write;
        let mut buf = String::new();
        let yy = (self.year % 100) as u8;
        let _ = write!(
            buf,
            "{:02}{:02}{:02}{:02}{:02}{:02}Z",
            yy, self.month, self.day, self.hour, self.minute, self.second
        );
        s.serialize_str(&buf)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for UtcTime {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct V;
        impl<'de> serde::de::Visitor<'de> for V {
            type Value = UtcTime;
            fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
                write!(f, "a UTCTime string in YYMMDDHHMMSSZ format")
            }
            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<UtcTime, E> {
                UtcTime::from_str(v).map_err(|_| E::custom("invalid UTCTime string"))
            }
        }
        d.deserialize_str(V)
    }
}

/// `GeneralizedTime` serializes as a string in `YYYYMMDDHHMMSSZ` or
/// `YYYYMMDDHHMMSS.mmmZ` format.
#[cfg(feature = "serde")]
impl serde::Serialize for GeneralizedTime {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        use core::fmt::Write;
        let mut buf = String::new();
        if let Some(ms) = self.milliseconds {
            let _ = write!(
                buf,
                "{:04}{:02}{:02}{:02}{:02}{:02}.{:03}Z",
                self.year, self.month, self.day, self.hour, self.minute, self.second, ms
            );
        } else {
            let _ = write!(
                buf,
                "{:04}{:02}{:02}{:02}{:02}{:02}Z",
                self.year, self.month, self.day, self.hour, self.minute, self.second
            );
        }
        s.serialize_str(&buf)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for GeneralizedTime {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct V;
        impl<'de> serde::de::Visitor<'de> for V {
            type Value = GeneralizedTime;
            fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
                write!(
                    f,
                    "a GeneralizedTime string in YYYYMMDDHHMMSSZ or YYYYMMDDHHMMSS.mmmZ format"
                )
            }
            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<GeneralizedTime, E> {
                GeneralizedTime::from_str(v)
                    .map_err(|_| E::custom("invalid GeneralizedTime string"))
            }
        }
        d.deserialize_str(V)
    }
}