Accept owned and borrowed Regex

For performance, it is desirable to accept &Regex instead of Regex.
By changing changing to impl Borrow<Regex>, all existing code
remains valid, but &Regex is also accepted.
This commit is contained in:
Mark 2021-11-30 22:14:23 +01:00
parent 74140bd497
commit 36a68cbc9b
No known key found for this signature in database
GPG Key ID: 96F69FF3C6F52F8A
3 changed files with 17 additions and 4 deletions

View File

@ -5,6 +5,8 @@ use crate::helper::has_executable_extension;
use either::Either;
#[cfg(feature = "regex")]
use regex::Regex;
#[cfg(feature = "regex")]
use std::borrow::Borrow;
use std::env;
use std::ffi::OsStr;
#[cfg(feature = "regex")]
@ -81,7 +83,7 @@ impl Finder {
#[cfg(feature = "regex")]
pub fn find_re<T>(
&self,
binary_regex: Regex,
binary_regex: impl Borrow<Regex>,
paths: Option<T>,
binary_checker: CompositeChecker,
) -> Result<impl Iterator<Item = PathBuf>>
@ -99,7 +101,7 @@ impl Finder {
.map(|e| e.path())
.filter(move |p| {
if let Some(unicode_file_name) = p.file_name().unwrap().to_str() {
binary_regex.is_match(unicode_file_name)
binary_regex.borrow().is_match(unicode_file_name)
} else {
false
}

View File

@ -26,6 +26,8 @@ mod helper;
#[cfg(feature = "regex")]
use regex::Regex;
#[cfg(feature = "regex")]
use std::borrow::Borrow;
use std::env;
use std::fmt;
use std::path;
@ -87,7 +89,7 @@ pub fn which_all<T: AsRef<OsStr>>(binary_name: T) -> Result<impl Iterator<Item =
/// assert_eq!(binaries, python_paths);
/// ```
#[cfg(feature = "regex")]
pub fn which_re(regex: Regex) -> Result<impl Iterator<Item = path::PathBuf>> {
pub fn which_re(regex: impl Borrow<Regex>) -> Result<impl Iterator<Item = path::PathBuf>> {
which_re_in(regex, env::var_os("PATH"))
}
@ -124,7 +126,7 @@ where
/// assert_eq!(binaries, python_paths);
/// ```
#[cfg(feature = "regex")]
pub fn which_re_in<T>(regex: Regex, paths: Option<T>) -> Result<impl Iterator<Item = path::PathBuf>>
pub fn which_re_in<T>(regex: impl Borrow<Regex>, paths: Option<T>) -> Result<impl Iterator<Item = path::PathBuf>>
where
T: AsRef<OsStr>,
{

View File

@ -162,6 +162,15 @@ fn test_which_re_in_without_matches() {
assert_eq!(result, Vec::<PathBuf>::new())
}
#[test]
#[cfg(all(unix, feature = "regex"))]
fn test_which_re_accepts_owned_and_borrow() {
which::which_re(Regex::new(r".").unwrap());
which::which_re(&Regex::new(r".").unwrap());
which::which_re_in(Regex::new(r".").unwrap(), Some("pth"));
which::which_re_in(&Regex::new(r".").unwrap(), Some("pth"));
}
#[test]
#[cfg(unix)]
fn test_which_extension() {