From d1924aa758c53f1de37ceef3f90dc69be90779d7 Mon Sep 17 00:00:00 2001 From: Steppy Date: Mon, 3 Feb 2025 18:01:54 +0100 Subject: [PATCH] Refactor FileMatcher to use OsString --- src/file.rs | 22 ++++++++++++---------- src/main.rs | 4 ++-- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/src/file.rs b/src/file.rs index 2e9d9db..6de8cd1 100644 --- a/src/file.rs +++ b/src/file.rs @@ -1,5 +1,7 @@ use std::error::Error; +use std::ffi::{OsStr, OsString}; use std::fmt::{Display, Formatter}; +use std::os::unix::ffi::OsStrExt; use std::path::PathBuf; //TODO this whole structure should probably use OsString instead of String @@ -83,40 +85,40 @@ impl Display for FileInfoError { impl Error for FileInfoError {} -//TODO this structure should probably work with OsString instead of String #[derive(Debug, Clone)] pub struct FileMatcher { - name: String, - extension: Option, + name: OsString, + extension: Option, } impl FileMatcher { pub fn from(name: S) -> Self where - S: ToString, + S: AsRef, { Self { - name: name.to_string(), + name: name.as_ref().to_owned(), extension: None, } } pub fn and_extension(self, extension: S) -> Self where - S: ToString, + S: AsRef, { Self { - extension: Some(extension.to_string()), + extension: Some(extension.as_ref().to_owned()), ..self } } - pub fn matches(&self, file_name: &str) -> bool { - file_name.starts_with(&self.name) + pub fn matches(&self, file_name: S) -> bool where S: AsRef { + let file_name = file_name.as_ref(); + file_name.as_bytes().starts_with(self.name.as_bytes()) && self .extension .as_ref() - .is_none_or(|extension| file_name.ends_with(extension)) + .is_none_or(|extension| file_name.as_bytes().ends_with(extension.as_bytes())) } } diff --git a/src/main.rs b/src/main.rs index ff06a4a..585af87 100644 --- a/src/main.rs +++ b/src/main.rs @@ -359,7 +359,7 @@ fn main() -> Result<(), String> { //TODO avoid lossy match present_file_names .iter() - .filter(|file| file_matcher.matches(&file.to_string_lossy())) + .filter(|file| file_matcher.matches(file)) .map(|file| { FileAction::new( file, @@ -377,7 +377,7 @@ fn main() -> Result<(), String> { OldVersionPolicy::Delete => { //TODO avoid lossy match let mut actions = present_file_names.iter() - .filter(|file| file_matcher.matches(&file.to_string_lossy())) + .filter(|file| file_matcher.matches(file)) .map(|file| { //special case -> file has the same name as current file, then we just need to replace it if *file == file_name {