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
/*!
parser module maintains the main logic for processing BGP and MRT messages.
*/
use crate::models::{BgpElem, MrtRecord};
use log::warn;
use std::io::{BufReader, Cursor, Read};
pub use text_dump::{detect_text_dump, infer_timestamp_from_path, TextDumpElemIterator};
#[macro_use]
pub mod utils;
pub mod bgp;
pub mod bmp;
pub mod filter;
pub mod iters;
pub mod mrt;
pub mod rpki;
pub mod text_dump;
#[cfg(feature = "rislive")]
pub mod rislive;
pub(crate) use self::utils::*;
pub use mrt::mrt_elem::{BgpUpdateElemIter, ElemError, Elementor, RecordElemIter};
#[cfg(feature = "oneio")]
use oneio::{get_cache_reader, get_reader, get_resumable_http_reader};
pub use crate::error::{ParserError, ParserErrorWithBytes};
pub use bmp::{parse_bmp_msg, parse_openbmp_header, parse_openbmp_msg};
pub use filter::*;
pub use iters::*;
pub use mrt::*;
#[cfg(feature = "rislive")]
pub use rislive::messages::{
RisLiveClientMessage, RisSubscribe, RisSubscribeSocketOptions, RisSubscribeType,
};
#[cfg(feature = "rislive")]
pub use rislive::{
parse_ris_live_message, parse_ris_live_message_json, parse_ris_live_message_raw,
};
pub struct BgpkitParser<R> {
reader: R,
core_dump: bool,
filters: Vec<Filter>,
options: ParserOptions,
/// Streaming element iterator for text dumps. `None` for MRT input,
/// which is parsed lazily through [`Self::next_record`].
text_dump_iter: Option<Box<dyn Iterator<Item = BgpElem> + Send>>,
}
pub(crate) struct ParserOptions {
show_warnings: bool,
warned_zebra_compat: bool,
}
impl Default for ParserOptions {
fn default() -> Self {
ParserOptions {
show_warnings: true,
warned_zebra_compat: false,
}
}
}
impl ParserOptions {
pub(crate) fn warn_zebra_compat_once(&mut self) {
if self.show_warnings && !self.warned_zebra_compat {
warn!(
"recovered shortened Zebra BGP4MP records with missing envelope fields; substituting IPv4 zero addresses and interface index 0 (further occurrences for this parser will not be logged)"
);
self.warned_zebra_compat = true;
}
}
}
#[cfg(feature = "oneio")]
impl BgpkitParser<Box<dyn Read + Send>> {
/// Creating a new parser from a object that implements [Read] trait.
pub fn new(path: &str) -> Result<Self, ParserErrorWithBytes> {
let reader = get_reader(path)?;
Ok(BgpkitParser {
reader,
core_dump: false,
filters: vec![],
options: ParserOptions::default(),
text_dump_iter: None,
})
}
/// 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
///
/// ```no_run
/// use bgpkit_parser::BgpkitParser;
///
/// let url = "https://data.ris.ripe.net/rrc00/latest-update.gz";
/// let parser = BgpkitParser::new_resumable_http(url)?;
/// # Ok::<(), bgpkit_parser::ParserErrorWithBytes>(())
/// ```
pub fn new_resumable_http(path: &str) -> Result<Self, ParserErrorWithBytes> {
let reader = get_resumable_http_reader(path)?;
Ok(BgpkitParser {
reader,
core_dump: false,
filters: vec![],
options: ParserOptions::default(),
text_dump_iter: None,
})
}
/// 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.
pub fn new_cached(path: &str, cache_dir: &str) -> Result<Self, ParserErrorWithBytes> {
let file_name = path.rsplit('/').next().unwrap().to_string();
let new_file_name = format!(
"cache-{}",
add_suffix_to_filename(file_name.as_str(), crc32(path).as_str())
);
let reader = get_cache_reader(path, cache_dir, Some(new_file_name), false)?;
Ok(BgpkitParser {
reader,
core_dump: false,
filters: vec![],
options: ParserOptions::default(),
text_dump_iter: None,
})
}
/// 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`](Self::from_text_reader_with_timestamp)
/// directly. The resulting parser streams [`BgpElem`]s lazily — one route
/// line at a time, constant memory. Calling [`into_record_iter`](Self::into_record_iter)
/// or [`next_record`](Self::next_record) on a text-dump parser returns no
/// records (text dumps have no MRT-record representation); use
/// [`into_elem_iter`](Self::into_elem_iter) or the `for elem in parser` loop instead.
///
/// # Example
///
/// ```no_run
/// 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}");
/// }
/// ```
pub fn new_text(path: &str) -> Result<Self, ParserErrorWithBytes> {
let timestamp = infer_timestamp_from_path(path).unwrap_or(0.0);
let reader = get_reader(path)?;
Self::from_text_reader_with_timestamp(reader, timestamp)
}
/// 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
///
/// ```no_run
/// 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}");
/// }
/// ```
pub fn new_auto(path: &str) -> Result<Self, ParserErrorWithBytes> {
let reader = get_reader(path)?;
Self::from_auto_reader_with_timestamp(reader, infer_timestamp_from_path(path))
}
}
#[cfg(feature = "oneio")]
fn add_suffix_to_filename(filename: &str, suffix: &str) -> String {
let mut parts: Vec<&str> = filename.split('.').collect(); // Split filename by dots
if parts.len() > 1 {
let last_part = parts.pop().unwrap(); // Remove the last part (suffix) from the parts vector
let new_last_part = format!("{suffix}.{last_part}"); // Add the suffix to the last part
parts.push(&new_last_part); // Add the updated last part back to the parts vector
parts.join(".") // Join the parts back into a filename string with dots
} else {
// If the filename does not have any dots, simply append the suffix to the end
format!("{filename}.{suffix}")
}
}
impl<R: Read> BgpkitParser<R> {
/// Creating a new parser from an object that implements [Read] trait.
pub fn from_reader(reader: R) -> Self {
BgpkitParser {
reader,
core_dump: false,
filters: vec![],
options: ParserOptions::default(),
text_dump_iter: None,
}
}
/// This is used in for loop `for item in parser{}`
pub fn next_record(&mut self) -> Result<MrtRecord, ParserErrorWithBytes> {
if self.text_dump_iter.is_some() {
return Err(ParserError::Unsupported(
"text-dump parsers have no MRT record representation; iterate elements instead"
.to_string(),
)
.into());
}
let (record, used_zebra_compat) =
mrt::mrt_record::parse_mrt_record_with_zebra_compat(&mut self.reader)?;
if used_zebra_compat {
self.warn_zebra_compat_once();
}
Ok(record)
}
}
impl BgpkitParser<Box<dyn Read + Send>> {
/// 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.
pub fn from_text_reader(
reader: impl Read + Send + 'static,
) -> Result<Self, ParserErrorWithBytes> {
Self::from_text_reader_with_timestamp(reader, 0.0)
}
/// 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.
pub fn from_text_reader_with_timestamp(
reader: impl Read + Send + 'static,
timestamp: f64,
) -> Result<Self, ParserErrorWithBytes> {
let buf_reader = BufReader::new(reader);
let iter = TextDumpElemIterator::new(buf_reader, timestamp).map_err(ParserError::from)?;
Ok(BgpkitParser {
reader: Box::new(std::io::empty()),
core_dump: false,
filters: vec![],
options: ParserOptions::default(),
text_dump_iter: Some(Box::new(iter)),
})
}
/// 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.
pub fn from_auto_reader(
reader: impl Read + Send + 'static,
) -> Result<Self, ParserErrorWithBytes> {
Self::from_auto_reader_with_timestamp(reader, None)
}
/// Create a parser from any reader, auto-detecting MRT vs text dump.
/// `timestamp` sets the element timestamp for text dumps (`None` → `0.0`);
/// for filename-based inference, use [`new_auto`](Self::new_auto) instead.
pub fn from_auto_reader_with_timestamp(
reader: impl Read + Send + 'static,
timestamp: Option<f64>,
) -> Result<Self, ParserErrorWithBytes> {
let mut buf_reader = BufReader::new(reader);
let (is_text, head) = detect_text_dump(&mut buf_reader).map_err(ParserError::from)?;
if is_text {
let chained = BufReader::new(Cursor::new(head).chain(buf_reader));
let ts = timestamp.unwrap_or(0.0);
let iter = TextDumpElemIterator::new(chained, ts).map_err(ParserError::from)?;
Ok(BgpkitParser {
reader: Box::new(std::io::empty()),
core_dump: false,
filters: vec![],
options: ParserOptions::default(),
text_dump_iter: Some(Box::new(iter)),
})
} else {
Ok(BgpkitParser {
reader: Box::new(Cursor::new(head).chain(buf_reader)),
core_dump: false,
filters: vec![],
options: ParserOptions::default(),
text_dump_iter: None,
})
}
}
}
impl<R> BgpkitParser<R> {
pub(crate) fn warn_zebra_compat_once(&mut self) {
self.options.warn_zebra_compat_once();
}
pub fn enable_core_dump(self) -> Self {
BgpkitParser {
reader: self.reader,
core_dump: true,
filters: self.filters,
options: self.options,
text_dump_iter: self.text_dump_iter,
}
}
pub fn disable_warnings(self) -> Self {
let mut options = self.options;
options.show_warnings = false;
BgpkitParser {
reader: self.reader,
core_dump: self.core_dump,
filters: self.filters,
options,
text_dump_iter: self.text_dump_iter,
}
}
/// 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
///
/// ```no_run
/// 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);
/// }
/// ```
pub fn add_filter(
self,
filter_type: &str,
filter_value: &str,
) -> Result<Self, ParserErrorWithBytes> {
let mut filters = self.filters;
filters.push(Filter::new(filter_type, filter_value)?);
Ok(BgpkitParser {
reader: self.reader,
core_dump: self.core_dump,
filters,
options: self.options,
text_dump_iter: self.text_dump_iter,
})
}
/// Add multiple filters to the parser.
///
/// This method extends the existing filters with the provided slice of filters.
///
/// # Example
///
/// ```no_run
/// 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);
/// ```
pub fn add_filters(mut self, filters: &[Filter]) -> Self {
self.filters.extend(filters.iter().cloned());
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
///
/// ```no_run
/// 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);
/// ```
pub fn with_filters(mut self, filters: &[Filter]) -> Self {
self.filters = filters.to_vec();
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::Asn;
#[test]
fn test_new_with_reader() {
// bzip2 reader for a compressed file
let reader = oneio::get_reader("http://archive.routeviews.org/route-views.ny/bgpdata/2023.02/UPDATES/updates.20230215.0630.bz2").unwrap();
assert_eq!(
12683,
BgpkitParser::from_reader(reader).into_elem_iter().count()
);
// remote reader for an uncompressed updates file
let reader = oneio::get_reader("https://spaces.bgpkit.org/parser/update-example").unwrap();
assert_eq!(
8160,
BgpkitParser::from_reader(reader).into_elem_iter().count()
);
}
#[test]
fn test_new_resumable_http() {
let parser =
BgpkitParser::new_resumable_http("https://spaces.bgpkit.org/parser/update-example.gz")
.unwrap();
assert_eq!(8160, parser.into_elem_iter().count());
}
#[test]
fn test_new_cached_with_reader() {
let url = "https://spaces.bgpkit.org/parser/update-example.gz";
let parser = BgpkitParser::new_cached(url, "/tmp/bgpkit-parser-tests")
.unwrap()
.enable_core_dump()
.disable_warnings();
let count = parser.into_elem_iter().count();
assert_eq!(8160, count);
let parser = BgpkitParser::new_cached(url, "/tmp/bgpkit-parser-tests").unwrap();
let count = parser.into_elem_iter().count();
assert_eq!(8160, count);
}
#[test]
fn test_add_suffix_to_filename() {
// Test with a filename that has dots
let filename = "example.txt";
let suffix = "suffix";
let result = add_suffix_to_filename(filename, suffix);
assert_eq!(result, "example.suffix.txt");
// Test with a filename that has multiple dots
let filename = "example.tar.gz";
let suffix = "suffix";
let result = add_suffix_to_filename(filename, suffix);
assert_eq!(result, "example.tar.suffix.gz");
// Test with a filename that has no dots
let filename = "example";
let suffix = "suffix";
let result = add_suffix_to_filename(filename, suffix);
assert_eq!(result, "example.suffix");
// Test with an empty filename
let filename = "";
let suffix = "suffix";
let result = add_suffix_to_filename(filename, suffix);
assert_eq!(result, ".suffix");
// Test with an empty suffix
let filename = "example.txt";
let suffix = "";
let result = add_suffix_to_filename(filename, suffix);
assert_eq!(result, "example..txt");
}
#[test]
fn test_with_filters() {
let url = "https://spaces.bgpkit.org/parser/update-example.gz";
// Build filters independently
let filters = vec![
Filter::new("peer_ip", "185.1.8.65").unwrap(),
Filter::new("type", "w").unwrap(),
];
// Test with_filters - sets filters directly
let parser = BgpkitParser::new(url).unwrap().with_filters(&filters);
let count = parser.into_elem_iter().count();
// peer 185.1.8.65 has 3393 total, 132 withdrawals
assert_eq!(count, 132);
// Test that with_filters replaces existing filters
let filters1 = vec![Filter::new("peer_ip", "185.1.8.65").unwrap()];
let filters2 = vec![Filter::new("peer_ip", "185.1.8.50").unwrap()];
let parser = BgpkitParser::new(url)
.unwrap()
.with_filters(&filters1)
.with_filters(&filters2); // Should replace filters1
let count = parser.into_elem_iter().count();
// peer 185.1.8.50 has 1563 elements
assert_eq!(count, 1563);
}
#[test]
fn test_add_filters() {
let url = "https://spaces.bgpkit.org/parser/update-example.gz";
// Build filters independently
let filters = vec![
Filter::new("peer_ip", "185.1.8.65").unwrap(),
Filter::new("type", "w").unwrap(),
];
// Test add_filters - extends existing filters
let parser = BgpkitParser::new(url).unwrap().add_filters(&filters);
let count = parser.into_elem_iter().count();
// peer 185.1.8.65 has 3393 total, 132 withdrawals
assert_eq!(count, 132);
// Test combining add_filter and add_filters
let parser = BgpkitParser::new(url)
.unwrap()
.add_filter("peer_ip", "185.1.8.65")
.unwrap()
.add_filters(&[Filter::new("type", "w").unwrap()]);
let count = parser.into_elem_iter().count();
assert_eq!(count, 132);
}
#[test]
fn test_with_filters_empty() {
let url = "https://spaces.bgpkit.org/parser/update-example.gz";
// Test with empty filters - should return all elements
let parser = BgpkitParser::new(url).unwrap().with_filters(&[]);
let count = parser.into_elem_iter().count();
// Total elements in the file
assert_eq!(count, 8160);
}
#[test]
fn test_add_filters_empty() {
let url = "https://spaces.bgpkit.org/parser/update-example.gz";
// Test adding empty filters - should not change behavior
let parser = BgpkitParser::new(url)
.unwrap()
.add_filter("peer_ip", "185.1.8.65")
.unwrap()
.add_filters(&[]);
let count = parser.into_elem_iter().count();
// peer 185.1.8.65 has 3393 elements
assert_eq!(count, 3393);
}
#[test]
fn test_with_filters_reuse() {
let url = "https://spaces.bgpkit.org/parser/update-example.gz";
// Build filters once
let filters = vec![
Filter::new("peer_ip", "185.1.8.65").unwrap(),
Filter::new("type", "w").unwrap(),
];
// Apply to multiple parsers (simulating reuse pattern - no clone needed)
let parser1 = BgpkitParser::new(url).unwrap().with_filters(&filters);
let count1 = parser1.into_elem_iter().count();
let parser2 = BgpkitParser::new(url).unwrap().with_filters(&filters);
let count2 = parser2.into_elem_iter().count();
// Both should have same count: 132 withdrawals from peer 185.1.8.65
assert_eq!(count1, 132);
assert_eq!(count2, 132);
}
#[test]
fn test_from_text_reader_inline() {
let dump = "BGP table version is 1, local router ID is 1.2.3.4, vrf id 0\n\
Default local pref 100, local AS 65001\n\n\
Network Next Hop Metric LocPrf Weight Path\n\
*> 1.0.0.0/24 10.0.0.1 0 0 13335 i\n";
let parser =
BgpkitParser::from_text_reader(dump.as_bytes()).expect("inline text-dump parse");
let elems: Vec<_> = parser.into_elem_iter().collect();
assert_eq!(elems.len(), 1);
assert_eq!(elems[0].prefix.prefix.to_string(), "1.0.0.0/24");
assert_eq!(elems[0].peer_ip.to_string(), "1.2.3.4");
assert_eq!(u32::from(elems[0].peer_asn), 65001);
assert_eq!(elems[0].origin_asns, Some(vec![Asn::from(13335u32)]));
}
#[test]
fn test_from_auto_reader_detects_text() {
let dump = "BGP table version is 1, local router ID is 1.2.3.4, vrf id 0\n\
Default local pref 100, local AS 65001\n\n\
Network Next Hop Metric LocPrf Weight Path\n\
*> 1.0.0.0/24 10.0.0.1 0 0 13335 i\n";
let parser = BgpkitParser::from_auto_reader(dump.as_bytes()).expect("auto-detect parse");
let elems: Vec<_> = parser.into_elem_iter().collect();
assert_eq!(elems.len(), 1);
assert_eq!(elems[0].origin_asns, Some(vec![Asn::from(13335u32)]));
}
#[test]
fn test_from_auto_reader_detects_mrt() {
// A few zero bytes — not a text dump, so auto-detect should fall
// through to the MRT path (which will then hit EOF cleanly).
let data: Vec<u8> = vec![0x00u8; 16];
let parser =
BgpkitParser::from_auto_reader(std::io::Cursor::new(data)).expect("auto-detect parse");
let count = parser.into_elem_iter().count();
assert_eq!(count, 0);
}
#[test]
fn test_text_dump_parser_with_filter() {
let dump = "BGP table version is 1, local router ID is 1.2.3.4, vrf id 0\n\
Default local pref 100, local AS 65001\n\n\
Network Next Hop Metric LocPrf Weight Path\n\
*> 1.0.0.0/24 10.0.0.1 0 0 13335 i\n\
*> 8.8.8.0/24 10.0.0.2 0 0 15169 i\n";
let parser = BgpkitParser::from_text_reader(dump.as_bytes())
.unwrap()
.add_filter("origin_asn", "13335")
.unwrap();
let elems: Vec<_> = parser.into_elem_iter().collect();
assert_eq!(elems.len(), 1);
assert_eq!(elems[0].prefix.prefix.to_string(), "1.0.0.0/24");
}
#[test]
fn test_text_dump_next_record_errors() {
let dump = "BGP table version is 1, local router ID is 1.2.3.4, vrf id 0\n\
Default local pref 100, local AS 65001\n\n\
Network Next Hop Metric LocPrf Weight Path\n\
*> 1.0.0.0/24 10.0.0.1 0 0 13335 i\n";
let mut parser =
BgpkitParser::from_text_reader(dump.as_bytes()).expect("inline text-dump parse");
assert!(parser.next_record().is_err());
}
#[test]
fn test_text_dump_record_iter_terminates() {
// Calling into_record_iter on a text-dump parser should yield 0
// records immediately, not spin forever on Unsupported errors.
let dump = "BGP table version is 1, local router ID is 1.2.3.4, vrf id 0\n\
Default local pref 100, local AS 65001\n\n\
Network Next Hop Metric LocPrf Weight Path\n\
*> 1.0.0.0/24 10.0.0.1 0 0 13335 i\n";
let parser =
BgpkitParser::from_text_reader(dump.as_bytes()).expect("inline text-dump parse");
assert_eq!(parser.into_record_iter().count(), 0);
}
}