Skip to main content

googletest/matchers/
is_nan_matcher.rs

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
15use crate::{
16    description::Description,
17    matcher::{Matcher, MatcherBase, MatcherResult},
18};
19use num_traits::float::Float;
20use std::fmt::Debug;
21
22/// Matches a floating point value which is NaN.
23pub fn is_nan() -> IsNanMatcher {
24    IsNanMatcher
25}
26
27#[derive(MatcherBase)]
28pub struct IsNanMatcher;
29
30impl<T: Float + Debug + Copy> Matcher<T> for IsNanMatcher {
31    fn matches(&self, actual: T) -> MatcherResult {
32        actual.is_nan().into()
33    }
34
35    fn describe(&self, matcher_result: MatcherResult) -> Description {
36        if matcher_result.into() { "is NaN" } else { "isn't NaN" }.into()
37    }
38}
39
40#[cfg(test)]
41mod tests {
42    use crate::prelude::*;
43    use crate::Result;
44
45    #[test]
46    fn matches_f32_nan() -> Result<()> {
47        verify_that!(f32::NAN, is_nan())
48    }
49
50    #[test]
51    fn does_not_match_f32_number() -> Result<()> {
52        verify_that!(0.0f32, not(is_nan()))
53    }
54
55    #[test]
56    fn matches_f64_nan() -> Result<()> {
57        verify_that!(f64::NAN, is_nan())
58    }
59
60    #[test]
61    fn does_not_match_f64_number() -> Result<()> {
62        verify_that!(0.0f64, not(is_nan()))
63    }
64}