Skip to main content

BgpkitParser

Struct BgpkitParser 

Source
pub struct BgpkitParser<R> { /* private fields */ }

Implementations§

Source§

impl<R> BgpkitParser<R>

Source

pub fn into_record_iter(self) -> RecordIterator<R>

Source

pub fn into_elem_iter(self) -> ElemIterator<R>

Source

pub fn into_raw_record_iter(self) -> RawRecordIterator<R>

Source

pub fn into_recovering_record_iter( self, config: RecoveryConfig, ) -> RecoveringRecordIterator<R>

Creates an opt-in iterator that reports skipped byte ranges while recovering MRT framing.

Recovery never reconstructs a damaged record. It scans for a structurally valid boundary, confirms a chain of records, emits RecoveryEvent::Gap, and then resumes normal parsing. Damage extending to the end of the stream is reported as a terminal gap. Offsets in recovery events refer to the decompressed MRT byte stream.

Source

pub fn into_recovering_elem_iter( self, config: RecoveryConfig, ) -> RecoveringElemIterator<R>

Creates an opt-in iterator over BGP elements that reports skipped byte ranges while recovering MRT framing.

Behaves like into_recovering_record_iter but converts each recovered record to BgpElems, applying the parser’s filters per element.

Source

pub fn into_update_iter(self) -> UpdateIterator<R>

Creates an iterator over BGP announcements from MRT data.

This iterator yields MrtUpdate items from both UPDATES files (BGP4MP messages) and RIB dump files (TableDump/TableDumpV2 messages). It’s a middle ground between into_record_iter() and into_elem_iter():

  • More focused than into_record_iter() as it only returns BGP announcements
  • More efficient than into_elem_iter() as it doesn’t duplicate attributes per prefix

The iterator returns an MrtUpdate enum with variants:

  • Bgp4MpUpdate: BGP UPDATE messages from UPDATES files
  • LegacyBgpUpdate: Deprecated MRT Type 5 BGP UPDATE messages
  • TableDumpV2Entry: RIB entries from TableDumpV2 RIB dumps
  • TableDumpMessage: Legacy TableDump v1 messages
§Example
use bgpkit_parser::{BgpkitParser, MrtUpdate};

let parser = BgpkitParser::new("updates.mrt").unwrap();
for update in parser.into_update_iter() {
    match update {
        MrtUpdate::Bgp4MpUpdate(u) => {
            println!("Peer {} announced {} prefixes",
                u.peer_ip,
                u.message.announced_prefixes.len()
            );
        }
        MrtUpdate::LegacyBgpUpdate(u) => {
            println!("Legacy UPDATE from peer {}", u.peer_ip);
        }
        MrtUpdate::TableDumpV2Entry(e) => {
            println!("RIB entry for {} with {} peers",
                e.prefix,
                e.rib_entries.len()
            );
        }
        MrtUpdate::TableDumpMessage(m) => {
            println!("Legacy table dump for {}", m.prefix);
        }
    }
}
Source

pub fn into_route_iter(self) -> RouteIterator<R>

Creates an iterator over lightweight route elements from MRT data.

This iterator yields BgpRouteElem values and only parses route identity, peer metadata, timestamp, and AS path. Use into_elem_iter when you need the full BgpElem attribute set. Filters that only depend on route fields are supported; community filters do not match route elements.

Source

pub fn into_fallible_record_iter(self) -> FallibleRecordIterator<R>

Creates a fallible iterator over MRT records that returns parsing errors.

§Example
use bgpkit_parser::BgpkitParser;

let parser = BgpkitParser::new("updates.mrt").unwrap();
for result in parser.into_fallible_record_iter() {
    match result {
        Ok(record) => {
            // Process the record
        }
        Err(e) => {
            // Handle the error
            eprintln!("Error parsing record: {}", e);
        }
    }
}
Source

pub fn into_fallible_elem_iter(self) -> FallibleElemIterator<R>

Creates a fallible iterator over BGP elements that returns parsing errors.

§Example
use bgpkit_parser::BgpkitParser;

let parser = BgpkitParser::new("updates.mrt").unwrap();
for result in parser.into_fallible_elem_iter() {
    match result {
        Ok(elem) => {
            // Process the element
        }
        Err(e) => {
            // Handle the error
            eprintln!("Error parsing element: {}", e);
        }
    }
}
Source

pub fn into_fallible_update_iter(self) -> FallibleUpdateIterator<R>

Creates a fallible iterator over BGP announcements that returns parsing errors.

Unlike the default into_update_iter(), this iterator returns Result<MrtUpdate, ParserErrorWithBytes> allowing users to handle parsing errors explicitly instead of having them logged and skipped.

§Example
use bgpkit_parser::{BgpkitParser, MrtUpdate};

let parser = BgpkitParser::new("updates.mrt").unwrap();
for result in parser.into_fallible_update_iter() {
    match result {
        Ok(MrtUpdate::Bgp4MpUpdate(update)) => {
            println!("Peer {} announced {} prefixes",
                update.peer_ip,
                update.message.announced_prefixes.len()
            );
        }
        Ok(_) => { /* handle other variants */ }
        Err(e) => {
            eprintln!("Error parsing: {}", e);
        }
    }
}
Source

pub fn into_fallible_route_iter(self) -> FallibleRouteIterator<R>

Creates a fallible iterator over lightweight route elements.

Source

pub fn into_diagnostic_iter(self) -> DiagnosticIterator<R>

Creates an iterator that classifies each MRT record for malformed-data investigation.

This iterator emits clean parsed records, recoverable RFC 7606 validation findings, and fatal parse errors with available raw-byte context. It ignores parser filters so that malformed records cannot be hidden by element-oriented matching. Text-dump parsers yield no diagnostic events because they have no MRT record representation.

§Example
use bgpkit_parser::{BgpkitParser, DiagnosticEvent};

for event in BgpkitParser::new("updates.mrt")?.into_diagnostic_iter() {
    match event {
        DiagnosticEvent::Record(record) => println!("{record}"),
        DiagnosticEvent::Validation { warnings, raw_record, .. } => {
            eprintln!("validation findings: {warnings:?}");
            raw_record.write_raw_bytes("malformed-record.mrt")?;
        }
        DiagnosticEvent::ParseError { error, raw_bytes, .. } => {
            eprintln!("parse error: {error}");
            if let Some(raw_bytes) = raw_bytes {
                std::fs::write("malformed-record.mrt", raw_bytes)?;
            }
        }
        _ => {}
    }
}
Source

pub fn into_elementor_and_raw_record_iter( self, ) -> (Elementor, impl Iterator<Item = RawMrtRecord>)
where R: Read,

Creates an Elementor pre-initialized with PeerIndexTable and an iterator over raw records.

This is useful for parallel processing where the Elementor needs to be shared across threads. The Elementor is created with the PeerIndexTable from the first record if present, otherwise a new Elementor is created.

§Example

See the parallel_records_to_elem example for full usage.

use bgpkit_parser::BgpkitParser;

let parser = BgpkitParser::new_cached(url, "/tmp")?;
let (elementor, records) = parser.into_elementor_and_raw_record_iter();
Source

pub fn into_elementor_and_record_iter( self, ) -> (Elementor, impl Iterator<Item = MrtRecord>)
where R: Read,

Creates an Elementor pre-initialized with PeerIndexTable and an iterator over parsed records.

This is useful for parallel processing where the Elementor needs to be shared across threads. The Elementor is created with the PeerIndexTable from the first record if present, otherwise a new Elementor is created.

§Example

See the parallel_records_to_elem example for full usage.

Source§

impl BgpkitParser<Box<dyn Read + Send>>

Source

pub fn new(path: &str) -> Result<Self, ParserErrorWithBytes>

Creating a new parser from a object that implements Read trait.

Source

pub fn new_resumable_http(path: &str) -> Result<Self, ParserErrorWithBytes>

Creates a parser backed by an experimental resumable HTTP(S) reader.

If a remote server drops a connection while the parser is reading, the reader reconnects with an HTTP Range request and continues at the last byte read. Resumed responses are validated by oneio; servers that do not support Range requests, or resources that change while being read, return an error instead of combining inconsistent bytes.

This constructor is opt-in. BgpkitParser::new retains its existing reader behavior. Use a fallible iterator when the caller needs to handle an unrecoverable read failure explicitly.

§Example
use bgpkit_parser::BgpkitParser;

let url = "https://data.ris.ripe.net/rrc00/latest-update.gz";
let parser = BgpkitParser::new_resumable_http(url)?;
Source

pub fn new_cached( path: &str, cache_dir: &str, ) -> Result<Self, ParserErrorWithBytes>

Creating a new parser that also caches the remote content to a local cache directory.

The cache file name is generated by the following format: cache-<crc32 of file name>-<file name>. For example, the remote file http://archive.routeviews.org/route-views.chile/bgpdata/2023.03/RIBS/rib.20230326.0600.bz2 will be cached as cache-682cb1eb-rib.20230326.0600.bz2 in the cache directory.

Source

pub fn new_text(path: &str) -> Result<Self, ParserErrorWithBytes>

Create a parser for a Cisco sh ip bgp text dump (PCH daily snapshots or route-views oix-full-snapshot-* files).

The file is auto-decompressed by oneio. The timestamp for all elements is inferred from the file name when possible. To override the timestamp, use from_text_reader_with_timestamp directly. The resulting parser streams BgpElems lazily — one route line at a time, constant memory. Calling into_record_iter or next_record on a text-dump parser returns no records (text dumps have no MRT-record representation); use into_elem_iter or the for elem in parser loop instead.

§Example
use bgpkit_parser::BgpkitParser;

let url = "https://downloads.pch.net/files/Routing_Data/IPv4_daily_snapshots/2026/07/route-collector.bom2.pch.net/route-collector.bom2.pch.net-ipv4_bgp_routes.2026.07.01.gz";
for elem in BgpkitParser::new_text(url).unwrap() {
    println!("{elem}");
}
Source

pub fn new_auto(path: &str) -> Result<Self, ParserErrorWithBytes>

Create a parser that auto-detects whether the input is an MRT file or a Cisco sh ip bgp text dump, parsing accordingly.

Peeks the first 256 bytes: if they look like a Cisco text dump the file is parsed as one (timestamp inferred from the path); otherwise it is treated as MRT and parsed lazily as usual. This is the most convenient constructor when the input type is unknown.

§Example
use bgpkit_parser::BgpkitParser;

// works for either MRT or text dumps
for elem in BgpkitParser::new_auto("https://downloads.pch.net/files/Routing_Data/IPv4_daily_snapshots/2026/07/route-collector.bom2.pch.net/route-collector.bom2.pch.net-ipv4_bgp_routes.2026.07.01.gz").unwrap() {
    println!("{elem}");
}
Source§

impl<R: Read> BgpkitParser<R>

Source

pub fn from_reader(reader: R) -> Self

Creating a new parser from an object that implements Read trait.

Source

pub fn next_record(&mut self) -> Result<MrtRecord, ParserErrorWithBytes>

This is used in for loop for item in parser{}

Source§

impl BgpkitParser<Box<dyn Read + Send>>

Source

pub fn from_text_reader( reader: impl Read + Send + 'static, ) -> Result<Self, ParserErrorWithBytes>

Create a text-dump parser from any reader, with timestamp 0.0. Prefer BgpkitParser::new_text when you have a file path or URL, as it will infer the timestamp automatically.

Source

pub fn from_text_reader_with_timestamp( reader: impl Read + Send + 'static, timestamp: f64, ) -> Result<Self, ParserErrorWithBytes>

Create a text-dump parser from a reader with an explicit element timestamp. The parser streams elements lazily — one route line at a time, constant memory. It has no MRT-record representation.

Source

pub fn from_auto_reader( reader: impl Read + Send + 'static, ) -> Result<Self, ParserErrorWithBytes>

Create a parser from any reader, auto-detecting MRT vs text dump by sniffing the first bytes. Timestamp defaults to 0.0 for text dumps.

Source

pub fn from_auto_reader_with_timestamp( reader: impl Read + Send + 'static, timestamp: Option<f64>, ) -> Result<Self, ParserErrorWithBytes>

Create a parser from any reader, auto-detecting MRT vs text dump. timestamp sets the element timestamp for text dumps (None0.0); for filename-based inference, use new_auto instead.

Source§

impl<R> BgpkitParser<R>

Source

pub fn enable_core_dump(self) -> Self

Source

pub fn disable_warnings(self) -> Self

Source

pub fn add_filter( self, filter_type: &str, filter_value: &str, ) -> Result<Self, ParserErrorWithBytes>

Add a filter to the parser by specifying filter type and value as strings.

This method parses the filter type and value strings to create a Filter and adds it to the parser’s filter list. For the full list of available filter types and their formats, see the Filter struct documentation.

§Available Filter Types
  • origin_asn - Origin AS number (e.g., “12345”)
  • origin_asns - Multiple origin AS numbers, comma-separated (e.g., “12345,67890”)
  • prefix - Exact prefix match (e.g., “192.168.1.0/24”)
  • prefix_super - Match prefix and super-prefixes
  • prefix_sub - Match prefix and sub-prefixes
  • prefix_super_sub - Match prefix, super-prefixes, and sub-prefixes
  • prefixes - Multiple prefixes (e.g., “1.1.1.0/24,8.8.8.0/24”)
  • peer_ip - Peer IP address (e.g., “192.168.1.1”)
  • peer_ips - Multiple peer IPs (e.g., “192.168.1.1,192.168.1.2”)
  • peer_asn - Peer AS number (e.g., “12345”)
  • peer_asns - Multiple peer AS numbers (e.g., “12345,67890”)
  • type - Message type: “a”/“announce” or “w”/“withdraw”
  • ts_start - Start timestamp (unix timestamp or RFC3339)
  • ts_end - End timestamp (unix timestamp or RFC3339)
  • as_path - AS path regex pattern
  • community - Community regex pattern
  • ip_version - IP version: “4”/“ipv4” or “6”/“ipv6”
  • otc - Only-to-customer ASN (RFC 9234); * for present, !* for absent
  • next_hop - Next hop IP address; */!* for presence
  • origin - Origin attribute: “igp”, “egp”, or “incomplete”; */!* for presence
  • local_pref - Local preference value; */!* for presence
  • med - Multi-exit discriminator value; */!* for presence
  • atomic - Atomic aggregate flag: “true”/“false”
  • aggr_asn - Aggregator ASN; */!* for presence
  • aggr_ip - Aggregator IP address; */!* for presence
  • peer_bgp_id - Peer BGP identifier (router ID); */!* for presence
§Negative Filters

Most filters support negation by prefixing the value with !. For example:

  • origin_asn=!13335 matches elements where origin AS is NOT 13335
  • prefix=!10.0.0.0/8 matches elements where prefix is NOT 10.0.0.0/8
§Presence Filters

Optional fields (Option<T>) support * as a wildcard to check whether a field is present or absent: otc=* matches elements with an OTC value, otc=!* matches elements without one.

§Example
use bgpkit_parser::BgpkitParser;

let parser = BgpkitParser::new("https://spaces.bgpkit.org/parser/update-example.gz")
    .unwrap()
    .add_filter("peer_ip", "185.1.8.65")
    .unwrap()
    .add_filter("type", "w")
    .unwrap();

for elem in parser {
    println!("{}", elem);
}
Source

pub fn add_filters(self, filters: &[Filter]) -> Self

Add multiple filters to the parser.

This method extends the existing filters with the provided slice of filters.

§Example
use bgpkit_parser::BgpkitParser;
use bgpkit_parser::parser::Filter;

let filters = vec![
    Filter::new("peer_ip", "185.1.8.65").unwrap(),
    Filter::new("type", "w").unwrap(),
];

let parser = BgpkitParser::new("https://spaces.bgpkit.org/parser/update-example.gz")
    .unwrap()
    .add_filters(&filters);
Source

pub fn with_filters(self, filters: &[Filter]) -> Self

Set filters directly, replacing any existing filters.

This method allows passing a pre-built Vec<Filter> directly to the parser, bypassing the need to parse filter strings. This is useful when you want to build filter specifications independently and reuse them across multiple parsers.

§Example
use bgpkit_parser::BgpkitParser;
use bgpkit_parser::parser::Filter;

// Build filters independently
let filters = vec![
    Filter::new("peer_ip", "185.1.8.65").unwrap(),
    Filter::new("type", "w").unwrap(),
];

// Apply to multiple parsers (no manual clone needed)
let parser1 = BgpkitParser::new("https://spaces.bgpkit.org/parser/update-example.gz")
    .unwrap()
    .with_filters(&filters);

let parser2 = BgpkitParser::new("https://spaces.bgpkit.org/parser/update-example.gz")
    .unwrap()
    .with_filters(&filters);

Trait Implementations§

Source§

impl<R: Read> IntoIterator for BgpkitParser<R>

Use ElemIterator as the default iterator to return BgpElems instead of MrtRecords.

Source§

type Item = BgpElem

The type of the elements being iterated over.
Source§

type IntoIter = ElemIterator<R>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<R> !RefUnwindSafe for BgpkitParser<R>

§

impl<R> !Sync for BgpkitParser<R>

§

impl<R> !UnwindSafe for BgpkitParser<R>

§

impl<R> Freeze for BgpkitParser<R>
where R: Freeze,

§

impl<R> Send for BgpkitParser<R>
where R: Send,

§

impl<R> Unpin for BgpkitParser<R>
where R: Unpin,

§

impl<R> UnsafeUnpin for BgpkitParser<R>
where R: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> MaybeSendSync for T

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more