1use std::{collections::HashMap, sync::LazyLock};
2
3use serde::{Deserialize, Serialize};
4
5pub const UNKNOWN_CODE: &str = "XX";
6pub const UNKNOWN: &str = "Unknown";
7
8const COUNTRIES_JSON: &[u8] = include_bytes!("./assets/countries.json");
9
10#[derive(Clone, Debug, Deserialize, Serialize)]
11pub struct Country {
12 pub code: String,
13 pub name: String,
14}
15
16impl Default for Country {
17 fn default() -> Self {
18 Self {
19 code: String::from(UNKNOWN_CODE),
20 name: String::from(UNKNOWN),
21 }
22 }
23}
24
25static COUNTRIES: LazyLock<HashMap<String, Country>> = LazyLock::new(|| {
26 let countries: Vec<Country> = serde_json::from_slice(COUNTRIES_JSON)
27 .unwrap_or_else(|err| panic!("countries: error parsing countries JSON: {err}"));
28
29 return countries
30 .iter()
31 .map(|country| (country.code.clone(), country.clone()))
32 .collect();
33});
34
35pub fn countries() -> &'static HashMap<String, Country> {
36 &COUNTRIES
37}
38
39pub fn name(code: &str) -> String {
40 let countries = countries();
41 return countries
42 .get(code)
43 .map(|country| country.clone())
44 .unwrap_or_default()
45 .name;
46}