rust/tests/ui/float_cmp.rs

80 lines
2.1 KiB
Rust
Raw Normal View History

2018-10-06 11:18:06 -05:00
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
2018-10-11 05:16:22 -05:00
2017-09-18 05:47:33 -05:00
2018-07-28 10:34:52 -05:00
#![warn(clippy::float_cmp)]
#![allow(unused, clippy::no_effect, clippy::unnecessary_operation, clippy::cast_lossless)]
2015-09-02 03:30:11 -05:00
use std::ops::Add;
const ZERO : f32 = 0.0;
const ONE : f32 = ZERO + 1.0;
fn twice<T>(x : T) -> T where T : Add<T, Output = T>, T : Copy {
x + x
}
2015-09-02 03:30:11 -05:00
fn eq_fl(x: f32, y: f32) -> bool {
if x.is_nan() { y.is_nan() } else { x == y } // no error, inside "eq" fn
}
fn fl_eq(x: f32, y: f32) -> bool {
if x.is_nan() { y.is_nan() } else { x == y } // no error, inside "eq" fn
}
struct X { val: f32 }
impl PartialEq for X {
fn eq(&self, o: &X) -> bool {
if self.val.is_nan() {
o.val.is_nan()
} else {
self.val == o.val // no error, inside "eq" fn
}
}
}
fn main() {
2015-08-17 05:06:56 -05:00
ZERO == 0f32; //no error, comparison with zero is ok
1.0f32 != ::std::f32::INFINITY; // also comparison with infinity
1.0f32 != ::std::f32::NEG_INFINITY; // and negative infinity
2015-08-17 05:06:56 -05:00
ZERO == 0.0; //no error, comparison with zero is ok
ZERO + ZERO != 1.0; //no error, comparison with zero is ok
2016-06-29 12:47:51 -05:00
ONE == 1f32;
2016-06-29 14:25:23 -05:00
ONE == 1.0 + 0.0;
ONE + ONE == ZERO + ONE + ONE;
2016-06-29 12:47:51 -05:00
ONE != 2.0;
2015-08-17 05:06:56 -05:00
ONE != 0.0; // no error, comparison with zero is ok
2016-06-29 12:47:51 -05:00
twice(ONE) != ONE;
ONE as f64 != 2.0;
2015-08-17 05:06:56 -05:00
ONE as f64 != 0.0; // no error, comparison with zero is ok
let x : f64 = 1.0;
2016-06-29 12:47:51 -05:00
x == 1.0;
2015-08-17 05:06:56 -05:00
x != 0f64; // no error, comparison with zero is ok
2016-06-29 12:47:51 -05:00
twice(x) != twice(ONE as f64);
2017-02-08 07:58:07 -06:00
2015-08-17 05:06:56 -05:00
x < 0.0; // no errors, lower or greater comparisons need no fuzzyness
x > 0.0;
x <= 0.0;
x >= 0.0;
2016-06-25 11:59:37 -05:00
let xs : [f32; 1] = [0.0];
let a: *const f32 = xs.as_ptr();
let b: *const f32 = xs.as_ptr();
assert_eq!(a, b); // no errors
}