1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
// Copyright (c) 2018 The predicates-rs Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/license/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Definition of a constant (always true or always false) `Predicate`. use std::fmt; use std::marker::PhantomData; use Predicate; /// Predicate that always returns a constant (boolean) result. /// /// This is created by the `predicate::always` and `predicate::never` functions. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct BooleanPredicate<Item> { retval: bool, _phantom: PhantomData<Item>, } impl<Item> Predicate<Item> for BooleanPredicate<Item> { fn eval(&self, _variable: &Item) -> bool { self.retval } } impl<Item> fmt::Display for BooleanPredicate<Item> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.retval) } } /// Creates a new `Predicate` that always returns `true`. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::always(); /// assert_eq!(true, predicate_fn.eval(&5)); /// assert_eq!(true, predicate_fn.eval(&10)); /// assert_eq!(true, predicate_fn.eval(&15)); /// // Won't work - Predicates can only operate on a single type /// // assert_eq!(true, predicate_fn.eval("hello")) /// ``` pub fn always<Item>() -> BooleanPredicate<Item> { BooleanPredicate { retval: true, _phantom: PhantomData, } } /// Creates a new `Predicate` that always returns `false`. /// /// # Examples /// /// ``` /// use predicates::prelude::*; /// /// let predicate_fn = predicate::never(); /// assert_eq!(false, predicate_fn.eval(&5)); /// assert_eq!(false, predicate_fn.eval(&10)); /// assert_eq!(false, predicate_fn.eval(&15)); /// // Won't work - Predicates can only operate on a single type /// // assert_eq!(false, predicate_fn.eval("hello")) /// ``` pub fn never<Item>() -> BooleanPredicate<Item> { BooleanPredicate { retval: false, _phantom: PhantomData, } }