]> git.lizzy.rs Git - rust.git/blob - tests/ui/float_cmp.rs
Rollup merge of #5415 - nickrtorres:master, r=flip1995
[rust.git] / tests / ui / float_cmp.rs
1 #![warn(clippy::float_cmp)]
2 #![allow(unused, clippy::no_effect, clippy::unnecessary_operation, clippy::cast_lossless)]
3
4 use std::ops::Add;
5
6 const ZERO: f32 = 0.0;
7 const ONE: f32 = ZERO + 1.0;
8
9 fn twice<T>(x: T) -> T
10 where
11     T: Add<T, Output = T> + Copy,
12 {
13     x + x
14 }
15
16 fn eq_fl(x: f32, y: f32) -> bool {
17     if x.is_nan() {
18         y.is_nan()
19     } else {
20         x == y
21     } // no error, inside "eq" fn
22 }
23
24 fn fl_eq(x: f32, y: f32) -> bool {
25     if x.is_nan() {
26         y.is_nan()
27     } else {
28         x == y
29     } // no error, inside "eq" fn
30 }
31
32 struct X {
33     val: f32,
34 }
35
36 impl PartialEq for X {
37     fn eq(&self, o: &X) -> bool {
38         if self.val.is_nan() {
39             o.val.is_nan()
40         } else {
41             self.val == o.val // no error, inside "eq" fn
42         }
43     }
44 }
45
46 fn main() {
47     ZERO == 0f32; //no error, comparison with zero is ok
48     1.0f32 != f32::INFINITY; // also comparison with infinity
49     1.0f32 != f32::NEG_INFINITY; // and negative infinity
50     ZERO == 0.0; //no error, comparison with zero is ok
51     ZERO + ZERO != 1.0; //no error, comparison with zero is ok
52
53     ONE == 1f32;
54     ONE == 1.0 + 0.0;
55     ONE + ONE == ZERO + ONE + ONE;
56     ONE != 2.0;
57     ONE != 0.0; // no error, comparison with zero is ok
58     twice(ONE) != ONE;
59     ONE as f64 != 2.0;
60     ONE as f64 != 0.0; // no error, comparison with zero is ok
61
62     let x: f64 = 1.0;
63
64     x == 1.0;
65     x != 0f64; // no error, comparison with zero is ok
66
67     twice(x) != twice(ONE as f64);
68
69     x < 0.0; // no errors, lower or greater comparisons need no fuzzyness
70     x > 0.0;
71     x <= 0.0;
72     x >= 0.0;
73
74     let xs: [f32; 1] = [0.0];
75     let a: *const f32 = xs.as_ptr();
76     let b: *const f32 = xs.as_ptr();
77
78     assert_eq!(a, b); // no errors
79
80     // no errors - comparing signums is ok
81     let x32 = 3.21f32;
82     1.23f32.signum() == x32.signum();
83     1.23f32.signum() == -(x32.signum());
84     1.23f32.signum() == 3.21f32.signum();
85
86     1.23f32.signum() != x32.signum();
87     1.23f32.signum() != -(x32.signum());
88     1.23f32.signum() != 3.21f32.signum();
89
90     let x64 = 3.21f64;
91     1.23f64.signum() == x64.signum();
92     1.23f64.signum() == -(x64.signum());
93     1.23f64.signum() == 3.21f64.signum();
94
95     1.23f64.signum() != x64.signum();
96     1.23f64.signum() != -(x64.signum());
97     1.23f64.signum() != 3.21f64.signum();
98 }