ntap_db_ipv6_country/
lib.rs

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