prts/headhunt_tool/
toml_banner.rs

1use std::{collections::HashMap};
2use serde::{Serialize, Deserialize};
3use toml;
4use crate::{BannerType, Banner};
5
6use std::fs::File;
7use std::io::prelude::*;
8use std::path::Path;
9
10#[derive(Deserialize, Serialize)]
11pub(crate) struct TomlBanner{
12    pub(crate) pool: HashMap<String, Vec<String>>,
13    pub(crate) rate_up: HashMap<String, Vec<String>>,
14    pub(crate) banner_type: BannerType
15}
16
17#[allow(dead_code)]
18impl TomlBanner {
19    pub fn from_banner(banner: &Banner) -> Self {
20        let mut pool = HashMap::new();
21        for (k, v) in banner.pool.iter() {
22            pool.insert(k.to_string(), v.to_owned());
23        };
24
25        let mut rate_up = HashMap::new();
26        for (k, v) in banner.rate_up.iter() {
27            rate_up.insert(k.to_string(), v.to_owned());
28        };
29
30        Self {
31            pool, rate_up,
32            banner_type: banner.banner_type
33        }
34    }
35
36    pub fn from_toml_file(file_name: String) -> Self {
37        let path = Path::new(&file_name);
38        let display = path.display();
39
40        // Open the path in read-only mode, returns `io::Result<File>`
41        let mut file = match File::open(&path) {
42            Err(why) => panic!("couldn't open {}: {}", display, why),
43            Ok(file) => file,
44        };
45
46        // Read the file contents into a string, returns `io::Result<usize>`
47        let mut s = String::new();
48        match file.read_to_string(&mut s) {
49            Err(why) => panic!("couldn't read {}: {}", display, why),
50            Ok(_) => (),
51        }
52
53        toml::from_str::<Self>(&s).unwrap()
54    }
55
56    pub fn to_string(&self) -> String {
57        match toml::to_string(self) {
58            Ok(res) => res,
59            Err(why) => {
60                println!("[Panik!!!] Cannot parse to string: {}", why);
61                "".to_owned()
62            }
63        }
64    }
65}