location_rs/
config.rs

1use serde::Deserialize;
2use std::collections::HashMap;
3use crate::error::ParseError;
4
5/// 国家信息配置
6#[derive(Debug, Deserialize, Clone)]
7pub struct CountryInfo {
8    /// ISO 3166-1 alpha-2代码
9    pub alpha2: String,
10    /// ISO 3166-1 alpha-3代码
11    pub alpha3: String,
12    /// ISO 3166-1 数字代码
13    pub numeric: String,
14    /// 英文名称
15    pub name_en: String,
16    /// 简体中文名称
17    pub name_zh_cn: String,
18    /// 繁体中文名称
19    pub name_zh_tw: String,
20    /// 所属地区
21    pub region: String,
22}
23
24/// 解析器设置
25#[derive(Debug, Deserialize, Clone)]
26pub struct ParserSettings {
27    /// 是否区分大小写
28    pub case_sensitive: bool,
29    /// 是否启用模糊匹配
30    pub fuzzy_match: bool,
31    /// 解析超时时间(毫秒)
32    pub timeout_ms: u64,
33}
34
35/// 模式配置
36#[derive(Debug, Deserialize, Clone)]
37pub struct PatternConfig {
38    /// 前缀模式
39    pub prefix_patterns: Vec<String>,
40    /// 后缀模式
41    pub suffix_patterns: Vec<String>,
42}
43
44/// 完整配置
45#[derive(Debug, Deserialize, Clone)]
46pub struct Configuration {
47    /// 配置版本
48    pub version: String,
49    /// 国家信息列表
50    pub countries: Vec<CountryInfo>,
51    /// 模式配置
52    pub patterns: PatternConfig,
53    /// 解析器设置
54    pub settings: ParserSettings,
55}
56
57impl Configuration {
58    /// 从嵌入的JSON字符串加载配置
59    pub fn load() -> Result<Self, ParseError> {
60        let config_str = include_str!("../resources/countries.json");
61        
62        serde_json::from_str(config_str)
63            .map_err(|e| ParseError::config_error(&format!("配置解析失败: {}", e)))
64    }
65    
66    /// 创建国家代码到国家信息的映射
67    pub fn create_country_mapping(&self) -> HashMap<String, &CountryInfo> {
68        let mut mapping = HashMap::new();
69        
70        for country in &self.countries {
71            // 添加alpha-2代码
72            mapping.insert(country.alpha2.clone(), country);
73            
74            // 添加alpha-3代码
75            mapping.insert(country.alpha3.clone(), country);
76            
77            // 添加英文名称
78            mapping.insert(country.name_en.clone(), country);
79            
80            // 添加简体中文名称
81            mapping.insert(country.name_zh_cn.clone(), country);
82            
83            // 添加繁体中文名称
84            mapping.insert(country.name_zh_tw.clone(), country);
85        }
86        
87        mapping
88    }
89    
90    /// 获取解析器设置
91    pub fn get_settings(&self) -> &ParserSettings {
92        &self.settings
93    }
94    
95    /// 获取模式配置
96    pub fn get_patterns(&self) -> &PatternConfig {
97        &self.patterns
98    }
99    
100    /// 获取所有国家信息
101    pub fn get_countries(&self) -> &[CountryInfo] {
102        &self.countries
103    }
104}