s0-meter/src/cfg_reader.rs

56 lines
1.3 KiB
Rust
Raw Permalink Normal View History

#[cfg(test)]
#[path = "./cfg_reader_test.rs"]
mod cfg_reader_test;
2021-02-11 22:09:29 +01:00
use serde_derive::Deserialize;
use std::fs::File;
use std::{error::Error, io::Read};
extern crate toml;
#[derive(Deserialize)]
pub struct S0Channel {
pub id: u8,
pub gpio: u8,
2021-02-11 22:09:29 +01:00
}
#[derive(Deserialize)]
pub struct Config {
channel: Vec<S0Channel>,
}
impl Config {
pub fn channels(&self) -> &Vec<S0Channel> {
&self.channel
}
2021-02-11 22:09:29 +01:00
}
// use std::any::type_name;
// fn type_of<T>(_: T) -> &'static str {
// type_name::<T>()
// }
const MAX_CONFIG_FILE_SIZE: u64 = 1_000_000u64;
pub fn parse_file(config_file_name: &str) -> Result<Config, Box<dyn Error>> {
let mut cfg_file = File::open(String::from(config_file_name))?;
let cfg_file_meta = &cfg_file.metadata()?;
let cfg_file_len = &cfg_file_meta.len();
if cfg_file_len > &MAX_CONFIG_FILE_SIZE {
return Err(From::from(format!(
"Size of config file is {} exceeds the limit of {}",
&cfg_file_len, MAX_CONFIG_FILE_SIZE
)));
}
let mut cfg_file_content = String::new();
cfg_file.read_to_string(&mut cfg_file_content).unwrap();
parse_string(&cfg_file_content)
}
fn parse_string(cfg_str: &String) -> Result<Config, Box<dyn Error>> {
match toml::from_str(cfg_str) {
Ok(cfg) => Ok(cfg),
Err(err) => Err(From::from(err)),
}
}