Skip to content

Commit 5e4f212

Browse files
committed
impl Pattern for char array
1 parent 99d6692 commit 5e4f212

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

library/core/src/str/pattern.rs

+40
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
//! assert_eq!(s.find("you"), Some(4));
2323
//! // char pattern
2424
//! assert_eq!(s.find('n'), Some(2));
25+
//! // array of chars pattern
26+
//! assert_eq!(s.find(&['a', 'e', 'i', 'o', 'u']), Some(1));
2527
//! // slice of chars pattern
2628
//! assert_eq!(s.find(&['a', 'e', 'i', 'o', 'u'][..]), Some(1));
2729
//! // closure pattern
@@ -79,6 +81,11 @@ use crate::slice::memchr;
7981
/// assert_eq!("abaaa".find('b'), Some(1));
8082
/// assert_eq!("abaaa".find('c'), None);
8183
///
84+
/// // &[char; N]
85+
/// assert_eq!("ab".find(&['b', 'a']), Some(0));
86+
/// assert_eq!("abaaa".find(&['a', 'z']), Some(0));
87+
/// assert_eq!("abaaa".find(&['c', 'd']), None);
88+
///
8289
/// // &[char]
8390
/// assert_eq!("ab".find(&['b', 'a'][..]), Some(0));
8491
/// assert_eq!("abaaa".find(&['a', 'z'][..]), Some(0));
@@ -601,6 +608,13 @@ where
601608
}
602609
}
603610

611+
impl<const N: usize> MultiCharEq for &[char; N] {
612+
#[inline]
613+
fn matches(&mut self, c: char) -> bool {
614+
self.iter().any(|&m| m == c)
615+
}
616+
}
617+
604618
impl MultiCharEq for &[char] {
605619
#[inline]
606620
fn matches(&mut self, c: char) -> bool {
@@ -752,6 +766,32 @@ macro_rules! searcher_methods {
752766
};
753767
}
754768

769+
/// Associated type for `<[char; N] as Pattern<'a>>::Searcher`.
770+
#[derive(Clone, Debug)]
771+
pub struct CharArraySearcher<'a, 'b, const N: usize>(
772+
<MultiCharEqPattern<&'b [char; N]> as Pattern<'a>>::Searcher,
773+
);
774+
775+
/// Searches for chars that are equal to any of the [`char`]s in the array.
776+
///
777+
/// # Examples
778+
///
779+
/// ```
780+
/// assert_eq!("Hello world".find(&['l', 'l']), Some(2));
781+
/// assert_eq!("Hello world".find(&['l', 'l']), Some(2));
782+
/// ```
783+
impl<'a, 'b, const N: usize> Pattern<'a> for &'b [char; N] {
784+
pattern_methods!(CharArraySearcher<'a, 'b, N>, MultiCharEqPattern, CharArraySearcher);
785+
}
786+
787+
unsafe impl<'a, 'b, const N: usize> Searcher<'a> for CharArraySearcher<'a, 'b, N> {
788+
searcher_methods!(forward);
789+
}
790+
791+
unsafe impl<'a, 'b, const N: usize> ReverseSearcher<'a> for CharArraySearcher<'a, 'b, N> {
792+
searcher_methods!(reverse);
793+
}
794+
755795
/////////////////////////////////////////////////////////////////////////////
756796
// Impl for &[char]
757797
/////////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)