]> git.lizzy.rs Git - rust.git/blob - tests/ui/float_cmp.rs
Auto merge of #3533 - phansch:add_to_doc_valid_idents, r=phansch
[rust.git] / tests / ui / float_cmp.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 #![warn(clippy::float_cmp)]
11 #![allow(unused, clippy::no_effect, clippy::unnecessary_operation, clippy::cast_lossless)]
12
13 use std::ops::Add;
14
15 const ZERO: f32 = 0.0;
16 const ONE: f32 = ZERO + 1.0;
17
18 fn twice<T>(x: T) -> T
19 where
20     T: Add<T, Output = T>,
21     T: Copy,
22 {
23     x + x
24 }
25
26 fn eq_fl(x: f32, y: f32) -> bool {
27     if x.is_nan() {
28         y.is_nan()
29     } else {
30         x == y
31     } // no error, inside "eq" fn
32 }
33
34 fn fl_eq(x: f32, y: f32) -> bool {
35     if x.is_nan() {
36         y.is_nan()
37     } else {
38         x == y
39     } // no error, inside "eq" fn
40 }
41
42 struct X {
43     val: f32,
44 }
45
46 impl PartialEq for X {
47     fn eq(&self, o: &X) -> bool {
48         if self.val.is_nan() {
49             o.val.is_nan()
50         } else {
51             self.val == o.val // no error, inside "eq" fn
52         }
53     }
54 }
55
56 fn main() {
57     ZERO == 0f32; //no error, comparison with zero is ok
58     1.0f32 != ::std::f32::INFINITY; // also comparison with infinity
59     1.0f32 != ::std::f32::NEG_INFINITY; // and negative infinity
60     ZERO == 0.0; //no error, comparison with zero is ok
61     ZERO + ZERO != 1.0; //no error, comparison with zero is ok
62
63     ONE == 1f32;
64     ONE == 1.0 + 0.0;
65     ONE + ONE == ZERO + ONE + ONE;
66     ONE != 2.0;
67     ONE != 0.0; // no error, comparison with zero is ok
68     twice(ONE) != ONE;
69     ONE as f64 != 2.0;
70     ONE as f64 != 0.0; // no error, comparison with zero is ok
71
72     let x: f64 = 1.0;
73
74     x == 1.0;
75     x != 0f64; // no error, comparison with zero is ok
76
77     twice(x) != twice(ONE as f64);
78
79     x < 0.0; // no errors, lower or greater comparisons need no fuzzyness
80     x > 0.0;
81     x <= 0.0;
82     x >= 0.0;
83
84     let xs: [f32; 1] = [0.0];
85     let a: *const f32 = xs.as_ptr();
86     let b: *const f32 = xs.as_ptr();
87
88     assert_eq!(a, b); // no errors
89 }