1use rangemap::RangeInclusiveMap;
2use serde::{Deserialize, Serialize};
3use std::{fs, path::PathBuf};
4
5#[cfg(feature = "bundle")]
6pub const IPV4_ASN_BIN: &[u8] = include_bytes!("../resources/ipv4-asn.bin");
7
8pub const IPV4_ASN_BIN_NAME: &str = "ipv4-asn.bin";
9pub const IPV4_ASN_R2_URL: &str = "https://r2.ntap.io/ipv4-asn.bin";
10
11#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
12pub struct Ipv4Asn {
13 pub ip_from: u32,
14 pub ip_to: u32,
15 pub asn: u32,
16}
17
18impl Ipv4Asn {
19 pub fn file_name() -> String {
20 IPV4_ASN_BIN_NAME.to_owned()
21 }
22 pub fn r2_url() -> String {
23 IPV4_ASN_R2_URL.to_owned()
24 }
25}
26
27#[cfg(feature = "bundle")]
28pub fn get_map() -> RangeInclusiveMap<u32, u32> {
29 let mut ipv4_asn_map: RangeInclusiveMap<u32, u32> = RangeInclusiveMap::new();
30 let ipv4_asn_vec: Vec<Ipv4Asn> = bincode::deserialize(IPV4_ASN_BIN).unwrap();
31 for ipv4_asn in ipv4_asn_vec {
32 ipv4_asn_map.insert(ipv4_asn.ip_from..=ipv4_asn.ip_to, ipv4_asn.asn);
33 }
34 ipv4_asn_map
35}
36
37pub fn get_map_from_file(file_path: PathBuf) -> RangeInclusiveMap<u32, u32> {
38 let mut ipv4_asn_map: RangeInclusiveMap<u32, u32> = RangeInclusiveMap::new();
39 match fs::read(file_path) {
40 Ok(f) => {
41 let ipv4_asn_vec: Vec<Ipv4Asn> = bincode::deserialize(&f).unwrap();
42 for ipv4_asn in ipv4_asn_vec {
43 ipv4_asn_map.insert(ipv4_asn.ip_from..=ipv4_asn.ip_to, ipv4_asn.asn);
44 }
45 }
46 Err(e) => {
47 eprintln!("Error reading file: {}", e);
48 }
49 }
50 ipv4_asn_map
51}