From 8a4316df9fdf5bae70d8820ce28e590216a2ff05 Mon Sep 17 00:00:00 2001 From: Narawit Rakket Date: Wed, 13 Jul 2022 00:07:48 +0700 Subject: [PATCH] refactor: change input type from `String` to `AsRef` This improve flexibility and reduce `String` allocation --- src/config_file.rs | 25 +++++++++++++++---------- src/main.rs | 3 +-- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/config_file.rs b/src/config_file.rs index 642eb38..68e3658 100644 --- a/src/config_file.rs +++ b/src/config_file.rs @@ -101,19 +101,28 @@ impl Config { } } - /// This constructs a Config struct with a passed file path [String]. - pub fn from_file(file: String) -> Option { - match fs::read(&file) { + /// This constructs a Config struct with a passed file path. + pub fn from_file>(file: P) -> Option { + let file = file.as_ref(); + match fs::read(file) { Ok(f) => match Self::from_yaml(&String::from_utf8_lossy(&f)) { Ok(c) => Some(c), Err(e) => { - print_error!("Configuration file {} format error, {}.", &file, e); + print_error!( + "Configuration file {} format error, {}.", + file.to_string_lossy(), + e + ); None } }, Err(e) => { 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 } @@ -176,11 +185,7 @@ impl Config { impl Default for Config { fn default() -> Self { if let Some(p) = Self::config_file_path() { - if let Some(c) = Self::from_file( - p.join([CONF_FILE_NAME, YAML_LONG_EXT].join(".")) - .to_string_lossy() - .to_string(), - ) { + if let Some(c) = Self::from_file(p.join([CONF_FILE_NAME, YAML_LONG_EXT].join("."))) { return c; } } diff --git a/src/main.rs b/src/main.rs index ceb4216..24b8bd5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -107,8 +107,7 @@ fn main() { } else if matches.is_present("config-file") { let path = matches .value_of("config-file") - .expect("Invalid config file path") - .into(); + .expect("Invalid config file path"); Config::from_file(path).expect("Provided file path is invalid") } else {