1use serde::Deserialize;
2use std::collections::HashMap;
3use crate::error::ParseError;
4
5#[derive(Debug, Deserialize, Clone)]
7pub struct CountryInfo {
8 pub alpha2: String,
10 pub alpha3: String,
12 pub name_en: String,
14 pub name_zh_cn: String,
16 pub name_zh_tw: String,
18 pub abbreviations: Vec<String>,
20}
21
22#[derive(Debug, Deserialize, Clone)]
24pub struct ParserSettings {
25 pub case_sensitive: bool,
27 pub fuzzy_match: bool,
29 pub timeout_ms: u64,
31}
32
33#[derive(Debug, Deserialize, Clone)]
35pub struct PatternConfig {
36 pub prefix_patterns: Vec<String>,
38 pub suffix_patterns: Vec<String>,
40}
41
42#[derive(Debug, Deserialize, Clone)]
44pub struct CountriesConfig {
45 pub version: String,
47 pub countries: Vec<CountryInfo>,
49}
50
51#[derive(Debug, Clone)]
53pub struct Configuration {
54 pub countries_config: CountriesConfig,
56 pub patterns: PatternConfig,
58 pub settings: ParserSettings,
60}
61
62impl Configuration {
63 pub fn load() -> Result<Self, ParseError> {
65 let countries_str = include_str!("../resources/countries.json");
67 let countries_config: CountriesConfig = serde_json::from_str(countries_str)
68 .map_err(|e| ParseError::config_error(&format!("国家配置解析失败: {}", e)))?;
69
70 let patterns_str = include_str!("../resources/patterns.json");
72 let patterns: PatternConfig = serde_json::from_str(patterns_str)
73 .map_err(|e| ParseError::config_error(&format!("模式配置解析失败: {}", e)))?;
74
75 let settings_str = include_str!("../resources/settings.json");
77 let settings: ParserSettings = serde_json::from_str(settings_str)
78 .map_err(|e| ParseError::config_error(&format!("设置配置解析失败: {}", e)))?;
79
80 Ok(Configuration {
81 countries_config,
82 patterns,
83 settings,
84 })
85 }
86
87 pub fn create_country_mapping(&self) -> HashMap<String, &CountryInfo> {
89 let mut mapping = HashMap::new();
90
91 for country in &self.countries_config.countries {
92 mapping.insert(country.alpha2.clone(), country);
94
95 mapping.insert(country.alpha3.clone(), country);
97
98 mapping.insert(country.name_en.clone(), country);
100
101 mapping.insert(country.name_zh_cn.clone(), country);
103
104 mapping.insert(country.name_zh_tw.clone(), country);
106
107 for abbr in &country.abbreviations {
109 mapping.insert(abbr.clone(), country);
110 }
111 }
112
113 mapping
114 }
115
116 pub fn get_settings(&self) -> &ParserSettings {
118 &self.settings
119 }
120
121 pub fn get_patterns(&self) -> &PatternConfig {
123 &self.patterns
124 }
125
126 pub fn get_countries(&self) -> &[CountryInfo] {
128 &self.countries_config.countries
129 }
130
131 pub fn get_version(&self) -> &str {
133 &self.countries_config.version
134 }
135}