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
//! Lazy ASN.1 SEQUENCE OF and SET OF types
//!
//! These types implement lazy iteration over ASN.1 sequences, avoiding
//! the memory allocation overhead of `Vec<T>` for better performance.

use core::marker::PhantomData;

#[cfg(not(feature = "std"))]
use alloc::{boxed::Box, vec::Vec};

use crate::der::decoder::Decoder;
use crate::error::{Error, Result};
use crate::traits::{Decode, Encode};
use crate::{Encoding, Length, Tag};

/// ASN.1 SEQUENCE OF type with lazy iteration
///
/// This type stores a reference to the encoded bytes and decodes elements
/// on-demand during iteration, avoiding the memory allocation overhead of
/// eagerly parsing all elements into a Vec.
///
/// # Performance
///
/// Compared to `Vec<T>`:
/// - Zero allocation on parse
/// - Lazy element decoding
/// - Cheap to clone when borrowed (just copies references); allocates when owned
/// - Ideal for cases where you iterate once or skip some elements
///
/// # Example
///
/// ```ignore
/// use synta::{Decoder, Encoding};
/// use synta::types::SequenceOf;
///
/// let mut decoder = Decoder::new(&bytes, Encoding::Der);
/// let seq: SequenceOf<Integer> = decoder.decode()?;
///
/// // Elements decoded only when iterated
/// for element in seq {
///     println!("{:?}", element);
/// }
/// ```
pub struct SequenceOf<'a, T> {
    /// Owned backing buffer, present when constructed via `from_vec` /
    /// `try_from_iter`.  The slices below point into this allocation.
    /// `Box<[u8]>` heap data is stable across moves, so the raw pointers
    /// in `full_content` and `remaining` remain valid after the struct is moved.
    owner: Option<Box<[u8]>>,
    /// The full encoded content of the SEQUENCE OF
    full_content: &'a [u8],
    /// The remaining content to parse (advances during iteration)
    remaining: &'a [u8],
    /// The encoding type (DER/BER/CER)
    encoding: Encoding,
    /// Number of elements in the sequence (pre-computed)
    length: usize,
    /// Number of elements already consumed
    consumed: usize,
    /// Phantom data for the element type
    _phantom: PhantomData<T>,
}

impl<'a, T> core::fmt::Debug for SequenceOf<'a, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("SequenceOf")
            .field("full_content", &self.full_content)
            .field("remaining", &self.remaining)
            .field("encoding", &self.encoding)
            .field("length", &self.length)
            .field("consumed", &self.consumed)
            .finish()
    }
}

impl<'a, T> SequenceOf<'a, T>
where
    T: Decode<'a>,
{
    /// Create a new SequenceOf from encoded content
    ///
    /// This pre-scans the content to count elements but doesn't decode them.
    pub(crate) fn new(content: &'a [u8], encoding: Encoding) -> Result<Self> {
        // Pre-scan to count elements
        let length = Self::count_elements(content, encoding)?;

        Ok(Self {
            owner: None,
            full_content: content,
            remaining: content,
            encoding,
            length,
            consumed: 0,
            _phantom: PhantomData,
        })
    }

    /// Count the number of elements without decoding them.
    ///
    /// Uses a skip-only scan: read tag + length, advance cursor by `len` bytes.
    /// No element construction, no allocations for OID components or strings.
    fn count_elements(content: &'a [u8], encoding: Encoding) -> Result<usize> {
        let mut decoder = Decoder::new(content, encoding);
        let mut count = 0;

        while !decoder.is_empty() {
            // Consume the tag — a few bytes, no allocation.
            decoder.read_tag()?;
            // Consume the length field.
            let length = decoder.read_length()?;
            // Skip the content bytes without decoding them.
            match length {
                Length::Definite(len) => {
                    decoder.read_bytes(len)?;
                }
                Length::Indefinite => {
                    // BER/CER only; DER rejects indefinite lengths in read_length().
                    decoder.read_indefinite_content()?;
                }
            }
            count += 1;
        }

        Ok(count)
    }

    /// Get the number of remaining elements in the sequence
    ///
    /// This returns the number of elements that have not yet been consumed
    /// by iteration. If the sequence has not been iterated, this equals the
    /// total number of elements.
    pub fn len(&self) -> usize {
        self.length - self.consumed
    }

    /// Check if there are no remaining elements
    pub fn is_empty(&self) -> bool {
        self.consumed >= self.length
    }

    /// Collect all **remaining** elements into a `Vec`.
    ///
    /// This eagerly decodes every element that has not yet been consumed by
    /// iteration, allocating a `Vec`.  If the sequence has been partially
    /// iterated, only the remaining elements are collected; elements already
    /// yielded by `next()` are not included.
    ///
    /// Use [`reset`](Self::reset) before calling this method if you want to
    /// collect from the beginning regardless of the current iterator position.
    pub fn collect_vec(self) -> Result<Vec<T>> {
        let mut result = Vec::with_capacity(self.length);
        for element in self {
            result.push(element);
        }
        Ok(result)
    }

    /// Reset the iterator to the beginning
    pub fn reset(&mut self) {
        self.remaining = self.full_content;
        self.consumed = 0;
    }

    /// Return the raw DER content bytes of this sequence.
    ///
    /// The returned slice is borrowed directly from the original input and
    /// carries lifetime `'a`.  It contains the serialized elements without
    /// the outer SEQUENCE tag or length prefix.
    ///
    /// To obtain the full TLV (tag + length + content), either re-encode via
    /// the [`Encode`] trait or manually prepend the
    /// appropriate SEQUENCE header to the returned slice.
    pub fn content_bytes(&self) -> &'a [u8] {
        self.full_content
    }
}

// Construction API - separate impl block for 'static lifetime
impl<T> SequenceOf<'static, T>
where
    T: Decode<'static> + Encode,
{
    /// Create a SequenceOf from a Vec of elements (for testing/construction)
    ///
    /// Encodes the elements to DER bytes and stores the resulting buffer
    /// inside the returned [`SequenceOf`].  The buffer is freed when the
    /// value is dropped; no memory is leaked.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use synta::types::SequenceOf;
    /// use synta::types::primitive::Integer;
    ///
    /// let elements = vec![Integer::from(1), Integer::from(2), Integer::from(3)];
    /// let seq = SequenceOf::from_vec(elements).unwrap();
    ///
    /// assert_eq!(seq.len(), 3);
    /// ```
    pub fn from_vec(elements: Vec<T>) -> Result<SequenceOf<'static, T>> {
        use crate::tag::TAG_SEQUENCE;
        use crate::Encoder;

        let tag = Tag::universal_constructed(TAG_SEQUENCE);

        // Encode all elements into a full SEQUENCE OF TLV.
        let mut encoder = Encoder::new(Encoding::Der);
        encoder.write_tag(tag)?;

        let mut content_encoder = Encoder::new(Encoding::Der);
        for element in &elements {
            content_encoder.encode(element)?;
        }
        let content = content_encoder.finish()?;
        encoder.write_length(content.len())?;
        encoder.write_bytes(&content);

        let boxed: Box<[u8]> = encoder.finish()?.into_boxed_slice();

        // Locate the content within the encoded TLV (skip tag + length header).
        let (content_offset, content_len) = {
            let mut tmp = crate::Decoder::new(&boxed, Encoding::Der);
            let read_tag = tmp.read_tag()?;
            if read_tag != tag {
                return Err(crate::Error::UnexpectedTag {
                    expected: tag,
                    actual: read_tag,
                    position: 0,
                });
            }
            let len = match tmp.read_length()? {
                crate::Length::Definite(n) => n,
                crate::Length::Indefinite => {
                    return Err(crate::Error::IndefiniteLengthInDer { position: 0 });
                }
            };
            (tmp.position(), len)
        };

        // SAFETY: `boxed` is moved into `owner` and its heap allocation is
        // stable (moving a `Box<[u8]>` does not relocate the backing data).
        // The `SequenceOf<'static, T>` return type guarantees the struct can
        // live for `'static`, so the `&'static` references are valid for as
        // long as the struct – which owns the allocation – exists.
        // Fields `full_content` and `remaining` are never accessed after
        // `owner` is dropped (they are all part of the same struct).
        let content_slice: &'static [u8] =
            unsafe { core::slice::from_raw_parts(boxed.as_ptr().add(content_offset), content_len) };

        let element_count = Self::count_elements(content_slice, Encoding::Der)?;

        Ok(SequenceOf {
            owner: Some(boxed),
            full_content: content_slice,
            remaining: content_slice,
            encoding: Encoding::Der,
            length: element_count,
            consumed: 0,
            _phantom: PhantomData,
        })
    }

    /// Create a SequenceOf from an iterator (for testing/construction)
    ///
    /// Convenience wrapper around [`from_vec`](Self::from_vec) that collects
    /// the iterator into a `Vec` first.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use synta::types::SequenceOf;
    /// use synta::types::primitive::Integer;
    ///
    /// let seq = SequenceOf::try_from_iter((1..=5).map(Integer::from)).unwrap();
    /// assert_eq!(seq.len(), 5);
    /// ```
    pub fn try_from_iter<I>(iter: I) -> Result<SequenceOf<'static, T>>
    where
        I: IntoIterator<Item = T>,
    {
        Self::from_vec(iter.into_iter().collect())
    }
}

// Manually implement Clone - we don't need T: Clone since we only store references
impl<'a, T> Clone for SequenceOf<'a, T> {
    fn clone(&self) -> Self {
        match &self.owner {
            None => {
                // Borrowed: just copy the references.
                SequenceOf {
                    owner: None,
                    full_content: self.full_content,
                    remaining: self.remaining,
                    encoding: self.encoding,
                    length: self.length,
                    consumed: self.consumed,
                    _phantom: PhantomData,
                }
            }
            Some(old_box) => {
                // Owned: clone the heap data and re-derive the slice references
                // into the new allocation at the same byte offsets.
                //
                // SAFETY: `full_content` and `remaining` were derived from
                // `old_box`, so their byte offsets relative to `old_box.as_ptr()`
                // are valid indices.  We apply the same offsets to `new_box`.
                // `new_box` is immediately stored in `owner` so it outlives the
                // references.
                let new_box = old_box.clone();
                let old_base = old_box.as_ptr() as usize;
                let full_content_offset = self.full_content.as_ptr() as usize - old_base;
                let remaining_offset = self.remaining.as_ptr() as usize - old_base;
                let new_full_content: &'static [u8] = unsafe {
                    core::slice::from_raw_parts(
                        new_box.as_ptr().add(full_content_offset),
                        self.full_content.len(),
                    )
                };
                let new_remaining: &'static [u8] = unsafe {
                    core::slice::from_raw_parts(
                        new_box.as_ptr().add(remaining_offset),
                        self.remaining.len(),
                    )
                };
                SequenceOf {
                    owner: Some(new_box),
                    full_content: new_full_content,
                    remaining: new_remaining,
                    encoding: self.encoding,
                    length: self.length,
                    consumed: self.consumed,
                    _phantom: PhantomData,
                }
            }
        }
    }
}

impl<'a, T> Iterator for SequenceOf<'a, T>
where
    T: Decode<'a>,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.consumed >= self.length {
            return None;
        }

        // Create a decoder for the remaining content
        let mut decoder = Decoder::new(self.remaining, self.encoding);

        // Decode the next element
        let element = match T::decode(&mut decoder) {
            Ok(el) => el,
            Err(_) => return None,
        };

        // Update remaining to point past the decoded element
        self.remaining = decoder.remaining();
        self.consumed += 1;

        Some(element)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.length - self.consumed;
        (remaining, Some(remaining))
    }
}

impl<'a, T> ExactSizeIterator for SequenceOf<'a, T>
where
    T: Decode<'a>,
{
    fn len(&self) -> usize {
        self.length - self.consumed
    }
}

impl<'a, T> Decode<'a> for SequenceOf<'a, T>
where
    T: Decode<'a>,
{
    fn decode(decoder: &mut Decoder<'a>) -> Result<Self> {
        use crate::tag::TAG_SEQUENCE;

        let tag = Tag::universal_constructed(TAG_SEQUENCE);

        // Read the tag and length
        let read_tag = decoder.read_tag()?;
        if read_tag != tag {
            return Err(Error::UnexpectedTag {
                expected: tag,
                actual: read_tag,
                position: decoder.position(),
            });
        }

        let length = decoder.read_length()?;
        let content = match length {
            crate::Length::Definite(len) => decoder.read_bytes(len)?,
            crate::Length::Indefinite => {
                return Err(Error::IndefiniteLengthInDer {
                    position: decoder.position(),
                });
            }
        };

        SequenceOf::new(content, decoder.encoding())
    }
}

impl<'a, T> Encode for SequenceOf<'a, T>
where
    T: Decode<'a> + Encode,
{
    fn encode(&self, encoder: &mut crate::Encoder) -> Result<()> {
        use crate::tag::TAG_SEQUENCE;

        let tag = Tag::universal_constructed(TAG_SEQUENCE);
        encoder.write_tag(tag)?;

        // full_content already holds the verbatim DER of all elements.
        // Write length + content directly — no clone, decode, or re-encode needed.
        encoder.write_length(self.full_content.len())?;
        encoder.write_bytes(self.full_content);

        Ok(())
    }

    fn encoded_len(&self) -> Result<usize> {
        // Tag (1 byte) + length encoding + content length
        let content_len = self.full_content.len();
        let tag_len = 1;
        let length_len = crate::Length::Definite(content_len).encoded_len()?;

        Ok(tag_len + length_len + content_len)
    }
}

impl<'a, T> crate::traits::Tagged for SequenceOf<'a, T> {
    fn tag() -> Tag {
        use crate::tag::TAG_SEQUENCE;
        Tag::universal_constructed(TAG_SEQUENCE)
    }
}

// Implement PartialEq by comparing elements
impl<'a, T> PartialEq for SequenceOf<'a, T>
where
    T: Decode<'a> + PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        if self.len() != other.len() {
            return false;
        }

        let mut it1 = self.clone();
        let mut it2 = other.clone();

        while let (Some(v1), Some(v2)) = (it1.next(), it2.next()) {
            if v1 != v2 {
                return false;
            }
        }

        true
    }
}

impl<'a, T> Eq for SequenceOf<'a, T> where T: Decode<'a> + Eq {}

/// ASN.1 SET OF type with lazy iteration.
///
/// This is currently a type alias for [`SequenceOf`].  **As a consequence its
/// `Decode` implementation accepts the SEQUENCE tag (`0x30`) and will reject
/// actual SET OF data encoded with the SET tag (`0x11`).**  It also does not
/// verify or enforce DER's requirement that SET OF elements are sorted.
///
/// Use this type only when the underlying encoding uses `0x30` (e.g. when an
/// outer IMPLICIT tag overrides the outer tag and the inner structure is decoded
/// as a sequence).  For genuine `SET OF` fields that carry the `0x11` tag, a
/// dedicated type with a `TAG_SET` check in its `Decode` implementation is
/// needed.
pub type SetOf<'a, T> = SequenceOf<'a, T>;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::primitive::Integer;

    #[test]
    fn test_sequenceof_from_vec() {
        // Create a SequenceOf from a Vec of integers
        let elements = vec![
            Integer::from(1),
            Integer::from(2),
            Integer::from(3),
            Integer::from(42),
            Integer::from(100),
        ];

        let seq = SequenceOf::from_vec(elements.clone()).unwrap();

        // Check length
        assert_eq!(seq.len(), 5);
        assert!(!seq.is_empty());

        // Iterate and verify elements
        let collected: Vec<_> = seq.collect_vec().unwrap();
        assert_eq!(collected.len(), 5);
        assert_eq!(collected[0], Integer::from(1));
        assert_eq!(collected[1], Integer::from(2));
        assert_eq!(collected[2], Integer::from(3));
        assert_eq!(collected[3], Integer::from(42));
        assert_eq!(collected[4], Integer::from(100));
    }

    #[test]
    fn test_sequenceof_from_iter() {
        // Create from an iterator
        let seq = SequenceOf::try_from_iter((1..=5).map(Integer::from)).unwrap();

        assert_eq!(seq.len(), 5);

        // Verify iteration
        let values: Vec<_> = seq.map(|i| i.as_i64().unwrap()).collect();
        assert_eq!(values, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_sequenceof_empty() {
        let seq = SequenceOf::<Integer>::from_vec(vec![]).unwrap();

        assert_eq!(seq.len(), 0);
        assert!(seq.is_empty());

        let collected = seq.collect_vec().unwrap();
        assert_eq!(collected.len(), 0);
    }

    #[test]
    fn test_sequenceof_iteration_multiple_times() {
        let elements = vec![Integer::from(10), Integer::from(20), Integer::from(30)];
        let mut seq = SequenceOf::from_vec(elements).unwrap();

        // First iteration
        let first: Vec<_> = seq.clone().collect_vec().unwrap();
        assert_eq!(first.len(), 3);

        // Reset and iterate again
        seq.reset();
        let second: Vec<_> = seq.collect_vec().unwrap();
        assert_eq!(second, first);
    }

    #[test]
    fn test_sequenceof_size_hint() {
        let seq = SequenceOf::try_from_iter((1..=10).map(Integer::from)).unwrap();

        assert_eq!(seq.len(), 10);
        assert_eq!(seq.size_hint(), (10, Some(10)));

        let mut iter = seq;
        iter.next(); // Consume one element
        assert_eq!(iter.size_hint(), (9, Some(9)));
        assert_eq!(iter.len(), 9); // ExactSizeIterator::len
    }

    #[test]
    fn test_sequenceof_partial_iteration() {
        let seq = SequenceOf::try_from_iter((1..=5).map(Integer::from)).unwrap();

        let mut iter = seq;
        assert_eq!(iter.next().unwrap().as_i64().unwrap(), 1);
        assert_eq!(iter.next().unwrap().as_i64().unwrap(), 2);

        // Stop iteration early
        assert_eq!(iter.len(), 3); // 3 remaining
    }

    #[test]
    fn test_sequenceof_encode_decode_roundtrip() {
        use crate::{Decoder, Encoder, Encoding};

        let original = vec![Integer::from(7), Integer::from(14), Integer::from(21)];
        let seq = SequenceOf::from_vec(original.clone()).unwrap();

        // Encode the SequenceOf
        let mut encoder = Encoder::new(Encoding::Der);
        encoder.encode(&seq).unwrap();
        let encoded = encoder.finish().unwrap();

        // Decode it back
        let mut decoder = Decoder::new(&encoded, Encoding::Der);
        let decoded: SequenceOf<Integer> = decoder.decode().unwrap();

        // Verify
        let decoded_vec = decoded.collect_vec().unwrap();
        assert_eq!(decoded_vec, original);
    }

    #[test]
    fn test_sequenceof_equality() {
        let seq1 = SequenceOf::from_vec(vec![Integer::from(1), Integer::from(2)]).unwrap();
        let seq2 = SequenceOf::from_vec(vec![Integer::from(1), Integer::from(2)]).unwrap();
        let seq3 = SequenceOf::from_vec(vec![Integer::from(1), Integer::from(3)]).unwrap();

        assert_eq!(seq1, seq2);
        assert_ne!(seq1, seq3);
    }

    #[test]
    fn test_sequenceof_content_bytes() {
        use crate::{Decoder, Encoder, Encoding};

        // Encode a SequenceOf so we have a known DER representation.
        let elements = vec![Integer::from(1), Integer::from(2), Integer::from(3)];
        let seq = SequenceOf::from_vec(elements).unwrap();

        // Re-encode to DER to capture the full TLV.
        let mut encoder = Encoder::new(Encoding::Der);
        encoder.encode(&seq).unwrap();
        let full_tlv = encoder.finish().unwrap();

        // Parse back so we have a SequenceOf borrowed from `full_tlv`.
        let mut decoder = Decoder::new(&full_tlv, Encoding::Der);
        let parsed: SequenceOf<Integer> = decoder.decode().unwrap();

        // content_bytes() must equal the content portion of the TLV
        // (i.e., full_tlv without the outer 0x30 tag byte and length byte).
        let content = parsed.content_bytes();
        assert!(!content.is_empty());
        assert_eq!(
            &full_tlv[2..],
            content,
            "content_bytes must match TLV content"
        );

        // Sanity: re-encoding content_bytes with a SEQUENCE header must
        // reproduce the original TLV.
        let mut reconstructed = Vec::new();
        reconstructed.push(0x30u8); // SEQUENCE tag
        reconstructed.push(content.len() as u8); // short-form length (content is small)
        reconstructed.extend_from_slice(content);
        assert_eq!(reconstructed, full_tlv);
    }
}