synta 0.3.1

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
698
699
700
//! ASN.1 Object Identifier (OID).
//!
//! An OID is a sequence of non-negative integers that globally identifies an
//! object (algorithm, attribute type, certificate extension, …).
//!
//! ## Encoding rules
//!
//! The first component must be 0, 1, or 2.  When the first component is 0 or
//! 1, the second must be less than 40.  On the wire the first two components
//! are combined into a single base-128 encoded integer (first × 40 + second);
//! subsequent components are each independently base-128 encoded.
//!
//! ## Matching OIDs efficiently
//!
//! Compare [`components`](ObjectIdentifier::components) slices directly rather
//! than converting to dotted-decimal strings:
//!
//! ```
//! use synta::ObjectIdentifier;
//!
//! // SHA-256: 2.16.840.1.101.3.4.2.1
//! let sha256 = ObjectIdentifier::new(&[2, 16, 840, 1, 101, 3, 4, 2, 1]).unwrap();
//! assert!(matches!(sha256.components(), [2, 16, 840, 1, 101, 3, 4, 2, 1]));
//! ```

#[cfg(all(not(feature = "std"), feature = "serde"))]
use alloc::string::String;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

use smallvec::SmallVec;

/// ASN.1 OBJECT IDENTIFIER
///
/// Uses SmallVec to avoid allocations for most OIDs (< 10 components)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjectIdentifier {
    // Most OIDs have fewer than 10 components
    components: SmallVec<[u32; 10]>,
}

impl ObjectIdentifier {
    /// Create a new `ObjectIdentifier` from a slice of component integers.
    ///
    /// # Validation
    ///
    /// - `components` must have at least 2 elements.
    /// - `components[0]` must be 0, 1, or 2.
    /// - If `components[0]` is 0 or 1, then `components[1]` must be < 40.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidOid`](crate::Error::InvalidOid) if any
    /// validation rule is violated.
    ///
    /// # Example
    ///
    /// ```
    /// use synta::ObjectIdentifier;
    ///
    /// // rsadsi (1.2.840.113549)
    /// let oid = ObjectIdentifier::new(&[1, 2, 840, 113549]).unwrap();
    /// assert_eq!(oid.to_string(), "1.2.840.113549");
    /// ```
    pub fn new(components: &[u32]) -> crate::Result<Self> {
        // OID must have at least 2 components
        if components.len() < 2 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }

        // First component must be 0, 1, or 2
        if components[0] > 2 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }

        // If first is 0 or 1, second must be < 40
        if components[0] < 2 && components[1] >= 40 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }

        Ok(Self {
            components: SmallVec::from_slice(components),
        })
    }

    /// Return the OID as a slice of component integers.
    ///
    /// The slice begins with the two top-level arc values (e.g. `[1, 2, …]`).
    /// Matching against a known OID is most efficient by comparing the slice
    /// directly rather than converting to a dotted-decimal string:
    ///
    /// ```
    /// use synta::ObjectIdentifier;
    ///
    /// let oid = ObjectIdentifier::new(&[1, 2, 840, 113549]).unwrap();
    /// assert!(matches!(oid.components(), [1, 2, 840, 113549]));
    /// ```
    pub fn components(&self) -> &[u32] {
        &self.components
    }

    /// Parse an OID from its DER/BER **content** bytes — the raw value bytes
    /// inside an OID TLV, with the tag (`0x06`) and length already stripped.
    ///
    /// This is the low-level counterpart to [`Decode`](crate::traits::Decode)
    /// for situations where the tag and length have already been consumed, for
    /// example after stripping an implicit context tag from a GeneralName
    /// `registeredID [8] IMPLICIT OID` alternative.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidOid`](crate::Error::InvalidOid) if `data` is
    /// empty, contains a truncated base-128 sequence, or causes a `u32`
    /// overflow in any component.
    ///
    /// # Example
    ///
    /// ```
    /// use synta::ObjectIdentifier;
    ///
    /// // commonName 2.5.4.3 — DER content bytes (tag+length stripped)
    /// let oid = ObjectIdentifier::from_content_bytes(&[0x55, 0x04, 0x03]).unwrap();
    /// assert_eq!(oid.to_string(), "2.5.4.3");
    /// ```
    pub fn from_content_bytes(data: &[u8]) -> crate::Result<Self> {
        if data.is_empty() {
            return Err(crate::Error::InvalidOid { position: 0 });
        }

        let mut components: SmallVec<[u32; 10]> = SmallVec::new();
        let mut i = 0;

        // First encoded value is base-128 and represents two OID components
        // combined as: arc0 * 40 + arc1  (with arc0 ∈ {0,1,2}).
        let mut combined: u32 = 0;
        loop {
            if i >= data.len() {
                return Err(crate::Error::InvalidOid { position: i });
            }
            let byte = data[i];
            i += 1;
            combined = combined
                .checked_mul(128)
                .and_then(|v| v.checked_add((byte & 0x7F) as u32))
                .ok_or(crate::Error::InvalidOid { position: i })?;
            if (byte & 0x80) == 0 {
                break;
            }
        }

        if combined < 40 {
            components.push(0);
            components.push(combined);
        } else if combined < 80 {
            components.push(1);
            components.push(combined - 40);
        } else {
            components.push(2);
            components.push(combined - 80);
        }

        // Remaining components, each independently base-128 encoded.
        while i < data.len() {
            let mut value: u32 = 0;
            loop {
                if i >= data.len() {
                    return Err(crate::Error::InvalidOid { position: i });
                }
                let byte = data[i];
                i += 1;
                value = value
                    .checked_mul(128)
                    .and_then(|v| v.checked_add((byte & 0x7F) as u32))
                    .ok_or(crate::Error::InvalidOid { position: i })?;
                if (byte & 0x80) == 0 {
                    break;
                }
            }
            components.push(value);
        }

        Ok(Self { components })
    }

    /// Construct an OID from an already-validated `SmallVec` of components.
    ///
    /// # Safety (logical)
    ///
    /// The caller must guarantee that `components` encodes a valid OID:
    /// - At least 2 elements
    /// - `components[0]` ∈ {0, 1, 2}
    /// - If `components[0]` < 2, then `components[1]` < 40
    ///
    /// This constructor skips the validation check and the `from_slice` copy
    /// performed by [`Self::new`].  It is `pub(crate)` to keep the unsafe
    /// contract internal.
    #[inline]
    pub(crate) fn from_components_unchecked(components: SmallVec<[u32; 10]>) -> Self {
        Self { components }
    }

    /// Encode this OID as DER **content** bytes — the raw base-128 arc bytes
    /// without the `0x06` tag byte or the length field.
    ///
    /// This is the symmetric counterpart to [`from_content_bytes`] and is
    /// useful for embedding OIDs in non-DER formats such as CBOR (RFC 9090
    /// tag 111) without going through the full DER TLV encoder.
    ///
    /// [`from_content_bytes`]: Self::from_content_bytes
    ///
    /// # Example
    ///
    /// ```
    /// use synta::ObjectIdentifier;
    ///
    /// // commonName 2.5.4.3
    /// let oid = ObjectIdentifier::new(&[2, 5, 4, 3]).unwrap();
    /// assert_eq!(oid.to_content_bytes(), &[0x55, 0x04, 0x03]);
    /// // Round-trip
    /// assert_eq!(ObjectIdentifier::from_content_bytes(&oid.to_content_bytes()).unwrap(), oid);
    /// ```
    pub fn to_content_bytes(&self) -> Vec<u8> {
        let mut out = Vec::new();
        let combined = self.components[0] * 40 + self.components[1];
        encode_base128(combined, &mut out);
        for &c in &self.components[2..] {
            encode_base128(c, &mut out);
        }
        out
    }
}

// `Display` produces canonical dotted-decimal notation, e.g. `"1.2.840.113549"`.
impl core::fmt::Display for ObjectIdentifier {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut iter = self.components.iter();
        if let Some(first) = iter.next() {
            write!(f, "{}", first)?;
            for component in iter {
                write!(f, ".{}", component)?;
            }
        }
        Ok(())
    }
}

// `FromStr` parses dotted-decimal notation (`"1.2.840.113549"`) and validates
// the resulting components.  Only available with the `std` feature.
#[cfg(feature = "std")]
impl core::str::FromStr for ObjectIdentifier {
    type Err = crate::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut components: SmallVec<[u32; 10]> = SmallVec::new();
        for part in s.split('.') {
            let v: u32 = part
                .parse()
                .map_err(|_| crate::Error::InvalidOid { position: 0 })?;
            components.push(v);
        }
        if components.len() < 2 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }
        if components[0] > 2 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }
        if components[0] < 2 && components[1] >= 40 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }
        Ok(Self { components })
    }
}

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

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

        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()?;

        if len == 0 {
            return Err(crate::Error::InvalidOid {
                position: decoder.position(),
            });
        }

        let bytes = decoder.read_bytes(len)?;

        ObjectIdentifier::from_content_bytes(bytes).map_err(|_| crate::Error::InvalidOid {
            position: decoder.position(),
        })
    }
}

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

        if self.components.len() < 2 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }

        let tag = crate::Tag::universal(TAG_OBJECT_IDENTIFIER);
        encoder.write_tag(tag)?;
        let content = self.to_content_bytes();
        encoder.write_length(content.len())?;
        encoder.write_bytes(&content);
        Ok(())
    }

    fn encoded_len(&self) -> crate::Result<usize> {
        if self.components.len() < 2 {
            return Err(crate::Error::InvalidOid { position: 0 });
        }

        let tag_len = 1;

        // Calculate content length
        // First two components are combined as: first * 40 + second
        let first = self.components[0];
        let second = self.components[1];
        let combined = first * 40 + second;
        let mut content_len = base128_len(combined);

        // Add lengths of remaining components
        for &component in &self.components[2..] {
            content_len += base128_len(component);
        }

        let length_len = crate::Length::Definite(content_len).encoded_len()?;
        Ok(tag_len + length_len + content_len)
    }
}

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

// Helper function to encode a u32 in base-128
fn encode_base128(mut value: u32, buffer: &mut Vec<u8>) {
    if value == 0 {
        buffer.push(0);
        return;
    }

    // Collect bytes in reverse order
    let mut bytes = Vec::new();
    while value > 0 {
        bytes.push((value & 0x7F) as u8);
        value >>= 7;
    }

    // Write in correct order with high bit set on all but last
    for (i, &byte) in bytes.iter().rev().enumerate() {
        if i < bytes.len() - 1 {
            buffer.push(byte | 0x80);
        } else {
            buffer.push(byte);
        }
    }
}

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

/// `ObjectIdentifier` serializes as a dotted-decimal string (e.g. `"1.2.840.113549"`).
#[cfg(feature = "serde")]
impl serde::Serialize for ObjectIdentifier {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        use core::fmt::Write;
        let mut buf = String::new();
        for (i, &component) in self.components().iter().enumerate() {
            if i > 0 {
                buf.push('.');
            }
            let _ = write!(buf, "{}", component);
        }
        s.serialize_str(&buf)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for ObjectIdentifier {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct OidVisitor;
        impl<'de> serde::de::Visitor<'de> for OidVisitor {
            type Value = ObjectIdentifier;
            fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
                write!(f, "an OID in dotted-decimal notation (e.g. \"1.2.840\")")
            }
            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<ObjectIdentifier, E> {
                let components: Result<Vec<u32>, _> =
                    v.split('.').map(|p| p.parse::<u32>()).collect();
                let components = components.map_err(|_| E::custom("invalid OID component"))?;
                ObjectIdentifier::new(&components).map_err(|_| E::custom("invalid OID"))
            }
        }
        d.deserialize_str(OidVisitor)
    }
}

// Helper function to calculate base-128 encoded length
fn base128_len(value: u32) -> usize {
    if value == 0 {
        return 1;
    }

    let mut len = 0;
    let mut v = value;
    while v > 0 {
        len += 1;
        v >>= 7;
    }
    len
}

/// ASN.1 RELATIVE-OID
///
/// A RELATIVE-OID is a sequence of integer components (arcs) that identifies
/// an object relative to some other OID. Unlike OBJECT IDENTIFIER, a RELATIVE-OID
/// can have any number of components (including zero) and does not apply special
/// encoding to the first two components.
///
/// Uses SmallVec to avoid allocations for most RELATIVE-OIDs (< 10 components)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelativeOid {
    // Most RELATIVE-OIDs have fewer than 10 components
    components: SmallVec<[u32; 10]>,
}

impl RelativeOid {
    /// Create a new `RelativeOid` from a slice of component integers.
    ///
    /// Unlike OBJECT IDENTIFIER, RELATIVE-OID has no validation constraints
    /// on the component values or count. An empty RELATIVE-OID is valid.
    ///
    /// # Example
    ///
    /// ```
    /// use synta::RelativeOid;
    ///
    /// // Trust anchor ID suffix (e.g., "1" in "32473.1")
    /// let roid = RelativeOid::new(&[1]);
    /// assert_eq!(roid.to_string(), "1");
    ///
    /// // Empty RELATIVE-OID is valid
    /// let empty = RelativeOid::new(&[]);
    /// assert_eq!(empty.to_string(), "");
    /// ```
    pub fn new(components: &[u32]) -> Self {
        Self {
            components: SmallVec::from_slice(components),
        }
    }

    /// Return the RELATIVE-OID as a slice of component integers.
    ///
    /// # Example
    ///
    /// ```
    /// use synta::RelativeOid;
    ///
    /// let roid = RelativeOid::new(&[1, 2, 3]);
    /// assert!(matches!(roid.components(), [1, 2, 3]));
    /// ```
    pub fn components(&self) -> &[u32] {
        &self.components
    }

    /// Parse a RELATIVE-OID from its DER/BER **content** bytes — the raw value
    /// bytes inside a RELATIVE-OID TLV, with the tag (`0x0D`) and length already
    /// stripped.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidOid`](crate::Error::InvalidOid) if `data` contains
    /// a truncated base-128 sequence or causes a `u32` overflow in any component.
    ///
    /// # Example
    ///
    /// ```
    /// use synta::RelativeOid;
    ///
    /// // RELATIVE-OID with components [1, 2, 3]
    /// let roid = RelativeOid::from_content_bytes(&[0x01, 0x02, 0x03]).unwrap();
    /// assert_eq!(roid.to_string(), "1.2.3");
    /// ```
    pub fn from_content_bytes(data: &[u8]) -> crate::Result<Self> {
        let mut components: SmallVec<[u32; 10]> = SmallVec::new();
        let mut i = 0;

        // Each component is independently base-128 encoded
        while i < data.len() {
            let mut value: u32 = 0;
            loop {
                if i >= data.len() {
                    return Err(crate::Error::InvalidOid { position: i });
                }
                let byte = data[i];
                i += 1;
                value = value
                    .checked_mul(128)
                    .and_then(|v| v.checked_add((byte & 0x7F) as u32))
                    .ok_or(crate::Error::InvalidOid { position: i })?;
                if (byte & 0x80) == 0 {
                    break;
                }
            }
            components.push(value);
        }

        Ok(Self { components })
    }

    /// Encode this RELATIVE-OID as DER **content** bytes — the raw base-128 arc
    /// bytes without the `0x0D` tag byte or the length field.
    ///
    /// This is the symmetric counterpart to [`from_content_bytes`].
    ///
    /// [`from_content_bytes`]: Self::from_content_bytes
    ///
    /// # Example
    ///
    /// ```
    /// use synta::RelativeOid;
    ///
    /// let roid = RelativeOid::new(&[1, 2, 3]);
    /// assert_eq!(roid.to_content_bytes(), &[0x01, 0x02, 0x03]);
    /// // Round-trip
    /// assert_eq!(RelativeOid::from_content_bytes(&roid.to_content_bytes()).unwrap(), roid);
    /// ```
    pub fn to_content_bytes(&self) -> Vec<u8> {
        let mut out = Vec::new();
        for &component in &self.components {
            encode_base128(component, &mut out);
        }
        out
    }
}

// `Display` produces canonical dotted-decimal notation, e.g. `"1.2.3"`.
// Empty RELATIVE-OID displays as empty string.
impl core::fmt::Display for RelativeOid {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut iter = self.components.iter();
        if let Some(first) = iter.next() {
            write!(f, "{}", first)?;
            for component in iter {
                write!(f, ".{}", component)?;
            }
        }
        Ok(())
    }
}

// `FromStr` parses dotted-decimal notation (`"1.2.3"`) for RELATIVE-OID.
// Empty string is valid and produces an empty RELATIVE-OID.
#[cfg(feature = "std")]
impl core::str::FromStr for RelativeOid {
    type Err = crate::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.is_empty() {
            return Ok(Self {
                components: SmallVec::new(),
            });
        }

        let mut components: SmallVec<[u32; 10]> = SmallVec::new();
        for part in s.split('.') {
            let v: u32 = part
                .parse()
                .map_err(|_| crate::Error::InvalidOid { position: 0 })?;
            components.push(v);
        }
        Ok(Self { components })
    }
}

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

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

        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)?;

        RelativeOid::from_content_bytes(bytes).map_err(|_| crate::Error::InvalidOid {
            position: decoder.position(),
        })
    }
}

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

        let tag = crate::Tag::universal(TAG_RELATIVE_OID);
        encoder.write_tag(tag)?;
        let content = self.to_content_bytes();
        encoder.write_length(content.len())?;
        encoder.write_bytes(&content);
        Ok(())
    }

    fn encoded_len(&self) -> crate::Result<usize> {
        let tag_len = 1;

        // Calculate content length
        let mut content_len = 0;
        for &component in &self.components {
            content_len += base128_len(component);
        }

        let length_len = crate::Length::Definite(content_len).encoded_len()?;
        Ok(tag_len + length_len + content_len)
    }
}

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

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

/// `RelativeOid` serializes as a dotted-decimal string (e.g. `"1.2.3"`).
/// Empty RELATIVE-OID serializes as empty string `""`.
#[cfg(feature = "serde")]
impl serde::Serialize for RelativeOid {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        use core::fmt::Write;
        let mut buf = String::new();
        for (i, &component) in self.components().iter().enumerate() {
            if i > 0 {
                buf.push('.');
            }
            let _ = write!(buf, "{}", component);
        }
        s.serialize_str(&buf)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for RelativeOid {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct RoidVisitor;
        impl<'de> serde::de::Visitor<'de> for RoidVisitor {
            type Value = RelativeOid;
            fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
                write!(
                    f,
                    "a RELATIVE-OID in dotted-decimal notation (e.g. \"1.2.3\")"
                )
            }
            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<RelativeOid, E> {
                if v.is_empty() {
                    return Ok(RelativeOid::new(&[]));
                }
                let components: Result<Vec<u32>, _> =
                    v.split('.').map(|p| p.parse::<u32>()).collect();
                let components =
                    components.map_err(|_| E::custom("invalid RELATIVE-OID component"))?;
                Ok(RelativeOid::new(&components))
            }
        }
        d.deserialize_str(RoidVisitor)
    }
}