use regex::Regex;
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::sync::LazyLock;
use std::{error, fs};
#[derive(Debug, PartialEq)]
pub enum Error {
CtyFileError(String),
CSVError(String),
ParseError(String),
PrefixNotFound,
CountryCodeNotFound,
CountryNotFound,
VersionEntityNotFound,
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl error::Error for Error {}
pub type CountryCode = String;
#[derive(Debug, Clone, PartialEq)]
pub enum Continent {
NorthAmerica,
SouthAmerica,
Europe,
Africa,
Oceania,
Asia,
Antarctica,
Unknown(String),
}
impl From<&str> for Continent {
fn from(value: &str) -> Self {
match value.to_uppercase().as_str() {
"NA" => Continent::NorthAmerica,
"SA" => Continent::SouthAmerica,
"EU" => Continent::Europe,
"AF" => Continent::Africa,
"OC" => Continent::Oceania,
"AS" => Continent::Asia,
"AN" => Continent::Antarctica,
_ => Continent::Unknown(value.to_string()),
}
}
}
impl Display for Continent {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Continent::NorthAmerica => "NA",
Continent::SouthAmerica => "SA",
Continent::Europe => "EU",
Continent::Africa => "AF",
Continent::Oceania => "OC",
Continent::Asia => "AS",
Continent::Antarctica => "AN",
Continent::Unknown(cont) => cont,
}
)
}
}
pub type DXCCEntity = u16;
pub type CQZone = u8;
pub type ITUZone = u8;
#[derive(Debug, Clone, PartialEq)]
pub struct Location {
pub lat: f32,
pub lon: f32,
}
pub type TimeOffset = f32;
#[derive(Debug, Clone, PartialEq)]
pub struct Country {
pub code: CountryCode,
pub name: String,
pub dxcc: DXCCEntity,
pub continent: Continent,
pub cq: CQZone,
pub itu: ITUZone,
pub location: Location,
pub time_off: TimeOffset,
}
impl Display for Country {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
pub type CountryMap = HashMap<CountryCode, Country>;
#[derive(Debug, Clone)]
struct OverrideData {
code: CountryCode,
cq: Option<CQZone>,
itu: Option<ITUZone>,
}
static RE_OVERRIDES: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"([A-Z0-9/=]+)(?:\((\d+)\))?(?:\[(\d+)\])?.*").unwrap());
pub struct CountryDatabase {
countries: CountryMap,
prefix_overrides: HashMap<String, OverrideData>,
prefixes: Vec<String>,
call_overrides: HashMap<String, OverrideData>,
version: String,
}
impl CountryDatabase {
pub fn new() -> Self {
Self::load(include_str!("../cty/cty.csv").as_bytes()).unwrap()
}
pub fn from_path(path: impl AsRef<str>) -> Result<Self, Error> {
Self::load(
fs::read(path.as_ref())
.map_err(|e| Error::CtyFileError(e.to_string()))?
.as_ref(),
)
}
fn load(data: &[u8]) -> Result<Self, Error> {
let mut countries = CountryMap::new();
let mut prefix_overrides: HashMap<String, OverrideData> = HashMap::new();
let mut call_overrides: HashMap<String, OverrideData> = HashMap::new();
let mut version = String::new();
let mut reader = csv::ReaderBuilder::new()
.delimiter(b',')
.has_headers(false)
.from_reader(data);
for res in reader.records() {
let record = res.map_err(|e| Error::CSVError(e.to_string()))?;
let code = record.get(0).unwrap_or_default().replace("*", "");
countries.insert(
code.to_string(),
Country {
code: code.to_string(),
name: record.get(1).unwrap_or_default().to_string(),
dxcc: record.get(2).unwrap_or_default().parse().map_err(|_| {
Error::ParseError(format!("DXCC for country code '{code}'"))
})?,
continent: record.get(3).unwrap_or_default().into(),
cq: record.get(4).unwrap_or_default().parse().map_err(|_| {
Error::ParseError(format!("CQ zone for country code '{code}'"))
})?,
itu: record.get(5).unwrap_or_default().parse().map_err(|_| {
Error::ParseError(format!("ITU zone for country code '{code}'"))
})?,
location: Location {
lat: record.get(6).unwrap_or_default().parse().map_err(|_| {
Error::ParseError(format!("longitude for country code '{code}'"))
})?,
lon: record.get(7).unwrap_or_default().parse().map_err(|_| {
Error::ParseError(format!("latitude for country code '{code}'"))
})?,
},
time_off: record.get(8).unwrap_or_default().parse().map_err(|_| {
Error::ParseError(format!("time offset for country code '{code}'"))
})?,
},
);
for pfx in record
.get(9)
.unwrap_or_default()
.replace(";", "")
.split(" ")
{
let (pfx, cq, itu) = if let Some(cap) = Regex::captures(&RE_OVERRIDES, pfx) {
(
cap.get(1).map(|v| v.as_str().to_string()),
cap.get(2).map(|v| v.as_str().parse::<CQZone>().unwrap()),
cap.get(3).map(|v| v.as_str().parse::<ITUZone>().unwrap()),
)
} else {
(None, None, None)
};
let Some(pfx) = pfx else { continue };
if let Some(pfx) = pfx.strip_prefix("=") {
if code == "VE" && pfx.starts_with("VER") {
version = pfx.to_string();
continue;
}
if !call_overrides.contains_key(pfx) {
call_overrides.insert(
pfx.to_string(),
OverrideData {
code: code.to_string(),
cq,
itu,
},
);
}
} else {
prefix_overrides.insert(
pfx,
OverrideData {
code: code.to_string(),
cq,
itu,
},
);
}
}
}
let mut prefixes = prefix_overrides
.clone()
.keys()
.map(|pfx| pfx.to_string())
.collect::<Vec<String>>();
prefixes.sort();
Ok(Self {
countries,
prefix_overrides,
prefixes,
call_overrides,
version,
})
}
pub fn version(&self) -> &String {
&self.version
}
pub fn version_entity(&self) -> Result<(CountryCode, String), Error> {
let cty = self
.country("VERSION")
.map_err(|_| Error::VersionEntityNotFound)?;
Ok((cty.code, cty.name))
}
pub fn prefix(&self, call: impl AsRef<str>) -> Result<String, Error> {
let mut part = String::new();
let idx: usize = 0;
let mut pfx = String::new();
for c in call.as_ref().to_uppercase().chars() {
part.push(c);
if let Some(idx) = self.prefixes[idx..].iter().position(|r| r == &part) {
pfx = self.prefixes[idx].to_string()
} else {
continue;
}
}
if !pfx.is_empty() {
Ok(pfx)
} else {
Err(Error::PrefixNotFound)
}
}
fn country_code(&self, call: impl AsRef<str>) -> Result<&OverrideData, Error> {
if let Some(ord) = self.call_overrides.get(&call.as_ref().to_uppercase()) {
return Ok(ord);
}
if let Some(ord) = self
.prefix_overrides
.get(&self.prefix(&call).map_err(|_| Error::CountryCodeNotFound)?)
{
return Ok(ord);
}
Err(Error::CountryCodeNotFound)
}
pub fn country(&self, call: impl AsRef<str>) -> Result<Country, Error> {
let data = self.country_code(&call)?;
if let Some(cty) = self.countries.get(&data.code) {
Ok(Country {
cq: if let Some(cq) = data.cq { cq } else { cty.cq },
itu: if let Some(itu) = data.itu {
itu
} else {
cty.itu
},
..cty.clone()
})
} else {
Err(Error::CountryNotFound)
}
}
}
impl Default for CountryDatabase {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn setup() -> CountryDatabase {
CountryDatabase::from_path("test_data/cty.csv").expect("error loading test data")
}
#[test]
fn test_100_version() {
let cdb = setup();
assert_eq!(cdb.version(), "VER20260603");
assert_eq!(
cdb.version_entity(),
Ok(("3DA".to_string(), "Kingdom of Eswatini".to_string()))
);
}
#[test]
fn test_101_cur_version() {
let cdb = CountryDatabase::new();
assert_eq!(cdb.version(), "VER20260611");
assert_eq!(
cdb.version_entity(),
Ok(("ZK3".to_string(), "Tokelau Islands".to_string()))
);
}
#[test]
fn test_110_prefix() {
let cdb = setup();
assert_eq!(cdb.prefix("DF1ASC"), Ok("DF".to_string()));
assert_eq!(cdb.prefix("DK50K32MR"), Ok("DK".to_string()));
assert_eq!(cdb.prefix("XX1XX"), Err(Error::PrefixNotFound));
}
#[test]
fn test_120_search() {
let cdb = setup();
let cty = cdb.country("DF1ASC").unwrap();
assert_eq!(cty.code, "DL");
assert_eq!(cty.continent, Continent::Europe);
assert_eq!(cdb.country("XX1XX"), Err(Error::CountryCodeNotFound));
}
#[test]
fn test_130_search_w_override() {
let cdb = setup();
let cty = cdb.country("LU1ZA").unwrap();
assert_eq!(cty.code, "VP8/o");
assert_eq!(cty.continent, Continent::SouthAmerica);
let cty = cdb.country("4U1WB").unwrap();
assert_eq!(cty.code, "K");
assert_eq!(cty.continent, Continent::NorthAmerica);
assert_eq!(cty.cq, 5);
assert_eq!(cty.itu, 8);
let cty = cdb.country("PP6XX").unwrap();
assert_eq!(cty.code, "PY");
assert_eq!(cty.continent, Continent::SouthAmerica);
assert_eq!(cty.itu, 13);
assert_eq!(cty.cq, 11);
}
}