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