Skip to content

Commit 237606c

Browse files
committed
core: add core::pattern::Predicate wrapper type
To work around orphan rules, introduce a wrapper type for predicate functions to be used as pattern. Specefically, if we want to add predicat pattern implementation for OsStr type, doing it with a naked `FnMut` results in compile-time errors: error[E0210]: type parameter `F` must be covered by another type when it appears before the first local type (`OsStr`) impl<'hs, F: FnMut(char) -> bool> core::pattern::Pattern<&'hs OsStr> for F { ^ type parameter `F` must be covered by another type when it appears before the first local type (`OsStr`)
1 parent 06e6d69 commit 237606c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

library/core/src/pattern.rs

+42
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,48 @@ pub unsafe trait ReverseSearcher<H: Haystack>: Searcher<H> {
457457
/// from which side it is searched.
458458
pub trait DoubleEndedSearcher<H: Haystack>: ReverseSearcher<H> {}
459459

460+
/// A wrapper around single-argument function returning a boolean,
461+
/// i.e. a predicate function.
462+
///
463+
/// `Predicate` objects are created with [`predicate`] function.
464+
#[derive(Clone, Debug)]
465+
pub struct Predicate<F>(F);
466+
467+
/// Constructs a wrapper for a single-argument function returning a boolean,
468+
/// i.e. a predicate function.
469+
///
470+
/// This is intended to be used as a pattern when working with haystacks which
471+
/// (for whatever reason) cannot support naked function traits as patterns.
472+
pub fn predicate<T, F: FnMut(T) -> bool>(pred: F) -> Predicate<F> {
473+
Predicate(pred)
474+
}
475+
476+
impl<F> Predicate<F> {
477+
/// Executes the predicate returning its result.
478+
pub fn test<T>(&mut self, element: T) -> bool
479+
where
480+
F: FnMut(T) -> bool,
481+
{
482+
self.0(element)
483+
}
484+
485+
/// Returns reference to the wrapped predicate function.
486+
pub fn as_fn<T>(&mut self) -> &mut F
487+
where
488+
F: FnMut(T) -> bool,
489+
{
490+
&mut self.0
491+
}
492+
493+
/// Consumes this object and returns wrapped predicate function.
494+
pub fn into_fn<T>(self) -> F
495+
where
496+
F: FnMut(T) -> bool,
497+
{
498+
self.0
499+
}
500+
}
501+
460502
//////////////////////////////////////////////////////////////////////////////
461503
// Internal EmptyNeedleSearcher helper
462504
//////////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)