Skip to main content

bgpkit_parser/parser/iters/elem_ref/
view.rs

1//! Borrowed attribute views over one element's attribute block.
2//!
3//! Each type here reads the bytes the record already holds and yields values on demand. The
4//! iterators over a single attribute allocate nothing; the ones that merge or coalesce (`segments`)
5//! reuse the owned model's inline storage and allocate only past it.
6
7use super::*;
8
9pub(super) fn wire_route_len(mut wire: &[u8]) -> usize {
10    let mut total = 0usize;
11    while wire.len() >= 2 {
12        let seg_type = wire[0];
13        let count = wire[1] as usize;
14        match seg_type {
15            AS_PATH_AS_SEQUENCE => total += count,
16            AS_PATH_AS_SET => total += 1,
17            _ => {}
18        }
19        wire = &wire[2 + count * 4..];
20    }
21    total
22}
23
24/// The global next hop of an `MP_REACH_NLRI` value.
25///
26/// The owned NLRI parser decides it: the families it accepts, the reserved octet, the next-hop
27/// widths, and the RFC 6396 §4.3.4 rule that a dump's entry may omit the attribute's own address
28/// family all behave here exactly as they do there. A body it rejects has no next hop, which is what
29/// the owned element path reports too. It allocates the copied body and the prefix list it decodes.
30pub(super) fn mp_reach_next_hop(
31    value: &[u8],
32    prefix: NetworkPrefix,
33    afi: Afi,
34    safi: Safi,
35    add_path: bool,
36    from_update: bool,
37) -> Result<Option<IpAddr>, ()> {
38    let prefix_list = [prefix];
39    let (afi, safi, prefixes) = if from_update {
40        (None, None, None)
41    } else {
42        (Some(afi), Some(safi), Some(&prefix_list[..]))
43    };
44    let decoded = crate::parser::bgp::attributes::parse_nlri(
45        bytes::Bytes::copy_from_slice(value),
46        &afi,
47        &safi,
48        &prefixes,
49        true,
50        add_path,
51    )
52    .map_err(|_| ())?;
53    match decoded {
54        crate::models::AttributeValue::MpReachNlri(nlri) => {
55            Ok(nlri.next_hop.map(|next_hop| next_hop.global_addr()))
56        }
57        _ => Err(()),
58    }
59}
60
61///////////////////////////////////////////////////////////////////////////////
62// AS_PATH & Origin ASN Views
63///////////////////////////////////////////////////////////////////////////////
64
65#[derive(Clone, Copy, Debug)]
66pub(super) enum AsPathSource<'a> {
67    Absent,
68    Single(&'a [u8]),
69    Merged {
70        as_path: &'a [u8],
71        as4_path: &'a [u8],
72    },
73}
74
75/// Segment kind in a wire `AS_PATH` attribute.
76#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
77pub(super) enum AsPathSegmentType {
78    AsSet,
79    AsSequence,
80    ConfedSequence,
81    ConfedSet,
82}
83
84impl AsPathSegmentType {
85    #[inline]
86    fn from_wire(code: u8) -> Self {
87        match code {
88            AS_PATH_AS_SET => Self::AsSet,
89            AS_PATH_AS_SEQUENCE => Self::AsSequence,
90            AS_PATH_CONFED_SEQUENCE => Self::ConfedSequence,
91            AS_PATH_CONFED_SET => Self::ConfedSet,
92            // Every caller validates the path first, so this is unreachable today; a segment type
93            // added later must not turn that into a panic.
94            _ => Self::AsSequence,
95        }
96    }
97}
98
99/// Borrowed view over one segment in a wire `AS_PATH`.
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub(super) struct AsPathSegmentRef<'a> {
102    seg_type: AsPathSegmentType,
103    asn_bytes: &'a [u8],
104}
105
106/// Zero-allocation borrowed view over an element's effective `AS_PATH`.
107///
108/// Iterating an `AsPathView` yields every [`Asn`] across its wire segments in order, expanding
109/// `AS_SET` (and confederation) segments inline on the fly without allocating. Call
110/// [`segments`](Self::segments) to inspect segment boundaries or [`to_vec`](Self::to_vec) to
111/// materialise an owned `Vec<Asn>`.
112#[derive(Clone, Copy, Debug)]
113pub struct AsPathView<'a> {
114    pub(super) source: AsPathSource<'a>,
115}
116
117impl<'a> AsPathView<'a> {
118    /// Returns `true` if a valid `AS_PATH` (or `AS4_PATH`) attribute is present on the element
119    /// (including an empty 0-segment iBGP `AS_PATH`).
120    #[inline]
121    pub fn is_present(&self) -> bool {
122        !matches!(self.source, AsPathSource::Absent)
123    }
124
125    /// Returns `true` if the path yields no AS numbers.
126    ///
127    /// Not the same question as [`AsPath::is_empty`], which asks whether the path has no *segments*:
128    /// a path made of one empty segment has a segment and no ASN. The name says which one this is.
129    #[inline]
130    pub fn has_no_asns(&self) -> bool {
131        self.iter().next().is_none()
132    }
133
134    /// Returns the path's segments after the same RFC 6793 merge and coalesce the owned [`AsPath`]
135    /// applies, so their boundaries match `elem.as_path` exactly.
136    ///
137    /// A single-segment path keeps its ASNs inline; a path with more than one segment, or with a
138    /// segment of more than six ASNs, allocates for the part that does not fit.
139    #[inline]
140    pub fn segments(&self) -> crate::models::SegmentIntoIter {
141        match self.to_as_path() {
142            Some(path) => path.into_segments_iter(),
143            None => AsPath::default().into_segments_iter(),
144        }
145    }
146
147    /// The wire segments this path is made of, without merging or coalescing them.
148    #[inline]
149    fn wire_segments(&self) -> AsPathSegments<'a> {
150        match self.source {
151            AsPathSource::Absent => AsPathSegments {
152                lead: &[],
153                lead_remaining: 0,
154                tail: &[],
155            },
156            AsPathSource::Single(wire) => AsPathSegments {
157                lead: &[],
158                lead_remaining: 0,
159                tail: wire,
160            },
161            AsPathSource::Merged { as_path, as4_path } => {
162                let lead_remaining = wire_route_len(as_path) - wire_route_len(as4_path);
163                AsPathSegments {
164                    lead: if lead_remaining > 0 { as_path } else { &[] },
165                    lead_remaining,
166                    tail: as4_path,
167                }
168            }
169        }
170    }
171
172    /// Returns a zero-allocation iterator over all [`Asn`]s in the path, expanding `AS_SET`
173    /// segments inline on the fly.
174    #[inline]
175    pub fn iter(&self) -> AsPathIter<'a> {
176        match self.source {
177            AsPathSource::Absent => AsPathIter {
178                cur_words: &[],
179                segs: AsPathSegments {
180                    lead: &[],
181                    lead_remaining: 0,
182                    tail: &[],
183                },
184            },
185            AsPathSource::Single(wire) => {
186                if wire.len() >= 2 {
187                    let count = wire[1] as usize;
188                    let end = 2 + count * 4;
189                    AsPathIter {
190                        cur_words: bytes_as_be_u32_words(&wire[2..end]),
191                        segs: AsPathSegments {
192                            lead: &[],
193                            lead_remaining: 0,
194                            tail: &wire[end..],
195                        },
196                    }
197                } else {
198                    AsPathIter {
199                        cur_words: &[],
200                        segs: AsPathSegments {
201                            lead: &[],
202                            lead_remaining: 0,
203                            tail: &[],
204                        },
205                    }
206                }
207            }
208            AsPathSource::Merged { .. } => AsPathIter {
209                cur_words: &[],
210                segs: self.wire_segments(),
211            },
212        }
213    }
214
215    /// Materialises all [`Asn`]s in this path (with `AS_SET` expanded in wire order) into a `Vec`.
216    pub fn to_vec(&self) -> Vec<Asn> {
217        self.iter().collect()
218    }
219
220    /// Converts this view into an owned `Option<AsPath>` matching [`BgpElem::as_path`](crate::BgpElem::as_path).
221    pub fn to_as_path(&self) -> Option<AsPath> {
222        match self.source {
223            AsPathSource::Absent => None,
224            AsPathSource::Single(wire) => Some(wire_to_owned_as_path(wire)),
225            AsPathSource::Merged { as_path, as4_path } => {
226                let p1 = wire_to_owned_as_path(as_path);
227                let p2 = wire_to_owned_as_path(as4_path);
228                Some(AsPath::merge_aspath_as4path(&p1, &p2))
229            }
230        }
231    }
232}
233
234fn wire_to_owned_as_path(wire: &[u8]) -> AsPath {
235    let mut out = AsPath::new();
236    let mut rest = wire;
237    while rest.len() >= 2 {
238        let code = rest[0];
239        let count = rest[1] as usize;
240        let end = 2 + count * 4;
241        let asns = bytes_as_be_u32_words(&rest[2..end])
242            .iter()
243            .map(|w| Asn::new_32bit(w.get()))
244            .collect();
245        let seg = match code {
246            AS_PATH_AS_SET => Some(AsPathSegment::AsSet(asns)),
247            AS_PATH_AS_SEQUENCE => Some(AsPathSegment::AsSequence(asns)),
248            AS_PATH_CONFED_SEQUENCE => Some(AsPathSegment::ConfedSequence(asns)),
249            AS_PATH_CONFED_SET => Some(AsPathSegment::ConfedSet(asns)),
250            // Validated before this runs, so this arm is unreachable today; skipping is safer than
251            // panicking if a later segment type reaches here.
252            _ => None,
253        };
254        if let Some(seg) = seg {
255            out.append_segment(seg);
256        }
257        rest = &rest[end..];
258    }
259    out
260}
261
262impl<'a> IntoIterator for AsPathView<'a> {
263    type Item = Asn;
264    type IntoIter = AsPathIter<'a>;
265
266    #[inline]
267    fn into_iter(self) -> Self::IntoIter {
268        self.iter()
269    }
270}
271
272impl<'a> IntoIterator for &AsPathView<'a> {
273    type Item = Asn;
274    type IntoIter = AsPathIter<'a>;
275
276    #[inline]
277    fn into_iter(self) -> Self::IntoIter {
278        self.iter()
279    }
280}
281
282/// Iterator over borrowed [`AsPathSegmentRef`]s of an [`AsPathView`].
283#[derive(Clone, Debug)]
284pub(super) struct AsPathSegments<'a> {
285    lead: &'a [u8],
286    lead_remaining: usize,
287    tail: &'a [u8],
288}
289
290impl<'a> Iterator for AsPathSegments<'a> {
291    type Item = AsPathSegmentRef<'a>;
292
293    #[inline]
294    fn next(&mut self) -> Option<Self::Item> {
295        if self.lead_remaining > 0 && self.lead.len() >= 2 {
296            let code = self.lead[0];
297            let count = self.lead[1] as usize;
298            let end = 2 + count * 4;
299            let full_asn_bytes = &self.lead[2..end];
300            self.lead = &self.lead[end..];
301
302            let seg_type = AsPathSegmentType::from_wire(code);
303            let route_asns = match seg_type {
304                AsPathSegmentType::AsSequence => count,
305                AsPathSegmentType::AsSet => 1,
306                AsPathSegmentType::ConfedSequence | AsPathSegmentType::ConfedSet => 0,
307            };
308
309            if route_asns <= self.lead_remaining {
310                self.lead_remaining -= route_asns;
311                if self.lead_remaining == 0 {
312                    self.lead = &[];
313                }
314                return Some(AsPathSegmentRef {
315                    seg_type,
316                    asn_bytes: full_asn_bytes,
317                });
318            } else {
319                // Only AS_SEQUENCE can straddle the leading count boundary (RFC 6793 §4.2.3).
320                let take_bytes = self.lead_remaining * 4;
321                self.lead_remaining = 0;
322                self.lead = &[];
323                return Some(AsPathSegmentRef {
324                    seg_type,
325                    asn_bytes: &full_asn_bytes[..take_bytes],
326                });
327            }
328        }
329
330        if self.tail.len() >= 2 {
331            let code = self.tail[0];
332            let count = self.tail[1] as usize;
333            let end = 2 + count * 4;
334            let asn_bytes = &self.tail[2..end];
335            self.tail = &self.tail[end..];
336            return Some(AsPathSegmentRef {
337                seg_type: AsPathSegmentType::from_wire(code),
338                asn_bytes,
339            });
340        }
341
342        None
343    }
344}
345
346/// Iterator over [`Asn`]s in an [`AsPathView`], expanding `AS_SET` segments on the fly.
347#[derive(Clone, Debug)]
348pub struct AsPathIter<'a> {
349    cur_words: &'a [BeU32],
350    segs: AsPathSegments<'a>,
351}
352
353impl<'a> Iterator for AsPathIter<'a> {
354    type Item = Asn;
355
356    #[inline]
357    fn next(&mut self) -> Option<Self::Item> {
358        loop {
359            if let Some((first, rest)) = self.cur_words.split_first() {
360                self.cur_words = rest;
361                return Some(Asn::new_32bit(first.get()));
362            }
363            let seg = self.segs.next()?;
364            self.cur_words = bytes_as_be_u32_words(seg.asn_bytes);
365        }
366    }
367}
368
369#[derive(Clone, Copy, Debug)]
370pub(super) enum OriginsRepr<'a> {
371    Absent,
372    Empty,
373    One(Asn),
374    Set(&'a [BeU32]),
375}
376
377#[inline]
378pub(super) fn single_wire_origins(wire: &[u8]) -> AsnsView<'_> {
379    // Fast path (99.99% of RIB entries): single non-empty AS_SEQUENCE segment.
380    if wire.len() >= 6 && wire[0] == AS_PATH_AS_SEQUENCE && 2 + (wire[1] as usize) * 4 == wire.len()
381    {
382        let last = wire.len() - 4;
383        let asn = Asn::new_32bit(u32::from_be_bytes([
384            wire[last],
385            wire[last + 1],
386            wire[last + 2],
387            wire[last + 3],
388        ]));
389        return AsnsView {
390            repr: OriginsRepr::One(asn),
391        };
392    }
393
394    let mut rest = wire;
395    let mut last_seg: Option<(u8, &[u8])> = None;
396    while rest.len() >= 2 {
397        let code = rest[0];
398        let count = rest[1] as usize;
399        let end = 2 + count * 4;
400        last_seg = Some((code, &rest[2..end]));
401        rest = &rest[end..];
402    }
403
404    let repr = match last_seg {
405        Some((AS_PATH_AS_SEQUENCE, bytes)) if bytes.len() >= 4 => {
406            let i = bytes.len() - 4;
407            OriginsRepr::One(Asn::new_32bit(u32::from_be_bytes([
408                bytes[i],
409                bytes[i + 1],
410                bytes[i + 2],
411                bytes[i + 3],
412            ])))
413        }
414        Some((AS_PATH_AS_SET, bytes)) if !bytes.is_empty() => {
415            OriginsRepr::Set(bytes_as_be_u32_words(bytes))
416        }
417        _ => OriginsRepr::Empty,
418    };
419    AsnsView { repr }
420}
421
422/// Compute exact post-`coalesce()` origin ASNs of RFC 6793 merged `(as_path, as4_path)` without
423/// allocating.
424#[cold]
425pub(super) fn merged_wire_origins<'a>(as_path: &'a [u8], as4_path: &'a [u8]) -> AsnsView<'a> {
426    #[derive(Clone, Copy)]
427    enum LastCoalesced<'b> {
428        None,
429        EmptySeq,
430        NonEmptyAsSeq(Asn),
431        NonEmptyConfedSeq,
432        AsSet(&'b [BeU32]),
433        ConfedSet,
434    }
435
436    let segs = AsPathSegments {
437        lead: if wire_route_len(as_path) > wire_route_len(as4_path) {
438            as_path
439        } else {
440            &[]
441        },
442        lead_remaining: wire_route_len(as_path) - wire_route_len(as4_path),
443        tail: as4_path,
444    };
445
446    let mut state = LastCoalesced::None;
447    for seg in segs {
448        let next_state = match seg.seg_type {
449            AsPathSegmentType::AsSequence => {
450                if seg.asn_bytes.len() >= 4 {
451                    let i = seg.asn_bytes.len() - 4;
452                    LastCoalesced::NonEmptyAsSeq(Asn::new_32bit(u32::from_be_bytes([
453                        seg.asn_bytes[i],
454                        seg.asn_bytes[i + 1],
455                        seg.asn_bytes[i + 2],
456                        seg.asn_bytes[i + 3],
457                    ])))
458                } else {
459                    LastCoalesced::EmptySeq
460                }
461            }
462            AsPathSegmentType::ConfedSequence => {
463                if seg.asn_bytes.is_empty() {
464                    LastCoalesced::EmptySeq
465                } else {
466                    LastCoalesced::NonEmptyConfedSeq
467                }
468            }
469            AsPathSegmentType::AsSet => LastCoalesced::AsSet(bytes_as_be_u32_words(seg.asn_bytes)),
470            AsPathSegmentType::ConfedSet => LastCoalesced::ConfedSet,
471        };
472
473        // Mirrors `AsPathSegment::merge_in_place` in `AsPath::coalesce`.
474        state = match (state, next_state) {
475            (LastCoalesced::None, y) | (LastCoalesced::EmptySeq, y) => y,
476            (x, LastCoalesced::EmptySeq) => x,
477            (_, y) => y,
478        };
479    }
480
481    let repr = match state {
482        LastCoalesced::NonEmptyAsSeq(asn) => OriginsRepr::One(asn),
483        LastCoalesced::AsSet(words) if !words.is_empty() => OriginsRepr::Set(words),
484        _ => OriginsRepr::Empty,
485    };
486    AsnsView { repr }
487}
488
489/// Zero-allocation view over the originating ASNs of an element's `AS_PATH`.
490#[derive(Clone, Copy, Debug)]
491pub struct AsnsView<'a> {
492    pub(super) repr: OriginsRepr<'a>,
493}
494
495impl<'a> AsnsView<'a> {
496    /// Returns `true` when the element carries a valid `AS_PATH` (matching
497    /// `elem.origin_asns.is_some()` on [`BgpElem`](crate::BgpElem)).
498    #[inline]
499    pub fn is_present(&self) -> bool {
500        !matches!(self.repr, OriginsRepr::Absent)
501    }
502
503    /// Returns the number of originating ASNs (`0`, `1`, or the cardinality of a trailing
504    /// `AS_SET`).
505    #[inline]
506    pub fn len(&self) -> usize {
507        match self.repr {
508            OriginsRepr::Absent | OriginsRepr::Empty => 0,
509            OriginsRepr::One(_) => 1,
510            OriginsRepr::Set(words) => words.len(),
511        }
512    }
513
514    /// Returns `true` if there are zero originating ASNs.
515    #[inline]
516    pub fn is_empty(&self) -> bool {
517        self.len() == 0
518    }
519
520    /// Returns an iterator over the originating [`Asn`]s without allocating.
521    #[inline]
522    pub fn iter(&self) -> AsnsIter<'a> {
523        AsnsIter { repr: self.repr }
524    }
525
526    /// Materialises the originating [`Asn`]s into a `Vec<Asn>`.
527    pub fn to_vec(&self) -> Vec<Asn> {
528        self.iter().collect()
529    }
530}
531
532impl<'a> IntoIterator for AsnsView<'a> {
533    type Item = Asn;
534    type IntoIter = AsnsIter<'a>;
535
536    #[inline]
537    fn into_iter(self) -> Self::IntoIter {
538        self.iter()
539    }
540}
541
542impl<'a> IntoIterator for &AsnsView<'a> {
543    type Item = Asn;
544    type IntoIter = AsnsIter<'a>;
545
546    #[inline]
547    fn into_iter(self) -> Self::IntoIter {
548        self.iter()
549    }
550}
551
552/// Iterator over originating [`Asn`]s from [`AsnsView`].
553#[derive(Clone, Debug)]
554pub struct AsnsIter<'a> {
555    repr: OriginsRepr<'a>,
556}
557
558impl<'a> Iterator for AsnsIter<'a> {
559    type Item = Asn;
560
561    #[inline]
562    fn next(&mut self) -> Option<Self::Item> {
563        match &mut self.repr {
564            OriginsRepr::Absent | OriginsRepr::Empty => None,
565            OriginsRepr::One(asn) => {
566                let out = *asn;
567                self.repr = OriginsRepr::Empty;
568                Some(out)
569            }
570            OriginsRepr::Set(words) => {
571                let (first, rest) = words.split_first()?;
572                *words = rest;
573                Some(Asn::new_32bit(first.get()))
574            }
575        }
576    }
577
578    #[inline]
579    fn size_hint(&self) -> (usize, Option<usize>) {
580        let len = match self.repr {
581            OriginsRepr::Absent | OriginsRepr::Empty => 0,
582            OriginsRepr::One(_) => 1,
583            OriginsRepr::Set(words) => words.len(),
584        };
585        (len, Some(len))
586    }
587}
588
589impl ExactSizeIterator for AsnsIter<'_> {}
590
591///////////////////////////////////////////////////////////////////////////////
592// Communities View
593///////////////////////////////////////////////////////////////////////////////
594
595/// Cast a byte slice whose length is a multiple of 4 into a zero-copy slice of unaligned
596/// network-byte-order 32-bit words (`zerocopy::big_endian::U32`) without `unsafe`.
597///
598/// If `bytes.len()` is not a multiple of 4, returns an empty slice.
599#[inline]
600pub(super) fn bytes_as_be_u32_words(bytes: &[u8]) -> &[BeU32] {
601    if !bytes.len().is_multiple_of(4) {
602        return &[];
603    }
604    <[BeU32]>::ref_from_bytes(bytes).unwrap_or(&[])
605}
606
607/// Borrowed view over an element's BGP community attributes (`COMMUNITIES`,
608/// `EXTENDED_COMMUNITIES`, `IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES`, and
609/// `LARGE_COMMUNITIES`).
610///
611/// Note on wire layout: BGP attributes in MRT bodies sit at arbitrary 1-byte alignments, store
612/// integers in network byte order (big-endian), and split plain, extended, and large communities
613/// across distinct TLV attributes. Consequently, a native `&[u32]` slice cannot borrow the wire
614/// bytes directly on little-endian hosts without copying. Instead, `CommunitiesView` borrows the
615/// attribute bytes directly and exposes a zero-allocation [`iter`](Self::iter) that decodes each
616/// community in place.
617#[derive(Clone, Copy, Debug)]
618pub struct CommunitiesView<'a> {
619    pub(super) attr_bytes: &'a [u8],
620}
621
622impl<'a> CommunitiesView<'a> {
623    /// Returns `true` if the element carries no communities of any kind.
624    #[inline]
625    pub fn is_empty(&self) -> bool {
626        self.iter().next().is_none()
627    }
628
629    /// Iterates over all [`MetaCommunity`] values in wire attribute order, matching
630    /// [`BgpElem::communities`](crate::BgpElem::communities).
631    #[inline]
632    pub fn iter(&self) -> CommunitiesIter<'a> {
633        CommunitiesIter {
634            rest_attrs: self.attr_bytes,
635            cur_kind: ActiveCommunityAttr::None,
636        }
637    }
638}
639
640impl<'a> IntoIterator for CommunitiesView<'a> {
641    type Item = MetaCommunity;
642    type IntoIter = CommunitiesIter<'a>;
643
644    #[inline]
645    fn into_iter(self) -> Self::IntoIter {
646        self.iter()
647    }
648}
649
650impl<'a> IntoIterator for &CommunitiesView<'a> {
651    type Item = MetaCommunity;
652    type IntoIter = CommunitiesIter<'a>;
653
654    #[inline]
655    fn into_iter(self) -> Self::IntoIter {
656        self.iter()
657    }
658}
659
660/// Where the next attribute in a block sits, or why the block cannot be walked further.
661pub(super) enum AttrStep {
662    /// The block ends here.
663    End,
664    /// The attribute whose header starts here declares more bytes than the block holds. `available`
665    /// is what remains after its header.
666    Truncated {
667        code: u8,
668        declared: usize,
669        available: usize,
670    },
671    /// One attribute: its type code and the byte range of its value within the block.
672    Attr {
673        code: u8,
674        value_start: usize,
675        value_end: usize,
676    },
677}
678
679/// How far into an attribute block a decoder can read, and what stopped it.
680pub(super) enum AttrBlockScan {
681    /// The block is usable up to `usable_len`. `truncated` is set when the attribute at that offset
682    /// declares more bytes than the block holds: the owned walker keeps what it already read there.
683    Usable {
684        usable_len: usize,
685        truncated: Option<(u8, usize, usize)>,
686    },
687    /// A header cannot be read at all, so the offset of the next attribute is unknown and the owned
688    /// path fails the record.
689    Unreadable,
690}
691
692/// Read an attribute block once, reporting where a decoder has to stop and why.
693///
694/// This is the only walk that decides where a block ends: `attribute_block_walks` asks it whether the
695/// record survives, and an element takes its usable prefix from it, so the decode loop cannot
696/// disagree with the gate that let the element exist.
697pub(super) fn scan_attr_block(bytes: &[u8]) -> AttrBlockScan {
698    let mut pos = 0usize;
699    loop {
700        // Fewer than three octets left: no header fits, and the owned walker accepts what it read.
701        if pos + 3 > bytes.len() {
702            return AttrBlockScan::Usable {
703                usable_len: pos,
704                truncated: None,
705            };
706        }
707        // Three octets with the extended-length flag set cannot even name the header's length.
708        if bytes[pos] & AttrFlags::EXTENDED.bits() != 0 && pos + 4 > bytes.len() {
709            return AttrBlockScan::Unreadable;
710        }
711        match step_attr(bytes, pos) {
712            AttrStep::End => {
713                return AttrBlockScan::Usable {
714                    usable_len: pos,
715                    truncated: None,
716                }
717            }
718            AttrStep::Truncated {
719                code,
720                declared,
721                available,
722            } => {
723                return AttrBlockScan::Usable {
724                    usable_len: pos,
725                    truncated: Some((code, declared, available)),
726                }
727            }
728            AttrStep::Attr { value_end, .. } => pos = value_end,
729        }
730    }
731}
732
733/// The type code, the offset the value starts at, and the offset it ends at, for the attribute at
734/// `pos`, when it fits in the block.
735pub(super) fn next_attr_bounds(bytes: &[u8], pos: usize) -> Option<(u8, usize, usize)> {
736    match step_attr(bytes, pos) {
737        AttrStep::Attr {
738            code,
739            value_start,
740            value_end,
741        } => Some((code, value_start, value_end)),
742        AttrStep::Truncated { .. } | AttrStep::End => None,
743    }
744}
745
746/// Decode the attribute header at `pos` without copying anything.
747///
748/// The block ends at a header that does not fit, which is how a block with a stray trailing byte or two
749/// is read: the owned decoder accepts it and stops there too.
750pub(super) fn step_attr(bytes: &[u8], pos: usize) -> AttrStep {
751    if pos + 3 > bytes.len() {
752        return AttrStep::End;
753    }
754    let flags = bytes[pos];
755    let code = bytes[pos + 1];
756    let (header_len, declared) = if (flags & AttrFlags::EXTENDED.bits()) == 0 {
757        (3usize, bytes[pos + 2] as usize)
758    } else {
759        if pos + 4 > bytes.len() {
760            return AttrStep::End;
761        }
762        (
763            4usize,
764            u16::from_be_bytes([bytes[pos + 2], bytes[pos + 3]]) as usize,
765        )
766    };
767    let value_start = pos + header_len;
768    let value_end = value_start + declared;
769    if value_end > bytes.len() {
770        return AttrStep::Truncated {
771            code,
772            declared,
773            available: bytes.len() - value_start,
774        };
775    }
776    AttrStep::Attr {
777        code,
778        value_start,
779        value_end,
780    }
781}
782
783#[inline]
784pub(super) fn next_attr_tlv(bytes: &[u8]) -> Option<(u8, &[u8], &[u8])> {
785    let (code, header_len, value_end) = next_attr_bounds(bytes, 0)?;
786    Some((code, &bytes[header_len..value_end], &bytes[value_end..]))
787}
788
789#[derive(Clone, Debug)]
790enum ActiveCommunityAttr<'a> {
791    None,
792    Plain(&'a [BeU32]),
793    Extended(&'a [u8]),
794    Ipv6Extended(&'a [u8]),
795    Large(&'a [BeU32]),
796}
797
798/// Iterator over all [`MetaCommunity`] items in wire attribute order.
799#[derive(Clone, Debug)]
800pub struct CommunitiesIter<'a> {
801    rest_attrs: &'a [u8],
802    cur_kind: ActiveCommunityAttr<'a>,
803}
804
805impl Iterator for CommunitiesIter<'_> {
806    type Item = MetaCommunity;
807
808    #[inline]
809    fn next(&mut self) -> Option<MetaCommunity> {
810        loop {
811            match &mut self.cur_kind {
812                ActiveCommunityAttr::Plain(words) => {
813                    if let Some((first, rest)) = words.split_first() {
814                        *words = rest;
815                        return Some(MetaCommunity::Plain(
816                            crate::parser::bgp::attributes::decode_regular_community(first.get()),
817                        ));
818                    }
819                }
820                ActiveCommunityAttr::Extended(bytes) => {
821                    if bytes.len() >= 8 {
822                        let mut chunk = &bytes[..8];
823                        *bytes = &bytes[8..];
824                        return Some(MetaCommunity::Extended(
825                            crate::parser::bgp::attributes::parse_extended_community_one(
826                                &mut chunk,
827                            )
828                            .unwrap_or(ExtendedCommunity::Raw([0u8; 8])),
829                        ));
830                    }
831                }
832                ActiveCommunityAttr::Ipv6Extended(bytes) => {
833                    if bytes.len() >= 20 {
834                        let mut chunk = &bytes[..20];
835                        *bytes = &bytes[20..];
836                        if let Ok(item) =
837                            crate::parser::bgp::attributes::parse_ipv6_extended_community_one(
838                                &mut chunk,
839                            )
840                        {
841                            return Some(MetaCommunity::Ipv6Extended(item));
842                        }
843                    }
844                }
845                ActiveCommunityAttr::Large(words) => {
846                    if words.len() >= 3 {
847                        let ga = words[0].get();
848                        let d0 = words[1].get();
849                        let d1 = words[2].get();
850                        *words = &words[3..];
851                        return Some(MetaCommunity::Large(LargeCommunity::new(ga, [d0, d1])));
852                    }
853                }
854                ActiveCommunityAttr::None => {}
855            }
856
857            self.cur_kind = ActiveCommunityAttr::None;
858            let (code, val, next_rest) = next_attr_tlv(self.rest_attrs)?;
859            self.rest_attrs = next_rest;
860            match AttrType::from(code) {
861                AttrType::COMMUNITIES if val.len().is_multiple_of(4) => {
862                    self.cur_kind = ActiveCommunityAttr::Plain(bytes_as_be_u32_words(val));
863                }
864                AttrType::EXTENDED_COMMUNITIES if val.len().is_multiple_of(8) => {
865                    self.cur_kind = ActiveCommunityAttr::Extended(val);
866                }
867                AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES
868                    if val.len().is_multiple_of(20) =>
869                {
870                    self.cur_kind = ActiveCommunityAttr::Ipv6Extended(val);
871                }
872                AttrType::LARGE_COMMUNITIES if val.len().is_multiple_of(12) => {
873                    self.cur_kind = ActiveCommunityAttr::Large(bytes_as_be_u32_words(val));
874                }
875                _ => {}
876            }
877        }
878    }
879}