|
| 1 | +// Copyright (c) 2018 The predicates-rs Project Developers. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 4 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 5 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 6 | +// option. This file may not be copied, modified, or distributed |
| 7 | +// except according to those terms. |
| 8 | + |
| 9 | +//! Name predicate expressions. |
| 10 | +
|
| 11 | +use std::fmt; |
| 12 | +use std::marker::PhantomData; |
| 13 | + |
| 14 | +use Predicate; |
| 15 | + |
| 16 | +/// Augment an existing predicate with a name. |
| 17 | +/// |
| 18 | +/// This is created by the `PredicateNameExt::name` function. |
| 19 | +#[derive(Debug)] |
| 20 | +pub struct NamePredicate<M, Item> |
| 21 | +where |
| 22 | + M: Predicate<Item>, |
| 23 | + Item: ?Sized, |
| 24 | +{ |
| 25 | + inner: M, |
| 26 | + name: &'static str, |
| 27 | + _phantom: PhantomData<Item>, |
| 28 | +} |
| 29 | + |
| 30 | +impl<M, Item> Predicate<Item> for NamePredicate<M, Item> |
| 31 | +where |
| 32 | + M: Predicate<Item>, |
| 33 | + Item: ?Sized, |
| 34 | +{ |
| 35 | + fn eval(&self, item: &Item) -> bool { |
| 36 | + self.inner.eval(item) |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +impl<M, Item> fmt::Display for NamePredicate<M, Item> |
| 41 | +where |
| 42 | + M: Predicate<Item>, |
| 43 | + Item: ?Sized, |
| 44 | +{ |
| 45 | + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 46 | + write!(f, "{}", self.name) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/// `Predicate` extension that adds naming predicate expressions. |
| 51 | +pub trait PredicateNameExt<Item: ?Sized> |
| 52 | +where |
| 53 | + Self: Predicate<Item>, |
| 54 | +{ |
| 55 | + /// Name a predicate expression. |
| 56 | + /// |
| 57 | + /// # Examples |
| 58 | + /// |
| 59 | + /// ``` |
| 60 | + /// use predicates::prelude::*; |
| 61 | + /// |
| 62 | + /// let predicate_fn = predicate::str::is_empty().not().name("non-empty"); |
| 63 | + /// println!("{}", predicate_fn); |
| 64 | + /// ``` |
| 65 | + fn name(self, name: &'static str) -> NamePredicate<Self, Item> |
| 66 | + where |
| 67 | + Self: Sized, |
| 68 | + { |
| 69 | + NamePredicate { |
| 70 | + inner: self, |
| 71 | + name, |
| 72 | + _phantom: PhantomData, |
| 73 | + } |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +impl<P, Item> PredicateNameExt<Item> for P |
| 78 | +where |
| 79 | + P: Predicate<Item>, |
| 80 | + Item: ?Sized, |
| 81 | +{ |
| 82 | +} |
0 commit comments