• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 use crate::{
16     description::Description,
17     matcher::{Matcher, MatcherResult},
18 };
19 use num_traits::float::Float;
20 use std::{fmt::Debug, marker::PhantomData};
21 
22 /// Matches a floating point value which is NaN.
is_nan<T: Float + Debug>() -> impl Matcher<ActualT = T>23 pub fn is_nan<T: Float + Debug>() -> impl Matcher<ActualT = T> {
24     IsNanMatcher::<T>(Default::default())
25 }
26 
27 struct IsNanMatcher<T>(PhantomData<T>);
28 
29 impl<T: Float + Debug> Matcher for IsNanMatcher<T> {
30     type ActualT = T;
31 
matches(&self, actual: &T) -> MatcherResult32     fn matches(&self, actual: &T) -> MatcherResult {
33         actual.is_nan().into()
34     }
35 
describe(&self, matcher_result: MatcherResult) -> Description36     fn describe(&self, matcher_result: MatcherResult) -> Description {
37         if matcher_result.into() { "is NaN" } else { "isn't NaN" }.into()
38     }
39 }
40 
41 #[cfg(test)]
42 mod tests {
43     use super::is_nan;
44     use crate::prelude::*;
45 
46     #[test]
matches_f32_nan() -> Result<()>47     fn matches_f32_nan() -> Result<()> {
48         verify_that!(f32::NAN, is_nan())
49     }
50 
51     #[test]
does_not_match_f32_number() -> Result<()>52     fn does_not_match_f32_number() -> Result<()> {
53         verify_that!(0.0f32, not(is_nan()))
54     }
55 
56     #[test]
matches_f64_nan() -> Result<()>57     fn matches_f64_nan() -> Result<()> {
58         verify_that!(f64::NAN, is_nan())
59     }
60 
61     #[test]
does_not_match_f64_number() -> Result<()>62     fn does_not_match_f64_number() -> Result<()> {
63         verify_that!(0.0f64, not(is_nan()))
64     }
65 }
66