ip2asn 0.1.2

A high-performance, memory-efficient Rust crate for mapping IP addresses to Autonomous System (AS) information.
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
#![deny(missing_docs)]
//! A high-performance, memory-efficient Rust crate for mapping IP addresses to
//! Autonomous System (AS) information with sub-microsecond lookups.
//!
//! The core of the crate is the [`IpAsnMap`], a read-optimized data structure
//! constructed using a flexible [`Builder`]. The builder can ingest data from
//! files, network streams, or in-memory buffers, and can operate in either a
//! strict mode that errors on malformed lines or a resilient mode that skips
//! them. Lookups are performed in sub-microsecond time, returning a lightweight
//! view of the ASN details. The crate provides detailed [`Error`] and [`Warning`]
//! types for robust error handling.
//!
//! All public data structures are marked as `#[non_exhaustive]` to allow for
//! future additions without breaking backward compatibility. This means you must
//! use the `..` syntax in match patterns on enums and struct instantiations.
//!
//! # Quick Start
//!
//! ```rust
//! use ip2asn::{Builder, IpAsnMap};
//! use ip_network::IpNetwork;
//! use std::net::IpAddr;
//!
//! fn main() -> Result<(), ip2asn::Error> {
//!     // A small, in-memory TSV data source for the example.
//!     let data = "31.13.64.0\t31.13.127.255\t32934\tUS\tFACEBOOK-AS";
//!
//!     // Build the map from a source that implements `io::Read`.
//!     let map = Builder::new()
//!         .with_source(data.as_bytes())?
//!         .build()?;
//!
//!     // Perform a lookup.
//!     let ip: IpAddr = "31.13.100.100".parse().unwrap();
//!     if let Some(info) = map.lookup(ip) {
//!         assert_eq!(info.network, "31.13.64.0/18".parse::<IpNetwork>().unwrap());
//!         assert_eq!(info.asn, 32934);
//!         assert_eq!(info.country_code, "US");
//!         assert_eq!(info.organization, "FACEBOOK-AS");
//!         println!(
//!             "{} -> AS{} {} ({}) in {}",
//!             ip, info.asn, info.organization, info.country_code, info.network
//!         );
//!     }
//!
//!     Ok(())
//! }
//! ```
mod interner;
/// Line-by-line parsing logic for IP-to-ASN data.
pub mod parser;
/// IP range to CIDR conversion logic.
pub mod range;
/// Core data structures for ASN records.
pub mod types;

use crate::interner::StringInterner;
use crate::parser::{parse_line, ParsedLine};
use crate::range::range_to_cidrs;
use crate::types::AsnRecord;
use flate2::read::GzDecoder;
use ip_network::IpNetwork;
use ip_network_table::IpNetworkTable;
use std::error::Error as StdError;
use std::fmt;
use std::fs::File;
use std::hash::{Hash, Hasher};
use std::io::{BufRead, BufReader};
use std::net::IpAddr;
use std::path::Path;

/// The primary error type for the crate.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// An error occurred during an I/O operation.
    Io(std::io::Error),

    /// An error occurred during an HTTP request.
    #[cfg(feature = "fetch")]
    Http(reqwest::Error),

    /// A line in the data source was malformed (only in strict mode).
    Parse {
        /// The 1-based line number where the error occurred.
        line_number: usize,
        /// The content of the line that failed to parse.
        line_content: String,
        /// The specific type of parsing error.
        kind: ParseErrorKind,
    },
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Error::Io(e) => Some(e),
            #[cfg(feature = "fetch")]
            Error::Http(e) => Some(e),
            Error::Parse { .. } => None,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Io(e) => write!(f, "I/O error: {e}"),
            #[cfg(feature = "fetch")]
            Error::Http(e) => write!(f, "HTTP error: {e}"),
            Error::Parse {
                line_number,
                line_content,
                kind,
            } => write!(
                f,
                "Parse error on line {line_number}: {kind} in line: \"{line_content}\""
            ),
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Self {
        Error::Io(err)
    }
}

#[cfg(feature = "fetch")]
impl From<reqwest::Error> for Error {
    fn from(err: reqwest::Error) -> Self {
        Error::Http(err)
    }
}

/// A non-fatal warning for a skipped line during parsing.
#[derive(Debug)]
#[non_exhaustive]
pub enum Warning {
    /// A line in the data source could not be parsed and was skipped.
    Parse {
        /// The 1-based line number where the warning occurred.
        line_number: usize,
        /// The content of the line that was skipped.
        line_content: String,
        /// A message describing the parse error.
        message: String,
    },
    /// A line contained a start IP and end IP of different families.
    IpFamilyMismatch {
        /// The 1-based line number where the warning occurred.
        line_number: usize,
        /// The content of the line that was skipped.
        line_content: String,
    },
}

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Warning::Parse {
                line_number,
                line_content,
                message,
            } => write!(
                f,
                "Parse warning on line {line_number}: {message} in line: \"{line_content}\""
            ),
            Warning::IpFamilyMismatch {
                line_number,
                line_content,
            } => write!(
                f,
                "IP family mismatch on line {line_number}: \"{line_content}\""
            ),
        }
    }
}

/// The specific kind of error that occurred during line parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseErrorKind {
    /// The line did not have the expected number of columns.
    IncorrectColumnCount {
        /// The expected number of columns.
        expected: usize,
        /// The actual number of columns found.
        found: usize,
    },
    /// A field could not be parsed as a valid IP address.
    InvalidIpAddress {
        /// The name of the field that failed parsing (e.g., "start_ip").
        field: String,
        /// The value that could not be parsed.
        value: String,
    },
    /// The ASN field could not be parsed as a valid number.
    InvalidAsnNumber {
        /// The value that could not be parsed as an ASN.
        value: String,
    },
    /// The start IP address was greater than the end IP address.
    InvalidRange {
        /// The start IP of the invalid range.
        start_ip: IpAddr,
        /// The end IP of the invalid range.
        end_ip: IpAddr,
    },
    /// The start and end IPs were of different families.
    IpFamilyMismatch,
    /// The country code was not a 2-character string.
    InvalidCountryCode {
        /// The value that could not be parsed as a country code.
        value: String,
    },
}

impl fmt::Display for ParseErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseErrorKind::IncorrectColumnCount { expected, found } => {
                write!(f, "expected {expected} columns, but found {found}")
            }
            ParseErrorKind::InvalidIpAddress { field, value } => {
                write!(f, "invalid IP address for field `{field}`: {value}")
            }
            ParseErrorKind::InvalidAsnNumber { value } => {
                write!(f, "invalid ASN: {value}")
            }
            ParseErrorKind::InvalidRange { start_ip, end_ip } => {
                write!(f, "start IP {start_ip} is greater than end IP {end_ip}")
            }
            ParseErrorKind::IpFamilyMismatch => {
                write!(f, "start and end IPs are of different families")
            }
            ParseErrorKind::InvalidCountryCode { value } => {
                write!(f, "invalid country code: {value}")
            }
        }
    }
}

/// A read-optimized, in-memory map for IP address to ASN lookups.
/// Construction is handled by the `Builder`.
pub struct IpAsnMap {
    table: IpNetworkTable<AsnRecord>,
    organizations: Vec<String>,
}

impl fmt::Debug for IpAsnMap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("IpAsnMap")
            .field("organizations", &self.organizations.len())
            .finish_non_exhaustive()
    }
}

impl Default for IpAsnMap {
    /// Creates a new, empty `IpAsnMap`.
    fn default() -> Self {
        Self {
            table: IpNetworkTable::new(),
            organizations: Vec::new(),
        }
    }
}

impl IpAsnMap {
    /// Creates a new, empty `IpAsnMap`.
    ///
    /// This is a convenience method equivalent to `IpAsnMap::default()`.
    ///
    /// # Example
    ///
    /// ```
    /// use ip2asn::IpAsnMap;
    ///
    /// let map = IpAsnMap::new();
    /// assert!(map.lookup("1.1.1.1".parse().unwrap()).is_none());
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a new `Builder` for constructing an `IpAsnMap`.
    ///
    /// This is a convenience method equivalent to `Builder::new()`.
    pub fn builder() -> Builder<'static> {
        Builder::new()
    }

    /// Looks up an IP address, returning a view into its ASN information if found.
    ///
    /// The lookup is a longest-prefix match, ensuring the most specific
    /// network range is returned. The returned `AsnInfoView` includes the
    /// matching network block itself.
    pub fn lookup(&self, ip: IpAddr) -> Option<AsnInfoView> {
        self.table.longest_match(ip).map(|(network, record)| {
            let organization = &self.organizations[record.organization_idx as usize];
            AsnInfoView {
                network,
                asn: record.asn,
                country_code: std::str::from_utf8(&record.country_code).unwrap_or_default(),
                organization,
            }
        })
    }

    /// Looks up an IP address, returning an owned `AsnInfo` struct if found.
    ///
    /// This method is an alternative to [`lookup`](#method.lookup) that returns an
    /// owned [`AsnInfo`] struct rather than a view. This is useful in async
    /// contexts or when the result needs to be stored or sent across threads.
    ///
    /// # Example
    ///
    /// ```
    /// # use ip2asn::{Builder, IpAsnMap};
    /// # use std::net::IpAddr;
    /// #
    /// # fn main() -> Result<(), ip2asn::Error> {
    /// # let data = "1.0.0.0\t1.0.0.255\t13335\tAU\tCLOUDFLARENET";
    /// # let map = Builder::new().with_source(data.as_bytes())?.build()?;
    /// let ip: IpAddr = "1.0.0.1".parse().unwrap();
    ///
    /// if let Some(info) = map.lookup_owned(ip) {
    ///     // The `info` object is owned and can be stored or sent across threads.
    ///     assert_eq!(info.asn, 13335);
    ///     println!("Owned info: {}", info);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn lookup_owned(&self, ip: IpAddr) -> Option<AsnInfo> {
        self.lookup(ip).map(AsnInfo::from)
    }
}

/// An owned struct containing ASN information for an IP address.
///
/// This struct is returned by the [`lookup_owned`](#method.lookup_owned) method
/// and is useful when the information needs to be stored or moved, as it does not
/// contain any lifetimes.
///
/// It implements common traits like `Clone`, `Eq`, `Ord`, and `Hash`, and can
/// be serialized with `serde` if the `serde` feature is enabled.
///
/// # Example
///
/// ```
/// # use ip2asn::{AsnInfo, Builder};
/// # use ip_network::IpNetwork;
/// # use std::net::IpAddr;
/// #
/// # fn main() -> Result<(), ip2asn::Error> {
/// # let data = "1.0.0.0\t1.0.0.255\t13335\tAU\tCLOUDFLARENET";
/// # let map = Builder::new().with_source(data.as_bytes())?.build()?;
/// let ip: IpAddr = "1.0.0.1".parse().unwrap();
/// let owned_info = map.lookup_owned(ip).unwrap();
///
/// // You can clone it, hash it, sort it, etc.
/// let cloned_info = owned_info.clone();
/// assert_eq!(owned_info, cloned_info);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct AsnInfo {
    /// The matching IP network block for the looked-up address.
    pub network: IpNetwork,
    /// The Autonomous System Number (ASN).
    pub asn: u32,
    /// The two-letter ISO 3166-1 alpha-2 country code.
    pub country_code: String,
    /// The common name of the organization that owns the IP range.
    pub organization: String,
}

impl PartialEq for AsnInfo {
    fn eq(&self, other: &Self) -> bool {
        self.network == other.network
            && self.asn == other.asn
            && self.country_code == other.country_code
            && self.organization == other.organization
    }
}

impl PartialOrd for AsnInfo {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for AsnInfo {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.asn
            .cmp(&other.asn)
            .then_with(|| self.network.cmp(&other.network))
            .then_with(|| self.country_code.cmp(&other.country_code))
            .then_with(|| self.organization.cmp(&other.organization))
    }
}

impl Hash for AsnInfo {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.network.hash(state);
        self.asn.hash(state);
        self.country_code.hash(state);
        self.organization.hash(state);
    }
}

impl fmt::Display for AsnInfo {
    /// Formats the `AsnInfo` for display.
    ///
    /// # Example
    ///
    /// ```
    /// # use ip2asn::{Builder, IpAsnMap};
    /// # use std::net::IpAddr;
    /// #
    /// # fn main() -> Result<(), ip2asn::Error> {
    /// # let data = "1.0.0.0\t1.0.0.255\t13335\tAU\tCLOUDFLARENET";
    /// # let map = Builder::new().with_source(data.as_bytes())?.build()?;
    /// let ip: IpAddr = "1.0.0.1".parse().unwrap();
    /// let info = map.lookup_owned(ip).unwrap();
    ///
    /// let display_str = info.to_string();
    /// assert_eq!(display_str, "AS13335 CLOUDFLARENET (AU) in 1.0.0.0/24");
    /// # Ok(())
    /// # }
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "AS{} {} ({}) in {}",
            self.asn, self.organization, self.country_code, self.network
        )
    }
}

impl<'a> From<AsnInfoView<'a>> for AsnInfo {
    fn from(view: AsnInfoView<'a>) -> Self {
        Self {
            network: view.network,
            asn: view.asn,
            country_code: view.country_code.to_string(),
            organization: view.organization.to_string(),
        }
    }
}

/// A builder for configuring and loading an `IpAsnMap`.
#[derive(Default)]
pub struct Builder<'a> {
    source: Option<Box<dyn BufRead + Send + 'a>>,
    strict: bool,
    on_warning: Option<Box<dyn Fn(Warning) + Send + 'a>>,
}

impl<'a> fmt::Debug for Builder<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Builder")
            .field("has_source", &self.source.is_some())
            .field("strict", &self.strict)
            .field("has_on_warning", &self.on_warning.is_some())
            .finish()
    }
}

impl<'a> Builder<'a> {
    /// Creates a new builder with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Configures the builder to load data from a file path.
    ///
    /// Gzip decompression is handled automatically by inspecting the file's magic bytes.
    pub fn from_path<P: AsRef<Path>>(mut self, path: P) -> Result<Self, Error> {
        let file = File::open(path.as_ref())?;
        let reader = BufReader::new(file);
        self.source = Some(self.create_source_from_reader(reader)?);
        Ok(self)
    }

    /// Configures the builder to load data from a source implementing `BufRead`.
    ///
    /// This is the most flexible way to provide data, accepting any reader,
    /// such as an in-memory buffer or a network stream.
    ///
    /// Gzip decompression is handled automatically by inspecting the stream's magic bytes.
    pub fn with_source(mut self, source: impl BufRead + Send + 'a) -> Result<Self, Error> {
        self.source = Some(self.create_source_from_reader(source)?);
        Ok(self)
    }

    /// Configures the builder to load data from a URL.
    ///
    /// This method is only available when the `fetch` feature is enabled.
    /// Gzip decompression is handled automatically by inspecting the stream's magic bytes.
    #[cfg(feature = "fetch")]
    pub fn from_url(mut self, url: &str) -> Result<Self, Error> {
        let response = reqwest::blocking::get(url)?;
        let response = response.error_for_status()?;
        let reader = BufReader::new(response);
        self.source = Some(self.create_source_from_reader(reader)?);
        Ok(self)
    }

    /// Enables strict parsing mode.
    ///
    /// If called, `build()` will return an `Err` on the first parse failure.
    pub fn strict(mut self) -> Self {
        self.strict = true;
        self
    }

    /// Sets a callback function to be invoked for each skipped line in resilient mode.
    pub fn on_warning<F>(mut self, callback: F) -> Self
    where
        F: Fn(Warning) + Send + 'a,
    {
        self.on_warning = Some(Box::new(callback));
        self
    }

    fn create_source_from_reader(
        &self,
        mut reader: impl BufRead + Send + 'a,
    ) -> Result<Box<dyn BufRead + Send + 'a>, Error> {
        let is_gzipped = {
            let header = reader.fill_buf()?;
            header.starts_with(&[0x1f, 0x8b])
        };

        let source: Box<dyn BufRead + Send + 'a> = if is_gzipped {
            Box::new(BufReader::new(GzDecoder::new(reader)))
        } else {
            Box::new(reader)
        };

        Ok(source)
    }

    /// Builds the `IpAsnMap`, consuming the builder.
    ///
    /// This method reads from the source, parses each line, interns strings,
    /// converts IP ranges to CIDRs, and inserts them into the final lookup table.
    pub fn build(self) -> Result<IpAsnMap, Error> {
        let source = self.source.ok_or_else(|| {
            Error::Io(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "No data source provided",
            ))
        })?;

        let mut interner = StringInterner::new();
        let mut table = IpNetworkTable::new();

        for (i, line_result) in source.lines().enumerate() {
            let line_number = i + 1;
            let line = line_result?;
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            let parsed: ParsedLine = match parse_line(&line) {
                Ok(p) => p,
                Err(kind) => {
                    if self.strict {
                        return Err(Error::Parse {
                            line_number,
                            line_content: line,
                            kind,
                        });
                    } else if let Some(callback) = &self.on_warning {
                        let warning = if kind == ParseErrorKind::IpFamilyMismatch {
                            Warning::IpFamilyMismatch {
                                line_number,
                                line_content: line,
                            }
                        } else {
                            Warning::Parse {
                                line_number,
                                line_content: line,
                                message: format!("{kind:?}"),
                            }
                        };
                        callback(warning);
                    }
                    continue;
                }
            };

            let org_idx = interner.get_or_intern(parsed.organization);

            let record = AsnRecord {
                asn: parsed.asn,
                country_code: parsed.country_code,
                organization_idx: org_idx,
            };

            for cidr in range_to_cidrs(parsed.start_ip, parsed.end_ip) {
                table.insert(cidr, record);
            }
        }

        let organizations = interner.into_vec();
        Ok(IpAsnMap {
            table,
            organizations,
        })
    }
}

/// A lightweight, read-only view into the ASN information for an IP address.
/// This struct is returned by the `lookup` method.
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AsnInfoView<'a> {
    /// The matching IP network block for the looked-up address.
    pub network: IpNetwork,
    /// The Autonomous System Number (ASN).
    pub asn: u32,
    /// The two-letter ISO 3166-1 alpha-2 country code.
    pub country_code: &'a str,
    /// The common name of the organization that owns the IP range.
    pub organization: &'a str,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io;

    #[test]
    fn test_error_source() {
        let io_error = Error::Io(io::Error::new(io::ErrorKind::NotFound, "file not found"));
        assert!(io_error.source().is_some());

        #[cfg(feature = "fetch")]
        {
            let client = reqwest::blocking::Client::new();
            let req = client.get("http://0.0.0.0:1").build().unwrap();
            let http_error = Error::Http(client.execute(req).unwrap_err());
            assert!(http_error.source().is_some());
        }

        let parse_error = Error::Parse {
            line_number: 1,
            line_content: "bad line".to_string(),
            kind: ParseErrorKind::IncorrectColumnCount {
                expected: 5,
                found: 1,
            },
        };
        assert!(parse_error.source().is_none());
    }

    #[test]
    fn test_error_display() {
        let io_error = Error::Io(io::Error::new(io::ErrorKind::NotFound, "file not found"));
        assert_eq!(io_error.to_string(), "I/O error: file not found");

        #[cfg(feature = "fetch")]
        {
            // This is hard to test deterministically, so we just check that it contains
            // the prefix. The underlying error message can change.
            let client = reqwest::blocking::Client::new();
            let req = client.get("http://0.0.0.0:1").build().unwrap();
            let http_error = Error::Http(client.execute(req).unwrap_err());
            assert!(http_error.to_string().starts_with("HTTP error:"));
        }

        let parse_error = Error::Parse {
            line_number: 42,
            line_content: "bad line".to_string(),
            kind: ParseErrorKind::InvalidAsnNumber {
                value: "not-a-number".to_string(),
            },
        };
        assert_eq!(
            parse_error.to_string(),
            "Parse error on line 42: invalid ASN: not-a-number in line: \"bad line\""
        );
    }

    #[test]
    fn test_warning_display() {
        let parse_warning = Warning::Parse {
            line_number: 10,
            line_content: "another bad line".to_string(),
            message: "some issue".to_string(),
        };
        assert_eq!(
            parse_warning.to_string(),
            "Parse warning on line 10: some issue in line: \"another bad line\""
        );

        let mismatch_warning = Warning::IpFamilyMismatch {
            line_number: 20,
            line_content: "v4-and-v6".to_string(),
        };
        assert_eq!(
            mismatch_warning.to_string(),
            "IP family mismatch on line 20: \"v4-and-v6\""
        );
    }

    #[test]
    fn test_parse_error_kind_display() {
        let err = ParseErrorKind::IncorrectColumnCount {
            expected: 5,
            found: 4,
        };
        assert_eq!(err.to_string(), "expected 5 columns, but found 4");

        let err = ParseErrorKind::InvalidIpAddress {
            field: "start_ip".to_string(),
            value: "not-an-ip".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "invalid IP address for field `start_ip`: not-an-ip"
        );

        let err = ParseErrorKind::InvalidAsnNumber {
            value: "not-a-number".to_string(),
        };
        assert_eq!(err.to_string(), "invalid ASN: not-a-number");

        let err = ParseErrorKind::InvalidRange {
            start_ip: "1.1.1.1".parse().unwrap(),
            end_ip: "1.1.1.0".parse().unwrap(),
        };
        assert_eq!(
            err.to_string(),
            "start IP 1.1.1.1 is greater than end IP 1.1.1.0"
        );

        let err = ParseErrorKind::IpFamilyMismatch;
        assert_eq!(
            err.to_string(),
            "start and end IPs are of different families"
        );

        let err = ParseErrorKind::InvalidCountryCode {
            value: "USA".to_string(),
        };
        assert_eq!(err.to_string(), "invalid country code: USA");
    }

    #[test]
    fn test_ip_asn_map_builder() {
        let builder = IpAsnMap::builder();
        // A simple assertion to ensure it returns a Builder.
        // We can check a default value.
        assert!(!builder.strict);
    }

    #[test]
    fn test_asn_info_ord_and_hash() {
        use std::collections::HashSet;

        let info1 = AsnInfo {
            network: "1.0.0.0/24".parse().unwrap(),
            asn: 13335,
            country_code: "AU".to_string(),
            organization: "CLOUDFLARENET".to_string(),
        };
        let info2 = AsnInfo {
            network: "1.0.0.0/24".parse().unwrap(),
            asn: 13335,
            country_code: "AU".to_string(),
            organization: "CLOUDFLARENET".to_string(),
        };
        let info3 = AsnInfo {
            network: "8.8.8.0/24".parse().unwrap(),
            asn: 15169,
            country_code: "US".to_string(),
            organization: "GOOGLE".to_string(),
        };
        let info4 = AsnInfo {
            network: "1.0.0.0/24".parse().unwrap(),
            asn: 13336, // Different ASN
            country_code: "AU".to_string(),
            organization: "CLOUDFLARENET".to_string(),
        };

        // Test Ord
        assert_eq!(info1.cmp(&info2), std::cmp::Ordering::Equal);
        assert_eq!(info1.cmp(&info3), std::cmp::Ordering::Less);
        assert_eq!(info3.cmp(&info1), std::cmp::Ordering::Greater);
        assert_eq!(info1.cmp(&info4), std::cmp::Ordering::Less);

        // Test Hash
        let mut set = HashSet::new();
        assert!(set.insert(info1.clone()));
        assert!(!set.insert(info2.clone())); // Should not insert, as it's a duplicate
        assert!(set.insert(info3.clone()));
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn test_asn_info_display() {
        let info = AsnInfo {
            network: "192.0.2.0/24".parse().unwrap(),
            asn: 64496,
            country_code: "ZZ".to_string(),
            organization: "TEST-NET".to_string(),
        };
        assert_eq!(info.to_string(), "AS64496 TEST-NET (ZZ) in 192.0.2.0/24");
    }

    #[test]
    fn test_builder_debug_impl() {
        let builder = Builder::new();
        let debug_str = format!("{builder:?}");
        assert!(debug_str.contains("Builder"));
        assert!(debug_str.contains("has_source: false"));
        assert!(debug_str.contains("strict: false"));
        assert!(debug_str.contains("has_on_warning: false"));

        let builder_with_source = builder.with_source("".as_bytes()).unwrap();
        let debug_str_with_source = format!("{builder_with_source:?}");
        assert!(debug_str_with_source.contains("has_source: true"));
    }

    #[test]
    fn test_builder_build_no_source() {
        let result = Builder::new().build();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, Error::Io(_)));
        if let Error::Io(io_err) = err {
            assert_eq!(io_err.kind(), io::ErrorKind::NotFound);
            assert_eq!(io_err.to_string(), "No data source provided");
        }
    }

    #[test]
    fn test_builder_warning_handling() {
        use std::sync::{Arc, Mutex};

        // Test IpFamilyMismatch with a warning handler
        let data = "1.0.0.0\t::1\t123\tUS\tTEST";
        let warnings = Arc::new(Mutex::new(Vec::new()));
        let warnings_clone = warnings.clone();

        let builder = Builder::new()
            .with_source(data.as_bytes())
            .unwrap()
            .on_warning(move |w| {
                warnings_clone.lock().unwrap().push(format!("{w:?}"));
            });

        let map = builder.build().unwrap();
        assert!(map.lookup("1.1.1.1".parse::<IpAddr>().unwrap()).is_none()); // Should be empty
        let warnings_guard = warnings.lock().unwrap();
        assert_eq!(warnings_guard.len(), 1);
        assert!(warnings_guard[0].contains("IpFamilyMismatch"));

        // Test a parse error in non-strict mode with no warning handler.
        // It should just be skipped.
        let data = "invalid line";
        let builder = Builder::new().with_source(data.as_bytes()).unwrap();
        let map = builder.build().unwrap();
        assert!(map.lookup("1.1.1.1".parse::<IpAddr>().unwrap()).is_none()); // Should be empty
    }
}