bgpkit-parser 0.25.0-beta.1

MRT/BGP/BMP data processing library
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
//! Borrowed attribute views over one element's attribute block.
//!
//! Each type here reads the bytes the record already holds and yields values on demand. The
//! iterators over a single attribute allocate nothing; the ones that merge or coalesce (`segments`)
//! reuse the owned model's inline storage and allocate only past it.

use super::*;

pub(super) fn wire_route_len(mut wire: &[u8]) -> usize {
    let mut total = 0usize;
    while wire.len() >= 2 {
        let seg_type = wire[0];
        let count = wire[1] as usize;
        match seg_type {
            AS_PATH_AS_SEQUENCE => total += count,
            AS_PATH_AS_SET => total += 1,
            _ => {}
        }
        wire = &wire[2 + count * 4..];
    }
    total
}

/// The global next hop of an `MP_REACH_NLRI` value.
///
/// The owned NLRI parser decides it: the families it accepts, the reserved octet, the next-hop
/// widths, and the RFC 6396 ยง4.3.4 rule that a dump's entry may omit the attribute's own address
/// family all behave here exactly as they do there. A body it rejects has no next hop, which is what
/// the owned element path reports too. It allocates the copied body and the prefix list it decodes.
pub(super) fn mp_reach_next_hop(
    value: &[u8],
    prefix: NetworkPrefix,
    afi: Afi,
    safi: Safi,
    add_path: bool,
    from_update: bool,
) -> Result<Option<IpAddr>, ()> {
    let prefix_list = [prefix];
    let (afi, safi, prefixes) = if from_update {
        (None, None, None)
    } else {
        (Some(afi), Some(safi), Some(&prefix_list[..]))
    };
    let decoded = crate::parser::bgp::attributes::parse_nlri(
        bytes::Bytes::copy_from_slice(value),
        &afi,
        &safi,
        &prefixes,
        true,
        add_path,
    )
    .map_err(|_| ())?;
    match decoded {
        crate::models::AttributeValue::MpReachNlri(nlri) => {
            Ok(nlri.next_hop.map(|next_hop| next_hop.global_addr()))
        }
        _ => Err(()),
    }
}

///////////////////////////////////////////////////////////////////////////////
// AS_PATH & Origin ASN Views
///////////////////////////////////////////////////////////////////////////////

#[derive(Clone, Copy, Debug)]
pub(super) enum AsPathSource<'a> {
    Absent,
    Single(&'a [u8]),
    Merged {
        as_path: &'a [u8],
        as4_path: &'a [u8],
    },
}

/// Segment kind in a wire `AS_PATH` attribute.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(super) enum AsPathSegmentType {
    AsSet,
    AsSequence,
    ConfedSequence,
    ConfedSet,
}

impl AsPathSegmentType {
    #[inline]
    fn from_wire(code: u8) -> Self {
        match code {
            AS_PATH_AS_SET => Self::AsSet,
            AS_PATH_AS_SEQUENCE => Self::AsSequence,
            AS_PATH_CONFED_SEQUENCE => Self::ConfedSequence,
            AS_PATH_CONFED_SET => Self::ConfedSet,
            // Every caller validates the path first, so this is unreachable today; a segment type
            // added later must not turn that into a panic.
            _ => Self::AsSequence,
        }
    }
}

/// Borrowed view over one segment in a wire `AS_PATH`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct AsPathSegmentRef<'a> {
    seg_type: AsPathSegmentType,
    asn_bytes: &'a [u8],
}

/// Zero-allocation borrowed view over an element's effective `AS_PATH`.
///
/// Iterating an `AsPathView` yields every [`Asn`] across its wire segments in order, expanding
/// `AS_SET` (and confederation) segments inline on the fly without allocating. Call
/// [`segments`](Self::segments) to inspect segment boundaries or [`to_vec`](Self::to_vec) to
/// materialise an owned `Vec<Asn>`.
#[derive(Clone, Copy, Debug)]
pub struct AsPathView<'a> {
    pub(super) source: AsPathSource<'a>,
}

impl<'a> AsPathView<'a> {
    /// Returns `true` if a valid `AS_PATH` (or `AS4_PATH`) attribute is present on the element
    /// (including an empty 0-segment iBGP `AS_PATH`).
    #[inline]
    pub fn is_present(&self) -> bool {
        !matches!(self.source, AsPathSource::Absent)
    }

    /// Returns `true` if the path yields no AS numbers.
    ///
    /// Not the same question as [`AsPath::is_empty`], which asks whether the path has no *segments*:
    /// a path made of one empty segment has a segment and no ASN. The name says which one this is.
    #[inline]
    pub fn has_no_asns(&self) -> bool {
        self.iter().next().is_none()
    }

    /// Returns the path's segments after the same RFC 6793 merge and coalesce the owned [`AsPath`]
    /// applies, so their boundaries match `elem.as_path` exactly.
    ///
    /// A single-segment path keeps its ASNs inline; a path with more than one segment, or with a
    /// segment of more than six ASNs, allocates for the part that does not fit.
    #[inline]
    pub fn segments(&self) -> crate::models::SegmentIntoIter {
        match self.to_as_path() {
            Some(path) => path.into_segments_iter(),
            None => AsPath::default().into_segments_iter(),
        }
    }

    /// The wire segments this path is made of, without merging or coalescing them.
    #[inline]
    fn wire_segments(&self) -> AsPathSegments<'a> {
        match self.source {
            AsPathSource::Absent => AsPathSegments {
                lead: &[],
                lead_remaining: 0,
                tail: &[],
            },
            AsPathSource::Single(wire) => AsPathSegments {
                lead: &[],
                lead_remaining: 0,
                tail: wire,
            },
            AsPathSource::Merged { as_path, as4_path } => {
                let lead_remaining = wire_route_len(as_path) - wire_route_len(as4_path);
                AsPathSegments {
                    lead: if lead_remaining > 0 { as_path } else { &[] },
                    lead_remaining,
                    tail: as4_path,
                }
            }
        }
    }

    /// Returns a zero-allocation iterator over all [`Asn`]s in the path, expanding `AS_SET`
    /// segments inline on the fly.
    #[inline]
    pub fn iter(&self) -> AsPathIter<'a> {
        match self.source {
            AsPathSource::Absent => AsPathIter {
                cur_words: &[],
                segs: AsPathSegments {
                    lead: &[],
                    lead_remaining: 0,
                    tail: &[],
                },
            },
            AsPathSource::Single(wire) => {
                if wire.len() >= 2 {
                    let count = wire[1] as usize;
                    let end = 2 + count * 4;
                    AsPathIter {
                        cur_words: bytes_as_be_u32_words(&wire[2..end]),
                        segs: AsPathSegments {
                            lead: &[],
                            lead_remaining: 0,
                            tail: &wire[end..],
                        },
                    }
                } else {
                    AsPathIter {
                        cur_words: &[],
                        segs: AsPathSegments {
                            lead: &[],
                            lead_remaining: 0,
                            tail: &[],
                        },
                    }
                }
            }
            AsPathSource::Merged { .. } => AsPathIter {
                cur_words: &[],
                segs: self.wire_segments(),
            },
        }
    }

    /// Materialises all [`Asn`]s in this path (with `AS_SET` expanded in wire order) into a `Vec`.
    pub fn to_vec(&self) -> Vec<Asn> {
        self.iter().collect()
    }

    /// Converts this view into an owned `Option<AsPath>` matching [`BgpElem::as_path`](crate::BgpElem::as_path).
    pub fn to_as_path(&self) -> Option<AsPath> {
        match self.source {
            AsPathSource::Absent => None,
            AsPathSource::Single(wire) => Some(wire_to_owned_as_path(wire)),
            AsPathSource::Merged { as_path, as4_path } => {
                let p1 = wire_to_owned_as_path(as_path);
                let p2 = wire_to_owned_as_path(as4_path);
                Some(AsPath::merge_aspath_as4path(&p1, &p2))
            }
        }
    }
}

fn wire_to_owned_as_path(wire: &[u8]) -> AsPath {
    let mut out = AsPath::new();
    let mut rest = wire;
    while rest.len() >= 2 {
        let code = rest[0];
        let count = rest[1] as usize;
        let end = 2 + count * 4;
        let asns = bytes_as_be_u32_words(&rest[2..end])
            .iter()
            .map(|w| Asn::new_32bit(w.get()))
            .collect();
        let seg = match code {
            AS_PATH_AS_SET => Some(AsPathSegment::AsSet(asns)),
            AS_PATH_AS_SEQUENCE => Some(AsPathSegment::AsSequence(asns)),
            AS_PATH_CONFED_SEQUENCE => Some(AsPathSegment::ConfedSequence(asns)),
            AS_PATH_CONFED_SET => Some(AsPathSegment::ConfedSet(asns)),
            // Validated before this runs, so this arm is unreachable today; skipping is safer than
            // panicking if a later segment type reaches here.
            _ => None,
        };
        if let Some(seg) = seg {
            out.append_segment(seg);
        }
        rest = &rest[end..];
    }
    out
}

impl<'a> IntoIterator for AsPathView<'a> {
    type Item = Asn;
    type IntoIter = AsPathIter<'a>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a> IntoIterator for &AsPathView<'a> {
    type Item = Asn;
    type IntoIter = AsPathIter<'a>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Iterator over borrowed [`AsPathSegmentRef`]s of an [`AsPathView`].
#[derive(Clone, Debug)]
pub(super) struct AsPathSegments<'a> {
    lead: &'a [u8],
    lead_remaining: usize,
    tail: &'a [u8],
}

impl<'a> Iterator for AsPathSegments<'a> {
    type Item = AsPathSegmentRef<'a>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.lead_remaining > 0 && self.lead.len() >= 2 {
            let code = self.lead[0];
            let count = self.lead[1] as usize;
            let end = 2 + count * 4;
            let full_asn_bytes = &self.lead[2..end];
            self.lead = &self.lead[end..];

            let seg_type = AsPathSegmentType::from_wire(code);
            let route_asns = match seg_type {
                AsPathSegmentType::AsSequence => count,
                AsPathSegmentType::AsSet => 1,
                AsPathSegmentType::ConfedSequence | AsPathSegmentType::ConfedSet => 0,
            };

            if route_asns <= self.lead_remaining {
                self.lead_remaining -= route_asns;
                if self.lead_remaining == 0 {
                    self.lead = &[];
                }
                return Some(AsPathSegmentRef {
                    seg_type,
                    asn_bytes: full_asn_bytes,
                });
            } else {
                // Only AS_SEQUENCE can straddle the leading count boundary (RFC 6793 ยง4.2.3).
                let take_bytes = self.lead_remaining * 4;
                self.lead_remaining = 0;
                self.lead = &[];
                return Some(AsPathSegmentRef {
                    seg_type,
                    asn_bytes: &full_asn_bytes[..take_bytes],
                });
            }
        }

        if self.tail.len() >= 2 {
            let code = self.tail[0];
            let count = self.tail[1] as usize;
            let end = 2 + count * 4;
            let asn_bytes = &self.tail[2..end];
            self.tail = &self.tail[end..];
            return Some(AsPathSegmentRef {
                seg_type: AsPathSegmentType::from_wire(code),
                asn_bytes,
            });
        }

        None
    }
}

/// Iterator over [`Asn`]s in an [`AsPathView`], expanding `AS_SET` segments on the fly.
#[derive(Clone, Debug)]
pub struct AsPathIter<'a> {
    cur_words: &'a [BeU32],
    segs: AsPathSegments<'a>,
}

impl<'a> Iterator for AsPathIter<'a> {
    type Item = Asn;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some((first, rest)) = self.cur_words.split_first() {
                self.cur_words = rest;
                return Some(Asn::new_32bit(first.get()));
            }
            let seg = self.segs.next()?;
            self.cur_words = bytes_as_be_u32_words(seg.asn_bytes);
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub(super) enum OriginsRepr<'a> {
    Absent,
    Empty,
    One(Asn),
    Set(&'a [BeU32]),
}

#[inline]
pub(super) fn single_wire_origins(wire: &[u8]) -> AsnsView<'_> {
    // Fast path (99.99% of RIB entries): single non-empty AS_SEQUENCE segment.
    if wire.len() >= 6 && wire[0] == AS_PATH_AS_SEQUENCE && 2 + (wire[1] as usize) * 4 == wire.len()
    {
        let last = wire.len() - 4;
        let asn = Asn::new_32bit(u32::from_be_bytes([
            wire[last],
            wire[last + 1],
            wire[last + 2],
            wire[last + 3],
        ]));
        return AsnsView {
            repr: OriginsRepr::One(asn),
        };
    }

    let mut rest = wire;
    let mut last_seg: Option<(u8, &[u8])> = None;
    while rest.len() >= 2 {
        let code = rest[0];
        let count = rest[1] as usize;
        let end = 2 + count * 4;
        last_seg = Some((code, &rest[2..end]));
        rest = &rest[end..];
    }

    let repr = match last_seg {
        Some((AS_PATH_AS_SEQUENCE, bytes)) if bytes.len() >= 4 => {
            let i = bytes.len() - 4;
            OriginsRepr::One(Asn::new_32bit(u32::from_be_bytes([
                bytes[i],
                bytes[i + 1],
                bytes[i + 2],
                bytes[i + 3],
            ])))
        }
        Some((AS_PATH_AS_SET, bytes)) if !bytes.is_empty() => {
            OriginsRepr::Set(bytes_as_be_u32_words(bytes))
        }
        _ => OriginsRepr::Empty,
    };
    AsnsView { repr }
}

/// Compute exact post-`coalesce()` origin ASNs of RFC 6793 merged `(as_path, as4_path)` without
/// allocating.
#[cold]
pub(super) fn merged_wire_origins<'a>(as_path: &'a [u8], as4_path: &'a [u8]) -> AsnsView<'a> {
    #[derive(Clone, Copy)]
    enum LastCoalesced<'b> {
        None,
        EmptySeq,
        NonEmptyAsSeq(Asn),
        NonEmptyConfedSeq,
        AsSet(&'b [BeU32]),
        ConfedSet,
    }

    let segs = AsPathSegments {
        lead: if wire_route_len(as_path) > wire_route_len(as4_path) {
            as_path
        } else {
            &[]
        },
        lead_remaining: wire_route_len(as_path) - wire_route_len(as4_path),
        tail: as4_path,
    };

    let mut state = LastCoalesced::None;
    for seg in segs {
        let next_state = match seg.seg_type {
            AsPathSegmentType::AsSequence => {
                if seg.asn_bytes.len() >= 4 {
                    let i = seg.asn_bytes.len() - 4;
                    LastCoalesced::NonEmptyAsSeq(Asn::new_32bit(u32::from_be_bytes([
                        seg.asn_bytes[i],
                        seg.asn_bytes[i + 1],
                        seg.asn_bytes[i + 2],
                        seg.asn_bytes[i + 3],
                    ])))
                } else {
                    LastCoalesced::EmptySeq
                }
            }
            AsPathSegmentType::ConfedSequence => {
                if seg.asn_bytes.is_empty() {
                    LastCoalesced::EmptySeq
                } else {
                    LastCoalesced::NonEmptyConfedSeq
                }
            }
            AsPathSegmentType::AsSet => LastCoalesced::AsSet(bytes_as_be_u32_words(seg.asn_bytes)),
            AsPathSegmentType::ConfedSet => LastCoalesced::ConfedSet,
        };

        // Mirrors `AsPathSegment::merge_in_place` in `AsPath::coalesce`.
        state = match (state, next_state) {
            (LastCoalesced::None, y) | (LastCoalesced::EmptySeq, y) => y,
            (x, LastCoalesced::EmptySeq) => x,
            (_, y) => y,
        };
    }

    let repr = match state {
        LastCoalesced::NonEmptyAsSeq(asn) => OriginsRepr::One(asn),
        LastCoalesced::AsSet(words) if !words.is_empty() => OriginsRepr::Set(words),
        _ => OriginsRepr::Empty,
    };
    AsnsView { repr }
}

/// Zero-allocation view over the originating ASNs of an element's `AS_PATH`.
#[derive(Clone, Copy, Debug)]
pub struct AsnsView<'a> {
    pub(super) repr: OriginsRepr<'a>,
}

impl<'a> AsnsView<'a> {
    /// Returns `true` when the element carries a valid `AS_PATH` (matching
    /// `elem.origin_asns.is_some()` on [`BgpElem`](crate::BgpElem)).
    #[inline]
    pub fn is_present(&self) -> bool {
        !matches!(self.repr, OriginsRepr::Absent)
    }

    /// Returns the number of originating ASNs (`0`, `1`, or the cardinality of a trailing
    /// `AS_SET`).
    #[inline]
    pub fn len(&self) -> usize {
        match self.repr {
            OriginsRepr::Absent | OriginsRepr::Empty => 0,
            OriginsRepr::One(_) => 1,
            OriginsRepr::Set(words) => words.len(),
        }
    }

    /// Returns `true` if there are zero originating ASNs.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns an iterator over the originating [`Asn`]s without allocating.
    #[inline]
    pub fn iter(&self) -> AsnsIter<'a> {
        AsnsIter { repr: self.repr }
    }

    /// Materialises the originating [`Asn`]s into a `Vec<Asn>`.
    pub fn to_vec(&self) -> Vec<Asn> {
        self.iter().collect()
    }
}

impl<'a> IntoIterator for AsnsView<'a> {
    type Item = Asn;
    type IntoIter = AsnsIter<'a>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a> IntoIterator for &AsnsView<'a> {
    type Item = Asn;
    type IntoIter = AsnsIter<'a>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Iterator over originating [`Asn`]s from [`AsnsView`].
#[derive(Clone, Debug)]
pub struct AsnsIter<'a> {
    repr: OriginsRepr<'a>,
}

impl<'a> Iterator for AsnsIter<'a> {
    type Item = Asn;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.repr {
            OriginsRepr::Absent | OriginsRepr::Empty => None,
            OriginsRepr::One(asn) => {
                let out = *asn;
                self.repr = OriginsRepr::Empty;
                Some(out)
            }
            OriginsRepr::Set(words) => {
                let (first, rest) = words.split_first()?;
                *words = rest;
                Some(Asn::new_32bit(first.get()))
            }
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = match self.repr {
            OriginsRepr::Absent | OriginsRepr::Empty => 0,
            OriginsRepr::One(_) => 1,
            OriginsRepr::Set(words) => words.len(),
        };
        (len, Some(len))
    }
}

impl ExactSizeIterator for AsnsIter<'_> {}

///////////////////////////////////////////////////////////////////////////////
// Communities View
///////////////////////////////////////////////////////////////////////////////

/// Cast a byte slice whose length is a multiple of 4 into a zero-copy slice of unaligned
/// network-byte-order 32-bit words (`zerocopy::big_endian::U32`) without `unsafe`.
///
/// If `bytes.len()` is not a multiple of 4, returns an empty slice.
#[inline]
pub(super) fn bytes_as_be_u32_words(bytes: &[u8]) -> &[BeU32] {
    if !bytes.len().is_multiple_of(4) {
        return &[];
    }
    <[BeU32]>::ref_from_bytes(bytes).unwrap_or(&[])
}

/// Borrowed view over an element's BGP community attributes (`COMMUNITIES`,
/// `EXTENDED_COMMUNITIES`, `IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES`, and
/// `LARGE_COMMUNITIES`).
///
/// Note on wire layout: BGP attributes in MRT bodies sit at arbitrary 1-byte alignments, store
/// integers in network byte order (big-endian), and split plain, extended, and large communities
/// across distinct TLV attributes. Consequently, a native `&[u32]` slice cannot borrow the wire
/// bytes directly on little-endian hosts without copying. Instead, `CommunitiesView` borrows the
/// attribute bytes directly and exposes a zero-allocation [`iter`](Self::iter) that decodes each
/// community in place.
#[derive(Clone, Copy, Debug)]
pub struct CommunitiesView<'a> {
    pub(super) attr_bytes: &'a [u8],
}

impl<'a> CommunitiesView<'a> {
    /// Returns `true` if the element carries no communities of any kind.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.iter().next().is_none()
    }

    /// Iterates over all [`MetaCommunity`] values in wire attribute order, matching
    /// [`BgpElem::communities`](crate::BgpElem::communities).
    #[inline]
    pub fn iter(&self) -> CommunitiesIter<'a> {
        CommunitiesIter {
            rest_attrs: self.attr_bytes,
            cur_kind: ActiveCommunityAttr::None,
        }
    }
}

impl<'a> IntoIterator for CommunitiesView<'a> {
    type Item = MetaCommunity;
    type IntoIter = CommunitiesIter<'a>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<'a> IntoIterator for &CommunitiesView<'a> {
    type Item = MetaCommunity;
    type IntoIter = CommunitiesIter<'a>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Where the next attribute in a block sits, or why the block cannot be walked further.
pub(super) enum AttrStep {
    /// The block ends here.
    End,
    /// The attribute whose header starts here declares more bytes than the block holds. `available`
    /// is what remains after its header.
    Truncated {
        code: u8,
        declared: usize,
        available: usize,
    },
    /// One attribute: its type code and the byte range of its value within the block.
    Attr {
        code: u8,
        value_start: usize,
        value_end: usize,
    },
}

/// How far into an attribute block a decoder can read, and what stopped it.
pub(super) enum AttrBlockScan {
    /// The block is usable up to `usable_len`. `truncated` is set when the attribute at that offset
    /// declares more bytes than the block holds: the owned walker keeps what it already read there.
    Usable {
        usable_len: usize,
        truncated: Option<(u8, usize, usize)>,
    },
    /// A header cannot be read at all, so the offset of the next attribute is unknown and the owned
    /// path fails the record.
    Unreadable,
}

/// Read an attribute block once, reporting where a decoder has to stop and why.
///
/// This is the only walk that decides where a block ends: `attribute_block_walks` asks it whether the
/// record survives, and an element takes its usable prefix from it, so the decode loop cannot
/// disagree with the gate that let the element exist.
pub(super) fn scan_attr_block(bytes: &[u8]) -> AttrBlockScan {
    let mut pos = 0usize;
    loop {
        // Fewer than three octets left: no header fits, and the owned walker accepts what it read.
        if pos + 3 > bytes.len() {
            return AttrBlockScan::Usable {
                usable_len: pos,
                truncated: None,
            };
        }
        // Three octets with the extended-length flag set cannot even name the header's length.
        if bytes[pos] & AttrFlags::EXTENDED.bits() != 0 && pos + 4 > bytes.len() {
            return AttrBlockScan::Unreadable;
        }
        match step_attr(bytes, pos) {
            AttrStep::End => {
                return AttrBlockScan::Usable {
                    usable_len: pos,
                    truncated: None,
                }
            }
            AttrStep::Truncated {
                code,
                declared,
                available,
            } => {
                return AttrBlockScan::Usable {
                    usable_len: pos,
                    truncated: Some((code, declared, available)),
                }
            }
            AttrStep::Attr { value_end, .. } => pos = value_end,
        }
    }
}

/// The type code, the offset the value starts at, and the offset it ends at, for the attribute at
/// `pos`, when it fits in the block.
pub(super) fn next_attr_bounds(bytes: &[u8], pos: usize) -> Option<(u8, usize, usize)> {
    match step_attr(bytes, pos) {
        AttrStep::Attr {
            code,
            value_start,
            value_end,
        } => Some((code, value_start, value_end)),
        AttrStep::Truncated { .. } | AttrStep::End => None,
    }
}

/// Decode the attribute header at `pos` without copying anything.
///
/// The block ends at a header that does not fit, which is how a block with a stray trailing byte or two
/// is read: the owned decoder accepts it and stops there too.
pub(super) fn step_attr(bytes: &[u8], pos: usize) -> AttrStep {
    if pos + 3 > bytes.len() {
        return AttrStep::End;
    }
    let flags = bytes[pos];
    let code = bytes[pos + 1];
    let (header_len, declared) = if (flags & AttrFlags::EXTENDED.bits()) == 0 {
        (3usize, bytes[pos + 2] as usize)
    } else {
        if pos + 4 > bytes.len() {
            return AttrStep::End;
        }
        (
            4usize,
            u16::from_be_bytes([bytes[pos + 2], bytes[pos + 3]]) as usize,
        )
    };
    let value_start = pos + header_len;
    let value_end = value_start + declared;
    if value_end > bytes.len() {
        return AttrStep::Truncated {
            code,
            declared,
            available: bytes.len() - value_start,
        };
    }
    AttrStep::Attr {
        code,
        value_start,
        value_end,
    }
}

#[inline]
pub(super) fn next_attr_tlv(bytes: &[u8]) -> Option<(u8, &[u8], &[u8])> {
    let (code, header_len, value_end) = next_attr_bounds(bytes, 0)?;
    Some((code, &bytes[header_len..value_end], &bytes[value_end..]))
}

#[derive(Clone, Debug)]
enum ActiveCommunityAttr<'a> {
    None,
    Plain(&'a [BeU32]),
    Extended(&'a [u8]),
    Ipv6Extended(&'a [u8]),
    Large(&'a [BeU32]),
}

/// Iterator over all [`MetaCommunity`] items in wire attribute order.
#[derive(Clone, Debug)]
pub struct CommunitiesIter<'a> {
    rest_attrs: &'a [u8],
    cur_kind: ActiveCommunityAttr<'a>,
}

impl Iterator for CommunitiesIter<'_> {
    type Item = MetaCommunity;

    #[inline]
    fn next(&mut self) -> Option<MetaCommunity> {
        loop {
            match &mut self.cur_kind {
                ActiveCommunityAttr::Plain(words) => {
                    if let Some((first, rest)) = words.split_first() {
                        *words = rest;
                        return Some(MetaCommunity::Plain(
                            crate::parser::bgp::attributes::decode_regular_community(first.get()),
                        ));
                    }
                }
                ActiveCommunityAttr::Extended(bytes) => {
                    if bytes.len() >= 8 {
                        let mut chunk = &bytes[..8];
                        *bytes = &bytes[8..];
                        return Some(MetaCommunity::Extended(
                            crate::parser::bgp::attributes::parse_extended_community_one(
                                &mut chunk,
                            )
                            .unwrap_or(ExtendedCommunity::Raw([0u8; 8])),
                        ));
                    }
                }
                ActiveCommunityAttr::Ipv6Extended(bytes) => {
                    if bytes.len() >= 20 {
                        let mut chunk = &bytes[..20];
                        *bytes = &bytes[20..];
                        if let Ok(item) =
                            crate::parser::bgp::attributes::parse_ipv6_extended_community_one(
                                &mut chunk,
                            )
                        {
                            return Some(MetaCommunity::Ipv6Extended(item));
                        }
                    }
                }
                ActiveCommunityAttr::Large(words) => {
                    if words.len() >= 3 {
                        let ga = words[0].get();
                        let d0 = words[1].get();
                        let d1 = words[2].get();
                        *words = &words[3..];
                        return Some(MetaCommunity::Large(LargeCommunity::new(ga, [d0, d1])));
                    }
                }
                ActiveCommunityAttr::None => {}
            }

            self.cur_kind = ActiveCommunityAttr::None;
            let (code, val, next_rest) = next_attr_tlv(self.rest_attrs)?;
            self.rest_attrs = next_rest;
            match AttrType::from(code) {
                AttrType::COMMUNITIES if val.len().is_multiple_of(4) => {
                    self.cur_kind = ActiveCommunityAttr::Plain(bytes_as_be_u32_words(val));
                }
                AttrType::EXTENDED_COMMUNITIES if val.len().is_multiple_of(8) => {
                    self.cur_kind = ActiveCommunityAttr::Extended(val);
                }
                AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES
                    if val.len().is_multiple_of(20) =>
                {
                    self.cur_kind = ActiveCommunityAttr::Ipv6Extended(val);
                }
                AttrType::LARGE_COMMUNITIES if val.len().is_multiple_of(12) => {
                    self.cur_kind = ActiveCommunityAttr::Large(bytes_as_be_u32_words(val));
                }
                _ => {}
            }
        }
    }
}