iconf/
configs.rs

1
2use std::fs::File;
3use std::io::prelude::*;
4use toml;
5
6// 配置对象
7pub static mut CONFIG: Option<&mut Conf> = None;
8
9#[derive(Debug)]
10pub struct Conf {
11    file_path: String,
12    settings: toml::Value,
13}
14
15impl Conf{
16    fn new(file_path: String, settings: toml::Value) -> Conf{
17        Conf{file_path, settings}
18    }
19
20    pub fn file_path(&self) -> String {
21        String::from(&self.file_path)
22    }
23    pub fn settings(&self) -> &toml::Value {
24        &self.settings
25    }
26}
27
28/// # init 初始化解析 toml 配置文件
29pub unsafe fn init(file_path: String) -> std::io::Result<()> {
30
31    let mut file = File::open(&file_path)?;
32    let mut contents = String::new();
33    file.read_to_string(&mut contents)?;
34    let value = contents.parse::<toml::Value>().unwrap();
35
36    let c:Conf = Conf::new(file_path.to_string(), value);
37
38    unsafe {
39        // 将`c`从内存中泄漏,变成`'static`生命周期
40        let bc = Box::new(c);
41        CONFIG = Some(Box::leak(bc));
42
43        // println!("{:?}", CONFIG);
44        // let s = CONFIG.as_ref().unwrap();
45        // println!("{:?}", s);
46        // println!("{}", s.file_path());
47        // println!("{:?}", s.settings);
48    }
49
50    Ok(())
51}
52
53/// # get_str 读取字符串配置
54/// # 参数
55/// key1、key2
56/// settings()[key1][key2].as_str()
57pub unsafe fn get_str(key1: &str, key2: &str) -> String {
58    let cf = CONFIG.as_ref().unwrap();
59    cf.settings()[key1][key2].as_str().unwrap().to_string()
60}
61
62/// # get_int 读取 i64 配置
63pub unsafe fn get_int(key1: &str, key2: &str) -> i64 {
64    let cf = CONFIG.as_ref().unwrap();
65    cf.settings()[key1][key2].as_integer().unwrap()
66}
67
68/// # get_float 读取 f64 配置
69pub unsafe fn get_float(key1: &str, key2: &str) -> f64 {
70    let cf = CONFIG.as_ref().unwrap();
71    cf.settings()[key1][key2].as_float().unwrap()
72}
73
74/// # get_bool 读取 bool 配置
75pub unsafe fn get_bool(key1: &str, key2: &str) -> bool {
76    let cf = CONFIG.as_ref().unwrap();
77    cf.settings()[key1][key2].as_bool().unwrap()
78}