predicates/constant.rs
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 write!(f, "{}", self.retval)
45 }
46}
47
48/// Creates a new `Predicate` that always returns `true`.
49///
50/// # Examples
51///
52/// ```
53/// use predicates::prelude::*;
54///
55/// let predicate_fn = predicate::always();
56/// assert_eq!(true, predicate_fn.eval(&5));
57/// assert_eq!(true, predicate_fn.eval(&10));
58/// assert_eq!(true, predicate_fn.eval(&15));
59/// // Won't work - Predicates can only operate on a single type
60/// // assert_eq!(true, predicate_fn.eval("hello"))
61/// ```
62pub fn always() -> BooleanPredicate {
63 BooleanPredicate { retval: true }
64}
65
66/// Creates a new `Predicate` that always returns `false`.
67///
68/// # Examples
69///
70/// ```
71/// use predicates::prelude::*;
72///
73/// let predicate_fn = predicate::never();
74/// assert_eq!(false, predicate_fn.eval(&5));
75/// assert_eq!(false, predicate_fn.eval(&10));
76/// assert_eq!(false, predicate_fn.eval(&15));
77/// // Won't work - Predicates can only operate on a single type
78/// // assert_eq!(false, predicate_fn.eval("hello"))
79/// ```
80pub fn never() -> BooleanPredicate {
81 BooleanPredicate { retval: false }
82}