synta 0.1.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
//! 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>,
}

impl GeneralizedTime {
    /// 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)
    }
}