refactor: change input type from String to AsRef<Path>

This improve flexibility and reduce `String` allocation
This commit is contained in:
Narawit Rakket 2022-07-13 00:07:48 +07:00 committed by Abin Simon
parent 55c2ef1a7b
commit 8a4316df9f
2 changed files with 16 additions and 12 deletions

View file

@ -101,19 +101,28 @@ impl Config {
} }
} }
/// This constructs a Config struct with a passed file path [String]. /// This constructs a Config struct with a passed file path.
pub fn from_file(file: String) -> Option<Self> { pub fn from_file<P: AsRef<Path>>(file: P) -> Option<Self> {
match fs::read(&file) { let file = file.as_ref();
match fs::read(file) {
Ok(f) => match Self::from_yaml(&String::from_utf8_lossy(&f)) { Ok(f) => match Self::from_yaml(&String::from_utf8_lossy(&f)) {
Ok(c) => Some(c), Ok(c) => Some(c),
Err(e) => { Err(e) => {
print_error!("Configuration file {} format error, {}.", &file, e); print_error!(
"Configuration file {} format error, {}.",
file.to_string_lossy(),
e
);
None None
} }
}, },
Err(e) => { Err(e) => {
if e.kind() != io::ErrorKind::NotFound { if e.kind() != io::ErrorKind::NotFound {
print_error!("Can not open config file {}: {}.", &file, e); print_error!(
"Can not open config file {}: {}.",
file.to_string_lossy(),
e
);
} }
None None
} }
@ -176,11 +185,7 @@ impl Config {
impl Default for Config { impl Default for Config {
fn default() -> Self { fn default() -> Self {
if let Some(p) = Self::config_file_path() { if let Some(p) = Self::config_file_path() {
if let Some(c) = Self::from_file( if let Some(c) = Self::from_file(p.join([CONF_FILE_NAME, YAML_LONG_EXT].join("."))) {
p.join([CONF_FILE_NAME, YAML_LONG_EXT].join("."))
.to_string_lossy()
.to_string(),
) {
return c; return c;
} }
} }

View file

@ -107,8 +107,7 @@ fn main() {
} else if matches.is_present("config-file") { } else if matches.is_present("config-file") {
let path = matches let path = matches
.value_of("config-file") .value_of("config-file")
.expect("Invalid config file path") .expect("Invalid config file path");
.into();
Config::from_file(path).expect("Provided file path is invalid") Config::from_file(path).expect("Provided file path is invalid")
} else { } else {