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/license/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//! Definition of a constant (always true or always false) `Predicate`.
10
11use std::fmt;
12
13use crate::reflection;
14use crate::utils;
15use crate::Predicate;
16
17/// Predicate that always returns a constant (boolean) result.
18///
19/// This is created by the `predicate::always` and `predicate::never` functions.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct BooleanPredicate {
22 retval: bool,
23}
24
25impl<Item: ?Sized> Predicate<Item> for BooleanPredicate {
26 fn eval(&self, _variable: &Item) -> bool {
27 self.retval
28 }
29
30 fn find_case<'a>(&'a self, expected: bool, variable: &Item) -> Option<reflection::Case<'a>> {
31 utils::default_find_case(self, expected, variable)
32 }
33}
34
35impl reflection::PredicateReflection for BooleanPredicate {
36 fn parameters<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Parameter<'a>> + 'a> {
37 let params = vec![reflection::Parameter::new("value", &self.retval)];
38 Box::new(params.into_iter())
39 }
40}
41
42impl fmt::Display for BooleanPredicate {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 let palette = crate::Palette::current();
45 write!(f, "{}", palette.expected.paint(self.retval))
46 }
47}
48
49/// Creates a new `Predicate` that always returns `true`.
50///
51/// # Examples
52///
53/// ```
54/// use predicates::prelude::*;
55///
56/// let predicate_fn = predicate::always();
57/// assert_eq!(true, predicate_fn.eval(&5));
58/// assert_eq!(true, predicate_fn.eval(&10));
59/// assert_eq!(true, predicate_fn.eval(&15));
60/// // Won't work - Predicates can only operate on a single type
61/// // assert_eq!(true, predicate_fn.eval("hello"))
62/// ```
63pub fn always() -> BooleanPredicate {
64 BooleanPredicate { retval: true }
65}
66
67/// Creates a new `Predicate` that always returns `false`.
68///
69/// # Examples
70///
71/// ```
72/// use predicates::prelude::*;
73///
74/// let predicate_fn = predicate::never();
75/// assert_eq!(false, predicate_fn.eval(&5));
76/// assert_eq!(false, predicate_fn.eval(&10));
77/// assert_eq!(false, predicate_fn.eval(&15));
78/// // Won't work - Predicates can only operate on a single type
79/// // assert_eq!(false, predicate_fn.eval("hello"))
80/// ```
81pub fn never() -> BooleanPredicate {
82 BooleanPredicate { retval: false }
83}
84