synta 0.1.11

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
//! ASN.1 tag handling
//!
//! Tags consist of:
//! - Class: Universal, Application, Context-specific, Private
//! - Constructed/Primitive flag
//! - Number: The type identifier

use crate::error::{Error, Result};
#[cfg(all(not(feature = "std"), feature = "serde"))]
use alloc::string::String;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

/// ASN.1 tag class
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum TagClass {
    /// Universal (0b00)
    Universal = 0b00,
    /// Application (0b01)
    Application = 0b01,
    /// Context-specific (0b10)
    ContextSpecific = 0b10,
    /// Private (0b11)
    Private = 0b11,
}

impl TagClass {
    /// Create from byte value (upper 2 bits)
    #[inline(always)]
    pub fn from_byte(byte: u8) -> Self {
        match (byte >> 6) & 0b11 {
            0b00 => TagClass::Universal,
            0b01 => TagClass::Application,
            0b10 => TagClass::ContextSpecific,
            0b11 => TagClass::Private,
            _ => unreachable!(),
        }
    }

    /// Convert to byte value
    pub fn to_byte(self) -> u8 {
        (self as u8) << 6
    }
}

/// ASN.1 tag
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Tag {
    class: TagClass,
    constructed: bool,
    number: u32,
}

impl Tag {
    /// Create a new tag
    pub const fn new(class: TagClass, constructed: bool, number: u32) -> Self {
        Self {
            class,
            constructed,
            number,
        }
    }

    /// Create a universal tag
    pub const fn universal(number: u32) -> Self {
        Self::new(TagClass::Universal, false, number)
    }

    /// Create a universal constructed tag
    pub const fn universal_constructed(number: u32) -> Self {
        Self::new(TagClass::Universal, true, number)
    }

    /// Create a context-specific tag
    pub const fn context_specific(number: u32) -> Self {
        Self::new(TagClass::ContextSpecific, false, number)
    }

    /// Create a context-specific constructed tag
    pub const fn context_specific_constructed(number: u32) -> Self {
        Self::new(TagClass::ContextSpecific, true, number)
    }

    /// Create an application tag
    pub const fn application(number: u32) -> Self {
        Self::new(TagClass::Application, false, number)
    }

    /// Get the tag class
    pub const fn class(&self) -> TagClass {
        self.class
    }

    /// Check if the tag is constructed
    pub const fn is_constructed(&self) -> bool {
        self.constructed
    }

    /// Get the tag number
    pub const fn number(&self) -> u32 {
        self.number
    }

    /// Calculate the encoded length of this tag
    pub fn encoded_len(&self) -> usize {
        if self.number < 31 {
            1
        } else {
            // High tag number form
            1 + self.number_encoded_len()
        }
    }

    /// Calculate encoded length of tag number (for high tag number form)
    fn number_encoded_len(&self) -> usize {
        if self.number == 0 {
            1
        } else {
            let mut n = self.number;
            let mut len = 0;
            while n > 0 {
                len += 1;
                n >>= 7;
            }
            len
        }
    }

    /// Encode the tag to a buffer
    pub fn encode(&self, buffer: &mut Vec<u8>) -> Result<()> {
        if self.number < 31 {
            // Low tag number form (0-30)
            let byte = self.class.to_byte()
                | if self.constructed { 0b00100000 } else { 0 }
                | (self.number as u8);
            buffer.push(byte);
        } else {
            // High tag number form (>= 31)
            let first_byte =
                self.class.to_byte() | if self.constructed { 0b00100000 } else { 0 } | 0b00011111; // All five bits set
            buffer.push(first_byte);

            // Encode tag number in base-128, big-endian
            let mut encoded = Vec::new();
            let mut n = self.number;
            while n > 0 {
                encoded.push((n & 0x7F) as u8);
                n >>= 7;
            }

            // Reverse and set high bit on all but last byte
            for (i, byte) in encoded.iter().rev().enumerate() {
                if i < encoded.len() - 1 {
                    buffer.push(byte | 0x80);
                } else {
                    buffer.push(*byte);
                }
            }
        }
        Ok(())
    }

    /// Decode a tag from a byte slice
    /// Returns (tag, bytes_consumed)
    pub fn decode(bytes: &[u8], position: usize) -> Result<(Self, usize)> {
        if bytes.is_empty() {
            return Err(Error::UnexpectedEof { position });
        }

        let first_byte = bytes[0];
        let class = TagClass::from_byte(first_byte);
        let constructed = (first_byte & 0b00100000) != 0;
        let number_bits = first_byte & 0b00011111;

        if number_bits < 31 {
            // Low tag number form (fast path - most common)
            Ok((Tag::new(class, constructed, number_bits as u32), 1))
        } else {
            // High tag number form (cold path - rare)
            #[cfg(feature = "unchecked")]
            {
                Self::decode_high_tag_unchecked(bytes, class, constructed, first_byte, position)
            }
            #[cfg(not(feature = "unchecked"))]
            {
                Self::decode_high_tag_checked(bytes, class, constructed, first_byte, position)
            }
        }
    }

    /// Decode high tag number with validation (safe)
    #[cfg(not(feature = "unchecked"))]
    #[cold]
    #[inline(never)]
    fn decode_high_tag_checked(
        bytes: &[u8],
        class: TagClass,
        constructed: bool,
        first_byte: u8,
        position: usize,
    ) -> Result<(Self, usize)> {
        let mut number: u32 = 0;
        let mut bytes_read = 1;

        loop {
            if bytes_read >= bytes.len() {
                return Err(Error::UnexpectedEof {
                    position: position + bytes_read,
                });
            }

            let byte = bytes[bytes_read];
            bytes_read += 1;

            // Check for overflow
            if number > (u32::MAX >> 7) {
                return Err(Error::InvalidTag {
                    position,
                    byte: first_byte,
                });
            }

            number = (number << 7) | ((byte & 0x7F) as u32);

            // Check if this is the last byte (high bit not set)
            if (byte & 0x80) == 0 {
                break;
            }

            // Prevent infinite loops with overly long encodings
            if bytes_read > 5 {
                // 5 bytes is enough for u32
                return Err(Error::InvalidTag {
                    position,
                    byte: first_byte,
                });
            }
        }

        Ok((Tag::new(class, constructed, number), bytes_read))
    }

    /// Decode high tag number without validation (fast but assumes valid DER)
    #[cfg(feature = "unchecked")]
    #[cold]
    #[inline(never)]
    fn decode_high_tag_unchecked(
        bytes: &[u8],
        class: TagClass,
        constructed: bool,
        _first_byte: u8,
        _position: usize,
    ) -> Result<(Self, usize)> {
        let mut number: u32 = 0;
        let mut bytes_read = 1;

        loop {
            let byte = bytes[bytes_read];
            bytes_read += 1;

            // Skip overflow check - assume valid DER
            number = (number << 7) | ((byte & 0x7F) as u32);

            // Check if this is the last byte (high bit not set)
            if (byte & 0x80) == 0 {
                break;
            }

            // Skip length check - assume valid DER
        }

        Ok((Tag::new(class, constructed, number), bytes_read))
    }
}

// Universal tag numbers as constants

/// Tag number for BOOLEAN type (tag 1)
pub const TAG_BOOLEAN: u32 = 1;

/// Tag number for INTEGER type (tag 2)
pub const TAG_INTEGER: u32 = 2;

/// Tag number for BIT STRING type (tag 3)
pub const TAG_BIT_STRING: u32 = 3;

/// Tag number for OCTET STRING type (tag 4)
pub const TAG_OCTET_STRING: u32 = 4;

/// Tag number for NULL type (tag 5)
pub const TAG_NULL: u32 = 5;

/// Tag number for OBJECT IDENTIFIER type (tag 6)
pub const TAG_OBJECT_IDENTIFIER: u32 = 6;

/// Tag number for REAL type (tag 9)
pub const TAG_REAL: u32 = 9;

/// Tag number for ENUMERATED type (tag 10)
pub const TAG_ENUMERATED: u32 = 10;

/// Tag number for UTF8String type (tag 12)
pub const TAG_UTF8_STRING: u32 = 12;

/// Tag number for SEQUENCE and SEQUENCE OF types (tag 16)
pub const TAG_SEQUENCE: u32 = 16;

/// Tag number for SET and SET OF types (tag 17)
pub const TAG_SET: u32 = 17;

/// Tag number for PrintableString type (tag 19)
pub const TAG_PRINTABLE_STRING: u32 = 19;

/// Tag number for IA5String type (tag 22)
pub const TAG_IA5_STRING: u32 = 22;

/// Tag number for UTCTime type (tag 23)
pub const TAG_UTC_TIME: u32 = 23;

/// Tag number for GeneralizedTime type (tag 24)
pub const TAG_GENERALIZED_TIME: u32 = 24;

/// Tag number for VisibleString type (tag 26) — printable ASCII subset
pub const TAG_VISIBLE_STRING: u32 = 26;

/// Tag number for GeneralString type (tag 27) — 8-bit character set, treated as Latin-1
pub const TAG_GENERAL_STRING: u32 = 27;

/// Tag number for UniversalString type (tag 28) — UCS-4 (UTF-32 big-endian)
pub const TAG_UNIVERSAL_STRING: u32 = 28;

/// Tag number for BMPString type (tag 30) — UCS-2 (UTF-16 big-endian, BMP only)
pub const TAG_BMP_STRING: u32 = 30;

/// Tag number for NumericString type (tag 18) — digits and space
pub const TAG_NUMERIC_STRING: u32 = 18;

/// Tag number for TeletexString / T61String type (tag 20) — arbitrary 8-bit bytes
pub const TAG_TELETEX_STRING: u32 = 20;

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

#[cfg(feature = "serde")]
impl serde::Serialize for TagClass {
    fn serialize<S: serde::Serializer>(&self, s: S) -> core::result::Result<S::Ok, S::Error> {
        s.serialize_str(match self {
            TagClass::Universal => "Universal",
            TagClass::Application => "Application",
            TagClass::ContextSpecific => "ContextSpecific",
            TagClass::Private => "Private",
        })
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for TagClass {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> core::result::Result<Self, D::Error> {
        struct V;
        impl<'de> serde::de::Visitor<'de> for V {
            type Value = TagClass;
            fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
                write!(
                    f,
                    "one of \"Universal\", \"Application\", \"ContextSpecific\", \"Private\""
                )
            }
            fn visit_str<E: serde::de::Error>(self, v: &str) -> core::result::Result<TagClass, E> {
                match v {
                    "Universal" => Ok(TagClass::Universal),
                    "Application" => Ok(TagClass::Application),
                    "ContextSpecific" => Ok(TagClass::ContextSpecific),
                    "Private" => Ok(TagClass::Private),
                    _ => Err(E::unknown_variant(
                        v,
                        &["Universal", "Application", "ContextSpecific", "Private"],
                    )),
                }
            }
        }
        d.deserialize_str(V)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Tag {
    fn serialize<S: serde::Serializer>(&self, s: S) -> core::result::Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut st = s.serialize_struct("Tag", 3)?;
        st.serialize_field("class", &self.class())?;
        st.serialize_field("constructed", &self.is_constructed())?;
        st.serialize_field("number", &self.number())?;
        st.end()
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Tag {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> core::result::Result<Self, D::Error> {
        struct TagVisitor;
        impl<'de> serde::de::Visitor<'de> for TagVisitor {
            type Value = Tag;
            fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
                write!(f, "a Tag with class, constructed, and number fields")
            }
            fn visit_map<A: serde::de::MapAccess<'de>>(
                self,
                mut map: A,
            ) -> core::result::Result<Tag, A::Error> {
                let mut class: Option<TagClass> = None;
                let mut constructed: Option<bool> = None;
                let mut number: Option<u32> = None;
                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "class" => class = Some(map.next_value()?),
                        "constructed" => constructed = Some(map.next_value()?),
                        "number" => number = Some(map.next_value()?),
                        _ => {
                            let _ = map.next_value::<serde::de::IgnoredAny>()?;
                        }
                    }
                }
                let class = class.ok_or_else(|| serde::de::Error::missing_field("class"))?;
                let constructed =
                    constructed.ok_or_else(|| serde::de::Error::missing_field("constructed"))?;
                let number = number.ok_or_else(|| serde::de::Error::missing_field("number"))?;
                Ok(Tag::new(class, constructed, number))
            }
        }
        d.deserialize_map(TagVisitor)
    }
}