predicates/str/
normalize.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
9use crate::reflection;
10use crate::Predicate;
11use std::fmt;
12
13use normalize_line_endings::normalized;
14use std::iter::FromIterator;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17/// Predicate adapter that normalizes the newlines contained in the variable being tested.
18///
19/// This is created by `pred.normalize()`.
20pub struct NormalizedPredicate<P>
21where
22    P: Predicate<str>,
23{
24    pub(crate) p: P,
25}
26
27impl<P> reflection::PredicateReflection for NormalizedPredicate<P>
28where
29    P: Predicate<str>,
30{
31    fn children<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Child<'a>> + 'a> {
32        let params = vec![reflection::Child::new("predicate", &self.p)];
33        Box::new(params.into_iter())
34    }
35}
36
37impl<P> Predicate<str> for NormalizedPredicate<P>
38where
39    P: Predicate<str>,
40{
41    fn eval(&self, variable: &str) -> bool {
42        self.p
43            .eval(&String::from_iter(normalized(variable.chars())))
44    }
45
46    fn find_case<'a>(&'a self, expected: bool, variable: &str) -> Option<reflection::Case<'a>> {
47        let variable = String::from_iter(normalized(variable.chars()));
48        self.p.find_case(expected, &variable)
49    }
50}
51
52impl<P> fmt::Display for NormalizedPredicate<P>
53where
54    P: Predicate<str>,
55{
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        write!(f, "{}", self.p)
58    }
59}