float_eq-1.0.1/.cargo_vcs_info.json0000644000000001460000000000100126260ustar { "git": { "sha1": "4a90eec3afce4c0c6ea997212de6400eddef9d19" }, "path_in_vcs": "float_eq" }float_eq-1.0.1/Cargo.toml0000644000000031360000000000100106260ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "float_eq" version = "1.0.1" authors = ["jtempest"] include = [ "Cargo.toml", "src/**/*.rs", "crates-io.md", "LICENSE-APACHE", "LICENSE-MIT", ] description = "Compare IEEE floating point primitives, structs and collections for equality." homepage = "https://jtempest.github.io/float_eq-rs/" documentation = "https://jtempest.github.io/float_eq-rs/book/" readme = "crates-io.md" keywords = [ "approximate", "assert", "comparison", "equality", "float", ] categories = [ "algorithms", "development-tools::debugging", "no-std", ] license = "MIT OR Apache-2.0" repository = "https://github.com/jtempest/float_eq-rs" [package.metadata.docs.rs] all-features = true [dependencies.float_eq_derive] version = "=1.0.1" optional = true [dependencies.num-complex] version = "0.4" optional = true [dev-dependencies.trybuild] version = "1" [features] default = ["std"] derive = ["float_eq_derive"] num = ["num-complex"] std = [] [badges.coveralls] repository = "jtempest/float_eq-rs" [badges.maintenance] status = "experimental" [badges.travis-ci] repository = "jtempest/float_eq-rs" float_eq-1.0.1/Cargo.toml.orig000064400000000000000000000024740072674642500143430ustar 00000000000000[package] name = "float_eq" version = "1.0.1" authors = ["jtempest"] license = "MIT OR Apache-2.0" description = "Compare IEEE floating point primitives, structs and collections for equality." homepage = "https://jtempest.github.io/float_eq-rs/" repository = "https://github.com/jtempest/float_eq-rs" documentation = "https://jtempest.github.io/float_eq-rs/book/" keywords = ["approximate", "assert", "comparison", "equality", "float"] categories = ["algorithms", "development-tools::debugging", "no-std"] readme = "crates-io.md" include = ["Cargo.toml", "src/**/*.rs", "crates-io.md", "LICENSE-APACHE", "LICENSE-MIT"] edition = "2018" [package.metadata.docs.rs] all-features = true [badges] maintenance = { status = "experimental" } travis-ci = { repository = "jtempest/float_eq-rs" } # Turned off for now since coveralls has better support for testing multiple # feature sets, and thus is more representative. # codecov = { repository = "jtempest/float_eq-rs" } coveralls = { repository = "jtempest/float_eq-rs" } [dev-dependencies] trybuild = "1" [dependencies.num-complex] version = "0.4" optional = true [dependencies.float_eq_derive] version = "=1.0.1" optional = true path = "../float_eq_derive" [features] default = ["std"] std = [] num = ["num-complex"] derive = ["float_eq_derive"]float_eq-1.0.1/LICENSE-APACHE000064400000000000000000000264500072674642500134000ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. float_eq-1.0.1/LICENSE-MIT000064400000000000000000000020550072674642500131030ustar 00000000000000Copyright (c) 2020 jtempest Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.float_eq-1.0.1/crates-io.md000064400000000000000000000126730072674642500136660ustar 00000000000000# float_eq Compare IEEE floating point primitives, structs and collections for equality. This crate provides an API with a focus on making the choices of comparison algorithm(s) and tolerances intuitive to implementers and maintainers, and of providing clear output for debugging and development iteration. This readme is a quick tour of the crate. For introductory material, guides and discussion see [the float_eq guide]. ## Usage Add this to your cargo.toml: ``` [dependencies] float_eq = "1" ``` And, if you're using the 2015 edition, this to your crate root: ```rust extern crate float_eq; ``` Then, you can import items with `use`: ```rust use float_eq::{assert_float_eq, float_eq}; ``` ## Comparisons This crate provides boolean comparison operations: ```rust if (float_eq!(y_pos, 0.0, abs <= 0.000_1)) { //... } ``` And asserts: ```rust const RECIP_REL_TOL: f32 = 0.000_366_210_94; assert_float_eq!(x.recip(), 10.0, r2nd <= RECIP_REL_TOL); ``` Using absolute tolerance, relative tolerance or ULPs based [comparison algorithms]. ## Composite types Composite types may implement the provided extension traits to be compared on a field-by-field basis: ```rust let a = Complex32 { re: 2.0, im: 4.000_002 }; let b = Complex32 { re: 2.000_000_5, im: 4.0 }; assert_float_eq!(a, b, ulps <= ComplexUlps32 { re: 2, im: 4 }); ``` ...and if they are homogeneous, with a uniformly applied tolerance across all fields: ```rust assert_float_eq!(a, b, ulps_all <= 4); ``` Arrays of any size are supported: ```rust let a = [1.0, -2.0, 3.0]; let b = [-1.0, 2.0, 3.5]; assert_float_eq!(a, b, abs <= [2.0, 4.0, 0.5]); assert_float_eq!(a, b, abs_all <= 4.0); ``` As are tuples up to size 12 (inclusive): ```rust let a = (1.0f32, 2.0f64); let b = (1.5f32, -2.0f64); assert_float_eq!(a, b, r2nd <= (0.5, 2.0)); ``` Many standard and core types like `Vec` are supported: ```rust let a = vec![1.0, -2.0, 3.0]; let b = vec![-1.0, 2.0, 3.5]; assert_float_eq!(a, b, rmax <= vec![2.0, 2.0, 0.25]); assert_float_eq!(a, b, rmax_all <= 2.0); ``` There are blanket trait impls for comparing mutable and immutable reference types, the contents of `Cell`, `RefCell`, `Rc`, `Arc` and `Box` instances, as well as for slices, `Option`, `Vec`, `VecDeque`, `LinkedList`, `BTreeMap` and `HashMap`. ## Derivable The extension traits may be derived for non-generic structs and tuple structs: ```rust #[derive_float_eq( ulps_tol = "PointUlps", ulps_tol_derive = "Clone, Copy, Debug, PartialEq", debug_ulps_diff = "PointUlpsDebugUlpsDiff", debug_ulps_diff_derive = "Clone, Copy, Debug, PartialEq", all_tol = "f64" )] #[derive(Debug, PartialEq, Clone, Copy)] pub struct Point { pub x: f64, pub y: f64, } let a = Point { x: 1.0, y: -2.0 }; let c = Point { x: 1.000_000_000_000_000_9, y: -2.000_000_000_000_001_3 }; assert_float_eq!(a, c, ulps <= PointUlps { x: 4, y: 3 }); assert_float_eq!(a, c, ulps_all <= 4); ``` ## Error messages Asserts provide additional useful context information. For example: ```rust assert_float_eq!(4.0f32, 4.000_008, rmax <= 0.000_001); ``` Panics with this error message: ``` thread 'main' panicked at 'assertion failed: `float_eq!(left, right, rmax <= t)` left: `4.0`, right: `4.000008`, abs_diff: `0.000008106232`, ulps_diff: `Some(17)`, [rmax] t: `0.000004000008`', assert_failure.rs:15:5 ``` Where `[rmax] t` shows the tolerance value that the absolute difference was compared against after being appropriately scaled. ## Optional features This crate can be used without the standard library (`#![no_std]`) by disabling the default `std` feature. Use this in `Cargo.toml`: ``` [dependencies.float_eq] version = "1" default-features = false ``` Other optional features: - **derive** — provides custom derive macros for all traits. - **num** — blanket trait impls for `num::Complex` where it is instanced with a compatible type. ## Related efforts The [`approx`], [`float-cmp`], [`assert_float_eq`] and [`is_close`] crates provide similar floating point comparison capabilities to `float_eq`. The [`almost`] crate divides its API into comparison of floats against zero and non-zero values. The [`efloat`] crate provides an `f32` equivalent type that tracks the maximum possible error bounds that may have occured due to rounding. The [`ieee754`] crate is not a comparison library, but provides useful functionality for decomposing floats into their component parts, iterating over representable values and working with ULPs directly, amoung other things. ## Contributing Constructive feedback, suggestions and contributions welcomed, please [open an issue]. ## Changelog Release information is available in [CHANGELOG.md](CHANGELOG.md). [comparison algorithms]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html [open an issue]: https://github.com/jtempest/float_eq-rs/issues/ [the float_eq guide]: https://jtempest.github.io/float_eq-rs/book/introduction.html [`almost`]: https://crates.io/crates/almost [`approx`]: https://crates.io/crates/approx [`assert_float_eq`]: https://crates.io/crates/assert_float_eq [`efloat`]: https://crates.io/crates/efloat [`float-cmp`]: https://crates.io/crates/float-cmp [`ieee754`]: https://crates.io/crates/ieee754 [`is_close`]: https://docs.rs/is_close/latest/is_close/ float_eq-1.0.1/src/lib.rs000064400000000000000000000101110072674642500133420ustar 00000000000000//! Compare IEEE floating point primitives, structs and collections for equality. //! //! This is API reference documentation. For introductory material, guides and //! discussion see [the float_eq guide]. //! //! # Basic usage //! //! This crate provides boolean comparisons via [`float_eq!`] and [`float_ne!`]: //! //! ``` //! use float_eq::float_eq; //! //! # let y_pos = 0.000_1; //! if (float_eq!(y_pos, 0.0, abs <= 0.000_1)) { //! //... //! } //! ``` //! //! And asserts via [`assert_float_eq!`] and [`assert_float_ne!`]: //! //! ``` //! use float_eq::assert_float_eq; //! //! const TOL: f32 = 0.000_366_210_94; //! assert_float_eq!(0.1f32.recip(), 10.0, r2nd <= TOL); //! ``` //! //! Each of which invokes a specific comparison algorithm with an explictly //! provided toelrance. In these examples: //! //! - `abs <= 0.000_1` is an absolute tolerance comparison with a tolerance of `0.000_1`. //! - `r2nd <= TOL` is a relative tolerance comparison with a tolerance of `TOL`, //! scaled to the precision of the second operand. //! //! # Comparison algorithms //! //! These are always of the form `CHECK <= tol`, where `CHECK` is one of: //! //! - `abs`: an [absolute tolerance comparison]. //! - `rmax`: a [relative tolerance comparison], scaled to the precision of the larger operand/field. //! - `rmin`: a [relative tolerance comparison], scaled to the precision of the smaller operand/field. //! - `r1st`: a [relative tolerance comparison], scaled to the precision of the first operand/field. //! - `r2nd`: a [relative tolerance comparison], scaled to the precision of the second operand/field. //! - `ulps`: an [ULPs comparison]. //! //! When comparing homogeneous composite types that implement [`FloatEqAll`], //! variants that use a uniform `tol` across all fields are also available: //! //! - `abs_all`: an [absolute tolerance comparison]. //! - `rmax_all`: a [relative tolerance comparison], scaled to the precision of the larger field. //! - `rmin_all`: a [relative tolerance comparison], scaled to the precision of the smaller field. //! - `r1st_all`: a [relative tolerance comparison], scaled to the precision of the first field. //! - `r2nd_all`: a [relative tolerance comparison], scaled to the precision of the second field. //! - `ulps_all`: an [ULPs comparison]. //! //! *Note: `rel` and `rel_all` are legacy aliases for `rmax` and `rmax_all`, but //! using the more precise algorithm names is recommended.* //! //! # Combining checks //! //! If multiple checks are specified in either a boolean comparison or an assert, //! they are applied left to right and will shortcut on success. For example: //! //! ``` //! # use float_eq::float_eq; //! # let a = 0.1; let b = 0.1; let abs_tol = 0.0; let ulps_tol: u64 = 0; //! float_eq!(a, b, abs <= abs_tol, ulps <= ulps_tol) //! # ; //! ``` //! //! Is equivalent to: //! //! ``` //! # use float_eq::float_eq; //! # let a = 0.1; let b = 0.1; let abs_tol = 0.0; let ulps_tol: u64 = 0; //! float_eq!(a, b, abs <= abs_tol) || float_eq!(a, b, ulps <= ulps_tol) //! # ; //! ``` //! //! # Extending float_eq over custom types //! //! See [How to compare custom types]. //! //! [How to compare custom types]: https://jtempest.github.io/float_eq-rs/book/how_to/compare_custom_types.html //! [the float_eq guide]: https://jtempest.github.io/float_eq-rs/book/index.html //! [absolute tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#absolute-tolerance-comparison //! [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison //! [ULPs comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison #![warn(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] #[macro_use] mod macros; pub use crate::macros::*; mod traits; pub use crate::traits::*; mod trait_impls; pub use crate::trait_impls::*; #[cfg(feature = "float_eq_derive")] pub use float_eq_derive::*; float_eq-1.0.1/src/macros.rs000064400000000000000000000743350072674642500141020ustar 00000000000000use crate::{AssertFloatEq, AssertFloatEqAll, FloatEq, FloatEqAll, UlpsTol}; /// Checks if two floating point expressions are equal to each other. /// /// See the top level documentation for a list of available [comparison algorithms]. /// /// # Examples /// ``` /// # use float_eq::float_eq; /// # use std::f32; /// let a: f32 = 4.0; /// let b: f32 = 4.000_002_5; /// /// assert!(float_eq!(a, b, ulps <= 10)); /// assert!(float_eq!(a, 3.999_999_6, rmax <= 2.0 * f32::EPSILON)); /// assert!(float_eq!(a - b, 0.0, abs <= 0.000_01)); /// ``` /// /// [comparison algorithms]: index.html#comparison-algorithms /// [from left to right]: index.html#combining-checks #[macro_export] macro_rules! float_eq { ($a:expr, $b:expr, $($eq:ident <= $tol:expr),+) => ({ match (&$a, &$b) { (a_val, b_val) => { false $(|| $crate::FloatEqCmp::$eq(a_val, b_val, &$tol))+ } } }); ($a:expr, $b:expr, $($eq:ident <= $tol:expr),+,) => ({ $crate::float_eq!($a, $b $(, $eq <= $tol)+) }) } /// Checks if two floating point expressions are not equal to each other. /// /// See the top level documentation for a list of available [comparison algorithms]. /// /// # Examples /// ``` /// # use float_eq::float_ne; /// # use std::f32; /// let a: f32 = 4.0; /// let b: f32 = 4.1; /// /// assert!(float_ne!(a, b, ulps <= 10)); /// assert!(float_ne!(a, b, rmax <= 2.0 * f32::EPSILON)); /// assert!(float_ne!(a - b, 0.0, abs <= 0.000_01)); /// ``` /// /// [comparison algorithms]: index.html#comparison-algorithms /// [from left to right]: index.html#combining-checks #[macro_export] macro_rules! float_ne { ($a:expr, $b:expr, $($eq:ident <= $tol:expr),+) => ({ !$crate::float_eq!($a, $b $(, $eq <= $tol)+) }); ($a:expr, $b:expr, $($eq:ident <= $tol:expr),+,) => ({ !$crate::float_eq!($a, $b $(, $eq <= $tol)+) }); } /// Asserts that two floating point expressions are equal to each other. /// /// See the top level documentation for a list of available [comparison algorithms]. /// /// On panic, this macro will print the values of the expressions with their debug /// representations, with [additional information] from the comparison operations. /// Like [`assert!`], this macro has a second form, where a custom panic message can /// be provided. /// /// # Examples /// ``` /// # use float_eq::assert_float_eq; /// # use std::f32; /// let a: f32 = 4.0; /// let b: f32 = 4.000_002_5; /// /// assert_float_eq!(a, b, ulps <= 10); /// assert_float_eq!(a, 3.999_999_6, rmax <= 2.0 * f32::EPSILON); /// assert_float_eq!(a - b, 0.0, abs <= 0.000_01, "Checking that {} == {}", a, b); /// ``` /// /// [`assert!`]: https://doc.rust-lang.org/std/macro.assert.html /// [additional information]: https://jtempest.github.io/float_eq-rs/book/how_to/interpret_assert_failure_messages.html /// [comparison algorithms]: index.html#comparison-algorithms /// [from left to right]: index.html#combining-checks #[macro_export] macro_rules! assert_float_eq { // the order of these rules matters a *lot* for the format string functionality // to work, otherwise we end up consuming the general case too early. ($left:expr, $right:expr, $eq1:ident <= $tol_1:expr, $eq2:ident <= $tol_2:expr, $eq3:ident <= $tol_3:expr) => ({ match (&$left, &$right, &$tol_1, &$tol_2, &$tol_3) { (left_val, right_val, tol_1_val, tol_2_val, tol_3_val) => { if !$crate::float_eq!( *left_val, *right_val, $eq1 <= *tol_1_val, $eq2 <= *tol_2_val, $eq3 <= *tol_3_val) { // The reborrows below are intentional. See assert_eq! in the standard library. panic!(concat!( "assertion failed: `float_eq!(left, right, ", stringify!($eq1), " <= t, ", stringify!($eq2), " <= t, ", stringify!($eq3), r#" <= t)` left: `{:?}`, right: `{:?}`, abs_diff: `{:?}`, ulps_diff: `{:?}`, {:>10} t: `{:?}`, {:>10} t: `{:?}`, {:>10} t: `{:?}`"#), &*left_val, &*right_val, $crate::AssertFloatEq::debug_abs_diff(&*left_val, &*right_val), $crate::AssertFloatEq::debug_ulps_diff(&*left_val, &*right_val), concat!("[", stringify!($eq1), "]"), $crate::FloatCmpOpTol::$eq1(&*left_val, &*right_val, &*tol_1_val), concat!("[", stringify!($eq2), "]"), $crate::FloatCmpOpTol::$eq2(&*left_val, &*right_val, &*tol_2_val), concat!("[", stringify!($eq3), "]"), $crate::FloatCmpOpTol::$eq3(&*left_val, &*right_val, &*tol_3_val) ) } } } }); ($left:expr, $right:expr, $eq1:ident <= $tol_1:expr, $eq2:ident <= $tol_2:expr) => ({ match (&$left, &$right, &$tol_1, &$tol_2) { (left_val, right_val, tol_1_val, tol_2_val) => { if !$crate::float_eq!( *left_val, *right_val, $eq1 <= *tol_1_val, $eq2 <= *tol_2_val) { // The reborrows below are intentional. See assert_eq! in the standard library. panic!(concat!( "assertion failed: `float_eq!(left, right, ", stringify!($eq1), " <= t, ", stringify!($eq2), r#" <= t)` left: `{:?}`, right: `{:?}`, abs_diff: `{:?}`, ulps_diff: `{:?}`, {:>10} t: `{:?}`, {:>10} t: `{:?}`"#), &*left_val, &*right_val, $crate::AssertFloatEq::debug_abs_diff(&*left_val, &*right_val), $crate::AssertFloatEq::debug_ulps_diff(&*left_val, &*right_val), concat!("[", stringify!($eq1), "]"), $crate::FloatCmpOpTol::$eq1(&*left_val, &*right_val, &*tol_1_val), concat!("[", stringify!($eq2), "]"), $crate::FloatCmpOpTol::$eq2(&*left_val, &*right_val, &*tol_2_val), ) } } } }); ($left:expr, $right:expr, $eq1:ident <= $tol_1:expr) => ({ match (&$left, &$right, &$tol_1) { (left_val, right_val, tol_1_val) => { if !$crate::float_eq!( *left_val, *right_val, $eq1 <= *tol_1_val) { // The reborrows below are intentional. See assert_eq! in the standard library. panic!(concat!( "assertion failed: `float_eq!(left, right, ", stringify!($eq1), r#" <= t)` left: `{:?}`, right: `{:?}`, abs_diff: `{:?}`, ulps_diff: `{:?}`, {:>10} t: `{:?}`"#), &*left_val, &*right_val, $crate::AssertFloatEq::debug_abs_diff(&*left_val, &*right_val), $crate::AssertFloatEq::debug_ulps_diff(&*left_val, &*right_val), concat!("[", stringify!($eq1), "]"), $crate::FloatCmpOpTol::$eq1(&*left_val, &*right_val, &*tol_1_val), ) } } } }); ($left:expr, $right:expr, $($eq:ident <= $tol:expr,)+) => ({ $crate::assert_float_eq!($left, $right $(, $eq <= $tol)+) }); ($left:expr, $right:expr, $eq1:ident <= $tol_1:expr, $eq2:ident <= $tol_2:expr, $eq3:ident <= $tol_3:expr, $($arg:tt)+) => ({ match (&$left, &$right, &$tol_1, &$tol_2, &$tol_3) { (left_val, right_val, tol_1_val, tol_2_val, tol_3_val) => { if !$crate::float_eq!( *left_val, *right_val, $eq1 <= *tol_1_val, $eq2 <= *tol_2_val, $eq3 <= *tol_3_val) { // The reborrows below are intentional. See assert_eq! in the standard library. panic!(concat!( "assertion failed: `float_eq!(left, right, ", stringify!($eq1), " <= t, ", stringify!($eq2), " <= t, ", stringify!($eq3), r#" <= t)` left: `{:?}`, right: `{:?}`, abs_diff: `{:?}`, ulps_diff: `{:?}`, {:>10} t: `{:?}`, {:>10} t: `{:?}`, {:>10} t: `{:?}`: {}"#), &*left_val, &*right_val, $crate::AssertFloatEq::debug_abs_diff(&*left_val, &*right_val), $crate::AssertFloatEq::debug_ulps_diff(&*left_val, &*right_val), concat!("[", stringify!($eq1), "]"), $crate::FloatCmpOpTol::$eq1(&*left_val, &*right_val, &*tol_1_val), concat!("[", stringify!($eq2), "]"), $crate::FloatCmpOpTol::$eq2(&*left_val, &*right_val, &*tol_2_val), concat!("[", stringify!($eq3), "]"), $crate::FloatCmpOpTol::$eq3(&*left_val, &*right_val, &*tol_3_val), format_args!($($arg)+) ) } } } }); ($left:expr, $right:expr, $eq1:ident <= $tol_1:expr, $eq2:ident <= $tol_2:expr, $($arg:tt)+) => ({ match (&$left, &$right, &$tol_1, &$tol_2) { (left_val, right_val, tol_1_val, tol_2_val) => { if !$crate::float_eq!( *left_val, *right_val, $eq1 <= *tol_1_val, $eq2 <= *tol_2_val) { // The reborrows below are intentional. See assert_eq! in the standard library. panic!(concat!( "assertion failed: `float_eq!(left, right, ", stringify!($eq1), " <= t, ", stringify!($eq2), r#" <= t)` left: `{:?}`, right: `{:?}`, abs_diff: `{:?}`, ulps_diff: `{:?}`, {:>10} t: `{:?}`, {:>10} t: `{:?}`: {}"#), &*left_val, &*right_val, $crate::AssertFloatEq::debug_abs_diff(&*left_val, &*right_val), $crate::AssertFloatEq::debug_ulps_diff(&*left_val, &*right_val), concat!("[", stringify!($eq1), "]"), $crate::FloatCmpOpTol::$eq1(&*left_val, &*right_val, &*tol_1_val), concat!("[", stringify!($eq2), "]"), $crate::FloatCmpOpTol::$eq2(&*left_val, &*right_val, &*tol_2_val), format_args!($($arg)+) ) } } } }); ($left:expr, $right:expr, $eq1:ident <= $tol_1:expr, $($arg:tt)+) => ({ match (&$left, &$right, &$tol_1) { (left_val, right_val, tol_1_val) => { if !$crate::float_eq!( *left_val, *right_val, $eq1 <= *tol_1_val) { // The reborrows below are intentional. See assert_eq! in the standard library. panic!(concat!( "assertion failed: `float_eq!(left, right, ", stringify!($eq1), r#" <= t)` left: `{:?}`, right: `{:?}`, abs_diff: `{:?}`, ulps_diff: `{:?}`, {:>10} t: `{:?}`: {}"#), &*left_val, &*right_val, $crate::AssertFloatEq::debug_abs_diff(&*left_val, &*right_val), $crate::AssertFloatEq::debug_ulps_diff(&*left_val, &*right_val), concat!("[", stringify!($eq1), "]"), $crate::FloatCmpOpTol::$eq1(&*left_val, &*right_val, &*tol_1_val), format_args!($($arg)+) ) } } } }); } /// Asserts that two floating point expressions are not equal to each other. /// /// See the top level documentation for a list of available [comparison algorithms]. /// /// On panic, this macro will print the values of the expressions with their debug /// representations, with [additional information] from the comparison operations. /// Like [`assert!`], this macro has a second form, where a custom panic message can /// be provided. /// /// # Examples /// ``` /// # use float_eq::assert_float_ne; /// # use std::f32; /// let a: f32 = 4.0; /// let b: f32 = 4.1; /// /// assert_float_ne!(a, b, ulps <= 10); /// assert_float_ne!(a, b, rmax <= 2.0 * f32::EPSILON); /// assert_float_ne!(a - b, 0.0, abs <= 0.000_01, "Checking that {} != {}", a, b); /// ``` /// /// [`assert!`]: https://doc.rust-lang.org/std/macro.assert.html /// [additional information]: https://jtempest.github.io/float_eq-rs/book/how_to/interpret_assert_failure_messages.html /// [comparison algorithms]: index.html#comparison-algorithms /// [from left to right]: index.html#combining-checks #[macro_export] macro_rules! assert_float_ne { // the order of these rules matters a *lot* for the format string functionality // to work, otherwise we end up consuming the general case too early. ($left:expr, $right:expr, $eq1:ident <= $tol_1:expr, $eq2:ident <= $tol_2:expr, $eq3:ident <= $tol_3:expr) => ({ match (&$left, &$right, &$tol_1, &$tol_2, &$tol_3) { (left_val, right_val, tol_1_val, tol_2_val, tol_3_val) => { if !$crate::float_ne!( *left_val, *right_val, $eq1 <= *tol_1_val, $eq2 <= *tol_2_val, $eq3 <= *tol_3_val) { // The reborrows below are intentional. See assert_eq! in the standard library. panic!(concat!( "assertion failed: `float_ne!(left, right, ", stringify!($eq1), " <= t, ", stringify!($eq2), " <= t, ", stringify!($eq3), r#" <= t)` left: `{:?}`, right: `{:?}`, abs_diff: `{:?}`, ulps_diff: `{:?}`, {:>10} t: `{:?}`, {:>10} t: `{:?}`, {:>10} t: `{:?}`"#), &*left_val, &*right_val, $crate::AssertFloatEq::debug_abs_diff(&*left_val, &*right_val), $crate::AssertFloatEq::debug_ulps_diff(&*left_val, &*right_val), concat!("[", stringify!($eq1), "]"), $crate::FloatCmpOpTol::$eq1(&*left_val, &*right_val, &*tol_1_val), concat!("[", stringify!($eq2), "]"), $crate::FloatCmpOpTol::$eq2(&*left_val, &*right_val, &*tol_2_val), concat!("[", stringify!($eq3), "]"), $crate::FloatCmpOpTol::$eq3(&*left_val, &*right_val, &*tol_3_val) ) } } } }); ($left:expr, $right:expr, $eq1:ident <= $tol_1:expr, $eq2:ident <= $tol_2:expr) => ({ match (&$left, &$right, &$tol_1, &$tol_2) { (left_val, right_val, tol_1_val, tol_2_val) => { if !$crate::float_ne!( *left_val, *right_val, $eq1 <= *tol_1_val, $eq2 <= *tol_2_val) { // The reborrows below are intentional. See assert_eq! in the standard library. panic!(concat!( "assertion failed: `float_ne!(left, right, ", stringify!($eq1), " <= t, ", stringify!($eq2), r#" <= t)` left: `{:?}`, right: `{:?}`, abs_diff: `{:?}`, ulps_diff: `{:?}`, {:>10} t: `{:?}`, {:>10} t: `{:?}`"#), &*left_val, &*right_val, $crate::AssertFloatEq::debug_abs_diff(&*left_val, &*right_val), $crate::AssertFloatEq::debug_ulps_diff(&*left_val, &*right_val), concat!("[", stringify!($eq1), "]"), $crate::FloatCmpOpTol::$eq1(&*left_val, &*right_val, &*tol_1_val), concat!("[", stringify!($eq2), "]"), $crate::FloatCmpOpTol::$eq2(&*left_val, &*right_val, &*tol_2_val), ) } } } }); ($left:expr, $right:expr, $eq1:ident <= $tol_1:expr) => ({ match (&$left, &$right, &$tol_1) { (left_val, right_val, tol_1_val) => { if !$crate::float_ne!( *left_val, *right_val, $eq1 <= *tol_1_val) { // The reborrows below are intentional. See assert_eq! in the standard library. panic!(concat!( "assertion failed: `float_ne!(left, right, ", stringify!($eq1), r#" <= t)` left: `{:?}`, right: `{:?}`, abs_diff: `{:?}`, ulps_diff: `{:?}`, {:>10} t: `{:?}`"#), &*left_val, &*right_val, $crate::AssertFloatEq::debug_abs_diff(&*left_val, &*right_val), $crate::AssertFloatEq::debug_ulps_diff(&*left_val, &*right_val), concat!("[", stringify!($eq1), "]"), $crate::FloatCmpOpTol::$eq1(&*left_val, &*right_val, &*tol_1_val), ) } } } }); ($left:expr, $right:expr, $($eq:ident <= $tol:expr,)+) => ({ $crate::assert_float_ne!($left, $right $(, $eq <= $tol)+) }); ($left:expr, $right:expr, $eq1:ident <= $tol_1:expr, $eq2:ident <= $tol_2:expr, $eq3:ident <= $tol_3:expr, $($arg:tt)+) => ({ match (&$left, &$right, &$tol_1, &$tol_2, &$tol_3) { (left_val, right_val, tol_1_val, tol_2_val, tol_3_val) => { if !$crate::float_ne!( *left_val, *right_val, $eq1 <= *tol_1_val, $eq2 <= *tol_2_val, $eq3 <= *tol_3_val) { // The reborrows below are intentional. See assert_eq! in the standard library. panic!(concat!( "assertion failed: `float_ne!(left, right, ", stringify!($eq1), " <= t, ", stringify!($eq2), " <= t, ", stringify!($eq3), r#" <= t)` left: `{:?}`, right: `{:?}`, abs_diff: `{:?}`, ulps_diff: `{:?}`, {:>10} t: `{:?}`, {:>10} t: `{:?}`, {:>10} t: `{:?}`: {}"#), &*left_val, &*right_val, $crate::AssertFloatEq::debug_abs_diff(&*left_val, &*right_val), $crate::AssertFloatEq::debug_ulps_diff(&*left_val, &*right_val), concat!("[", stringify!($eq1), "]"), $crate::FloatCmpOpTol::$eq1(&*left_val, &*right_val, &*tol_1_val), concat!("[", stringify!($eq2), "]"), $crate::FloatCmpOpTol::$eq2(&*left_val, &*right_val, &*tol_2_val), concat!("[", stringify!($eq3), "]"), $crate::FloatCmpOpTol::$eq3(&*left_val, &*right_val, &*tol_3_val), format_args!($($arg)+) ) } } } }); ($left:expr, $right:expr, $eq1:ident <= $tol_1:expr, $eq2:ident <= $tol_2:expr, $($arg:tt)+) => ({ match (&$left, &$right, &$tol_1, &$tol_2) { (left_val, right_val, tol_1_val, tol_2_val) => { if !$crate::float_ne!( *left_val, *right_val, $eq1 <= *tol_1_val, $eq2 <= *tol_2_val) { // The reborrows below are intentional. See assert_eq! in the standard library. panic!(concat!( "assertion failed: `float_ne!(left, right, ", stringify!($eq1), " <= t, ", stringify!($eq2), r#" <= t)` left: `{:?}`, right: `{:?}`, abs_diff: `{:?}`, ulps_diff: `{:?}`, {:>10} t: `{:?}`, {:>10} t: `{:?}`: {}"#), &*left_val, &*right_val, $crate::AssertFloatEq::debug_abs_diff(&*left_val, &*right_val), $crate::AssertFloatEq::debug_ulps_diff(&*left_val, &*right_val), concat!("[", stringify!($eq1), "]"), $crate::FloatCmpOpTol::$eq1(&*left_val, &*right_val, &*tol_1_val), concat!("[", stringify!($eq2), "]"), $crate::FloatCmpOpTol::$eq2(&*left_val, &*right_val, &*tol_2_val), format_args!($($arg)+) ) } } } }); ($left:expr, $right:expr, $eq1:ident <= $tol_1:expr, $($arg:tt)+) => ({ match (&$left, &$right, &$tol_1) { (left_val, right_val, tol_1_val) => { if !$crate::float_ne!( *left_val, *right_val, $eq1 <= *tol_1_val) { // The reborrows below are intentional. See assert_eq! in the standard library. panic!(concat!( "assertion failed: `float_ne!(left, right, ", stringify!($eq1), r#" <= t)` left: `{:?}`, right: `{:?}`, abs_diff: `{:?}`, ulps_diff: `{:?}`, {:>10} t: `{:?}`: {}"#), &*left_val, &*right_val, $crate::AssertFloatEq::debug_abs_diff(&*left_val, &*right_val), $crate::AssertFloatEq::debug_ulps_diff(&*left_val, &*right_val), concat!("[", stringify!($eq1), "]"), $crate::FloatCmpOpTol::$eq1(&*left_val, &*right_val, &*tol_1_val), format_args!($($arg)+) ) } } } }); } /// Asserts that two floating point expressions are equal to each other. /// /// See the top level documentation for a list of available [comparison algorithms]. /// /// On panic, this macro will print the values of the expressions with their debug /// representations, with [additional information] from the comparison operations. /// Like [`assert!`], this macro has a second form, where a custom panic message can /// be provided. /// /// Unlike [`assert_float_eq!`], `debug_assert_float_eq!` statements are only enabled in /// non optimized builds by default. See [`debug_assert_eq!`] for more details. /// /// # Examples /// ``` /// # use float_eq::debug_assert_float_eq; /// # use std::f32; /// let a: f32 = 4.0; /// let b: f32 = 4.000_002_5; /// /// debug_assert_float_eq!(a, b, ulps <= 10); /// debug_assert_float_eq!(a, 3.999_999_6, rmax <= 2.0 * f32::EPSILON); /// debug_assert_float_eq!(a - b, 0.0, abs <= 0.000_01, "Checking that {} == {}", a, b); /// ``` /// /// [`assert!`]: https://doc.rust-lang.org/std/macro.assert.html /// [`debug_assert_eq!`]: https://doc.rust-lang.org/std/macro.debug_assert_eq.html /// [additional information]: https://jtempest.github.io/float_eq-rs/book/how_to/interpret_assert_failure_messages.html /// [comparison algorithms]: index.html#comparison-algorithms /// [from left to right]: index.html#combining-checks #[macro_export] macro_rules! debug_assert_float_eq { ($($arg:tt)*) => (if cfg!(debug_assertions) { $crate::assert_float_eq!($($arg)*); }) } /// Asserts that two floating point expressions are not equal to each other. /// /// See the top level documentation for a list of available [comparison algorithms]. /// /// On panic, this macro will print the values of the expressions with their debug /// representations, with [additional information] from the comparison operations. /// Like [`assert!`], this macro has a second form, where a custom panic message can /// be provided. /// /// Unlike [`assert_float_ne!`], `debug_assert_float_ne!` statements are only enabled in /// non optimized builds by default. See [`debug_assert_ne!`] for more details. /// /// # Examples /// ``` /// # use float_eq::debug_assert_float_ne; /// # use std::f32; /// let a: f32 = 4.0; /// let b: f32 = 4.1; /// /// debug_assert_float_ne!(a, b, ulps <= 10); /// debug_assert_float_ne!(a, b, rmax <= 2.0 * f32::EPSILON); /// debug_assert_float_ne!(a - b, 0.0, abs <= 0.000_01, "Checking that {} != {}", a, b); /// ``` /// /// [`assert!`]: https://doc.rust-lang.org/std/macro.assert.html /// [`debug_assert_ne!`]: https://doc.rust-lang.org/std/macro.debug_assert_ne.html /// [additional information]: https://jtempest.github.io/float_eq-rs/book/how_to/interpret_assert_failure_messages.html /// [comparison algorithms]: index.html#comparison-algorithms /// [from left to right]: index.html#combining-checks #[macro_export] macro_rules! debug_assert_float_ne { ($($arg:tt)*) => (if cfg!(debug_assertions) { $crate::assert_float_ne!($($arg)*); }) } #[doc(hidden)] pub struct FloatEqCmp; #[doc(hidden)] impl FloatEqCmp { #[inline] pub fn abs(a: &A, b: &B, tol: &A::Tol) -> bool where A: FloatEq, { a.eq_abs(b, tol) } #[inline] pub fn abs_all(a: &A, b: &B, tol: &A::AllTol) -> bool where A: FloatEqAll, { a.eq_abs_all(b, tol) } #[inline] pub fn rel(a: &A, b: &B, tol: &A::Tol) -> bool where A: FloatEq, { a.eq_rel(b, tol) } #[inline] pub fn rel_all(a: &A, b: &B, tol: &A::AllTol) -> bool where A: FloatEqAll, { a.eq_rel_all(b, tol) } #[inline] pub fn rmax(a: &A, b: &B, tol: &A::Tol) -> bool where A: FloatEq, { a.eq_rmax(b, tol) } #[inline] pub fn rmax_all(a: &A, b: &B, tol: &A::AllTol) -> bool where A: FloatEqAll, { a.eq_rmax_all(b, tol) } #[inline] pub fn rmin(a: &A, b: &B, tol: &A::Tol) -> bool where A: FloatEq, { a.eq_rmin(b, tol) } #[inline] pub fn rmin_all(a: &A, b: &B, tol: &A::AllTol) -> bool where A: FloatEqAll, { a.eq_rmin_all(b, tol) } #[inline] pub fn r1st(a: &A, b: &B, tol: &A::Tol) -> bool where A: FloatEq, { a.eq_r1st(b, tol) } #[inline] pub fn r1st_all(a: &A, b: &B, tol: &A::AllTol) -> bool where A: FloatEqAll, { a.eq_r1st_all(b, tol) } #[inline] pub fn r2nd(a: &A, b: &B, tol: &A::Tol) -> bool where A: FloatEq, { a.eq_r2nd(b, tol) } #[inline] pub fn r2nd_all(a: &A, b: &B, tol: &A::AllTol) -> bool where A: FloatEqAll, { a.eq_r2nd_all(b, tol) } #[inline] pub fn ulps(a: &A, b: &B, tol: &UlpsTol) -> bool where A: FloatEq, { a.eq_ulps(b, tol) } #[inline] pub fn ulps_all(a: &A, b: &B, tol: &UlpsTol) -> bool where A: FloatEqAll, { a.eq_ulps_all(b, tol) } } #[doc(hidden)] pub struct FloatCmpOpTol; #[doc(hidden)] impl FloatCmpOpTol { #[inline] pub fn abs(a: &A, b: &B, tol: &A::Tol) -> A::DebugTol where A: FloatEq + AssertFloatEq, { a.debug_abs_tol(b, tol) } #[inline] pub fn abs_all(a: &A, b: &B, tol: &A::AllTol) -> A::AllDebugTol where A: FloatEqAll + AssertFloatEqAll, { a.debug_abs_all_tol(b, tol) } #[inline] pub fn rel(a: &A, b: &B, tol: &A::Tol) -> A::DebugTol where A: FloatEq + AssertFloatEq, { a.debug_rel_tol(b, tol) } #[inline] pub fn rel_all(a: &A, b: &B, tol: &A::AllTol) -> A::AllDebugTol where A: FloatEqAll + AssertFloatEqAll, { a.debug_rel_all_tol(b, tol) } #[inline] pub fn rmax(a: &A, b: &B, tol: &A::Tol) -> A::DebugTol where A: FloatEq + AssertFloatEq, { a.debug_rmax_tol(b, tol) } #[inline] pub fn rmax_all(a: &A, b: &B, tol: &A::AllTol) -> A::AllDebugTol where A: FloatEqAll + AssertFloatEqAll, { a.debug_rmax_all_tol(b, tol) } #[inline] pub fn rmin(a: &A, b: &B, tol: &A::Tol) -> A::DebugTol where A: FloatEq + AssertFloatEq, { a.debug_rmin_tol(b, tol) } #[inline] pub fn rmin_all(a: &A, b: &B, tol: &A::AllTol) -> A::AllDebugTol where A: FloatEqAll + AssertFloatEqAll, { a.debug_rmin_all_tol(b, tol) } #[inline] pub fn r1st(a: &A, b: &B, tol: &A::Tol) -> A::DebugTol where A: FloatEq + AssertFloatEq, { a.debug_r1st_tol(b, tol) } #[inline] pub fn r1st_all(a: &A, b: &B, tol: &A::AllTol) -> A::AllDebugTol where A: FloatEqAll + AssertFloatEqAll, { a.debug_r1st_all_tol(b, tol) } #[inline] pub fn r2nd(a: &A, b: &B, tol: &A::Tol) -> A::DebugTol where A: FloatEq + AssertFloatEq, { a.debug_r2nd_tol(b, tol) } #[inline] pub fn r2nd_all(a: &A, b: &B, tol: &A::AllTol) -> A::AllDebugTol where A: FloatEqAll + AssertFloatEqAll, { a.debug_r2nd_all_tol(b, tol) } #[inline] pub fn ulps(a: &A, b: &B, tol: &UlpsTol) -> UlpsTol where A: FloatEq + AssertFloatEq, UlpsTol: Sized, { a.debug_ulps_tol(b, tol) } #[inline] pub fn ulps_all( a: &A, b: &B, tol: &UlpsTol, ) -> UlpsTol where A: FloatEqAll + AssertFloatEqAll, UlpsTol: Sized, { a.debug_ulps_all_tol(b, tol) } } float_eq-1.0.1/src/trait_impls/arrays.rs000064400000000000000000000222450072674642500164370ustar 00000000000000use crate::{ AssertFloatEq, AssertFloatEqAll, DebugUlpsDiff, FloatEq, FloatEqAll, FloatEqDebugUlpsDiff, FloatEqUlpsTol, UlpsTol, }; use core::mem::MaybeUninit; // Uses the same technique as MaybeUninit::uninit_array. #[inline(always)] fn uninit_array() -> [MaybeUninit; N] { unsafe { MaybeUninit::<[MaybeUninit; N]>::uninit().assume_init() } } // Uses the same technique as MaybeUninit::array_assume_init. #[inline(always)] unsafe fn array_assume_init(array: [MaybeUninit; N]) -> [T; N] { (&array as *const _ as *const [T; N]).read() } impl FloatEqUlpsTol for [T; N] where UlpsTol: Sized, { type UlpsTol = [UlpsTol; N]; } impl FloatEqDebugUlpsDiff for [T; N] { type DebugUlpsDiff = [DebugUlpsDiff; N]; } impl FloatEq<[B; N]> for [A; N] where A: FloatEq, A::Tol: Sized, UlpsTol: Sized, { type Tol = [A::Tol; N]; #[inline] fn eq_abs(&self, other: &[B; N], tol: &Self::Tol) -> bool { for i in 0..N { if !self[i].eq_abs(&other[i], &tol[i]) { return false; } } true } #[inline] fn eq_rmax(&self, other: &[B; N], tol: &Self::Tol) -> bool { for i in 0..N { if !self[i].eq_rmax(&other[i], &tol[i]) { return false; } } true } #[inline] fn eq_rmin(&self, other: &[B; N], tol: &Self::Tol) -> bool { for i in 0..N { if !self[i].eq_rmin(&other[i], &tol[i]) { return false; } } true } #[inline] fn eq_r1st(&self, other: &[B; N], tol: &Self::Tol) -> bool { for i in 0..N { if !self[i].eq_r1st(&other[i], &tol[i]) { return false; } } true } #[inline] fn eq_r2nd(&self, other: &[B; N], tol: &Self::Tol) -> bool { for i in 0..N { if !self[i].eq_r2nd(&other[i], &tol[i]) { return false; } } true } #[inline] fn eq_ulps(&self, other: &[B; N], tol: &UlpsTol) -> bool { for i in 0..N { if !self[i].eq_ulps(&other[i], &tol[i]) { return false; } } true } } impl FloatEqAll<[B; N]> for [A; N] where A: FloatEqAll, { type AllTol = A::AllTol; #[inline] fn eq_abs_all(&self, other: &[B; N], tol: &Self::AllTol) -> bool { self.iter() .zip(other.iter()) .all(|(a, b)| a.eq_abs_all(b, tol)) } #[inline] fn eq_rmax_all(&self, other: &[B; N], tol: &Self::AllTol) -> bool { self.iter() .zip(other.iter()) .all(|(a, b)| a.eq_rmax_all(b, tol)) } #[inline] fn eq_rmin_all(&self, other: &[B; N], tol: &Self::AllTol) -> bool { self.iter() .zip(other.iter()) .all(|(a, b)| a.eq_rmin_all(b, tol)) } #[inline] fn eq_r1st_all(&self, other: &[B; N], tol: &Self::AllTol) -> bool { self.iter() .zip(other.iter()) .all(|(a, b)| a.eq_r1st_all(b, tol)) } #[inline] fn eq_r2nd_all(&self, other: &[B; N], tol: &Self::AllTol) -> bool { self.iter() .zip(other.iter()) .all(|(a, b)| a.eq_r2nd_all(b, tol)) } #[inline] fn eq_ulps_all(&self, other: &[B; N], tol: &UlpsTol) -> bool { self.iter() .zip(other.iter()) .all(|(a, b)| a.eq_ulps_all(b, tol)) } } impl AssertFloatEq<[B; N]> for [A; N] where A: AssertFloatEq, A::Tol: Sized, A::DebugTol: Sized, UlpsTol: Sized, UlpsTol: Sized, { type DebugAbsDiff = [A::DebugAbsDiff; N]; type DebugTol = [A::DebugTol; N]; #[inline] fn debug_abs_diff(&self, other: &[B; N]) -> Self::DebugAbsDiff { let mut result: [MaybeUninit; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_abs_diff(&other[i])); } unsafe { array_assume_init(result) } } #[inline] fn debug_ulps_diff(&self, other: &[B; N]) -> DebugUlpsDiff { let mut result: [MaybeUninit>; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_ulps_diff(&other[i])); } unsafe { array_assume_init(result) } } #[inline] fn debug_abs_tol(&self, other: &[B; N], tol: &Self::Tol) -> Self::DebugTol { let mut result: [MaybeUninit; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_abs_tol(&other[i], &tol[i])); } unsafe { array_assume_init(result) } } #[inline] fn debug_rmax_tol(&self, other: &[B; N], tol: &Self::Tol) -> Self::DebugTol { let mut result: [MaybeUninit; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_rmax_tol(&other[i], &tol[i])); } unsafe { array_assume_init(result) } } #[inline] fn debug_rmin_tol(&self, other: &[B; N], tol: &Self::Tol) -> Self::DebugTol { let mut result: [MaybeUninit; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_rmin_tol(&other[i], &tol[i])); } unsafe { array_assume_init(result) } } #[inline] fn debug_r1st_tol(&self, other: &[B; N], tol: &Self::Tol) -> Self::DebugTol { let mut result: [MaybeUninit; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_r1st_tol(&other[i], &tol[i])); } unsafe { array_assume_init(result) } } #[inline] fn debug_r2nd_tol(&self, other: &[B; N], tol: &Self::Tol) -> Self::DebugTol { let mut result: [MaybeUninit; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_r2nd_tol(&other[i], &tol[i])); } unsafe { array_assume_init(result) } } #[inline] fn debug_ulps_tol(&self, other: &[B; N], tol: &UlpsTol) -> UlpsTol { let mut result: [MaybeUninit>; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_ulps_tol(&other[i], &tol[i])); } unsafe { array_assume_init(result) } } } impl AssertFloatEqAll<[B; N]> for [A; N] where A: AssertFloatEqAll, UlpsTol: Sized, { type AllDebugTol = [A::AllDebugTol; N]; #[inline] fn debug_abs_all_tol(&self, other: &[B; N], tol: &Self::AllTol) -> Self::AllDebugTol { let mut result: [MaybeUninit; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_abs_all_tol(&other[i], tol)); } unsafe { array_assume_init(result) } } #[inline] fn debug_rmax_all_tol(&self, other: &[B; N], tol: &Self::AllTol) -> Self::AllDebugTol { let mut result: [MaybeUninit; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_rmax_all_tol(&other[i], tol)); } unsafe { array_assume_init(result) } } #[inline] fn debug_rmin_all_tol(&self, other: &[B; N], tol: &Self::AllTol) -> Self::AllDebugTol { let mut result: [MaybeUninit; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_rmin_all_tol(&other[i], tol)); } unsafe { array_assume_init(result) } } #[inline] fn debug_r1st_all_tol(&self, other: &[B; N], tol: &Self::AllTol) -> Self::AllDebugTol { let mut result: [MaybeUninit; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_r1st_all_tol(&other[i], tol)); } unsafe { array_assume_init(result) } } #[inline] fn debug_r2nd_all_tol(&self, other: &[B; N], tol: &Self::AllTol) -> Self::AllDebugTol { let mut result: [MaybeUninit; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_r2nd_all_tol(&other[i], tol)); } unsafe { array_assume_init(result) } } #[inline] fn debug_ulps_all_tol( &self, other: &[B; N], tol: &UlpsTol, ) -> UlpsTol { let mut result: [MaybeUninit>; N] = uninit_array(); for i in 0..N { result[i] = MaybeUninit::new(self[i].debug_ulps_all_tol(&other[i], tol)); } unsafe { array_assume_init(result) } } } float_eq-1.0.1/src/trait_impls/core_types.rs000064400000000000000000000742440072674642500173200ustar 00000000000000use crate::{ AssertFloatEq, AssertFloatEqAll, DebugUlpsDiff, FloatEq, FloatEqAll, FloatEqDebugUlpsDiff, FloatEqUlpsTol, UlpsTol, }; use core::cell::{Cell, RefCell}; //------------------------------------------------------------------------------ // ref types //------------------------------------------------------------------------------ macro_rules! impl_for_refs { // $a and $b are mutability (&$($a:ident)?, &$($b:ident)?) => { impl FloatEq<&$($b)? B> for &$($a)? A where A: FloatEq, { type Tol = A::Tol; #[inline] fn eq_abs(&self, other: &&$($b)? B, tol: &Self::Tol) -> bool { FloatEq::eq_abs(*self, *other, tol) } #[inline] fn eq_rmax(&self, other: &&$($b)? B, tol: &Self::Tol) -> bool { FloatEq::eq_rmax(*self, *other, tol) } #[inline] fn eq_rmin(&self, other: &&$($b)? B, tol: &Self::Tol) -> bool { FloatEq::eq_rmin(*self, *other, tol) } #[inline] fn eq_r1st(&self, other: &&$($b)? B, tol: &Self::Tol) -> bool { FloatEq::eq_r1st(*self, *other, tol) } #[inline] fn eq_r2nd(&self, other: &&$($b)? B, tol: &Self::Tol) -> bool { FloatEq::eq_r2nd(*self, *other, tol) } #[inline] fn eq_ulps(&self, other: &&$($b)? B, tol: &UlpsTol) -> bool { FloatEq::eq_ulps(*self, *other, tol) } } impl FloatEqAll<&$($b)? B> for &$($a)? A where A: FloatEqAll, { type AllTol = A::AllTol; #[inline] fn eq_abs_all(&self, other: &&$($b)? B, tol: &Self::AllTol) -> bool { FloatEqAll::eq_abs_all(*self, *other, tol) } #[inline] fn eq_rmax_all(&self, other: &&$($b)? B, tol: &Self::AllTol) -> bool { FloatEqAll::eq_rmax_all(*self, *other, tol) } #[inline] fn eq_rmin_all(&self, other: &&$($b)? B, tol: &Self::AllTol) -> bool { FloatEqAll::eq_rmin_all(*self, *other, tol) } #[inline] fn eq_r1st_all(&self, other: &&$($b)? B, tol: &Self::AllTol) -> bool { FloatEqAll::eq_r1st_all(*self, *other, tol) } #[inline] fn eq_r2nd_all(&self, other: &&$($b)? B, tol: &Self::AllTol) -> bool { FloatEqAll::eq_r2nd_all(*self, *other, tol) } #[inline] fn eq_ulps_all(&self, other: &&$($b)? B, tol: &UlpsTol) -> bool { FloatEqAll::eq_ulps_all(*self, *other, tol) } } impl AssertFloatEq<&$($b)? B> for &$($a)? A where A: AssertFloatEq, { type DebugAbsDiff = A::DebugAbsDiff; type DebugTol = A::DebugTol; #[inline] fn debug_abs_diff(&self, other: &&$($b)? B) -> Self::DebugAbsDiff { AssertFloatEq::debug_abs_diff(*self, *other) } #[inline] fn debug_ulps_diff(&self, other: &&$($b)? B) -> DebugUlpsDiff { AssertFloatEq::debug_ulps_diff(*self, *other) } #[inline] fn debug_abs_tol( &self, other: &&$($b)? B, tol: &Self::Tol ) -> Self::DebugTol { AssertFloatEq::debug_abs_tol(*self, *other, tol) } #[inline] fn debug_rmax_tol( &self, other: &&$($b)? B, tol: &Self::Tol ) -> Self::DebugTol { AssertFloatEq::debug_rmax_tol(*self, *other, tol) } #[inline] fn debug_rmin_tol( &self, other: &&$($b)? B, tol: &Self::Tol ) -> Self::DebugTol { AssertFloatEq::debug_rmin_tol(*self, *other, tol) } #[inline] fn debug_r1st_tol( &self, other: &&$($b)? B, tol: &Self::Tol ) -> Self::DebugTol { AssertFloatEq::debug_r1st_tol(*self, *other, tol) } #[inline] fn debug_r2nd_tol( &self, other: &&$($b)? B, tol: &Self::Tol ) -> Self::DebugTol { AssertFloatEq::debug_r2nd_tol(*self, *other, tol) } #[inline] fn debug_ulps_tol( &self, other: &&$($b)? B, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized { AssertFloatEq::debug_ulps_tol(*self, *other, tol) } } impl AssertFloatEqAll<&$($b)? B> for &$($a)? A where A: AssertFloatEqAll, { type AllDebugTol = A::AllDebugTol; #[inline] fn debug_abs_all_tol( &self, other: &&$($b)? B, tol: &Self::AllTol ) -> Self::AllDebugTol { AssertFloatEqAll::debug_abs_all_tol(*self, *other, tol) } #[inline] fn debug_rmax_all_tol( &self, other: &&$($b)? B, tol: &Self::AllTol ) -> Self::AllDebugTol { AssertFloatEqAll::debug_rmax_all_tol(*self, *other, tol) } #[inline] fn debug_rmin_all_tol( &self, other: &&$($b)? B, tol: &Self::AllTol ) -> Self::AllDebugTol { AssertFloatEqAll::debug_rmin_all_tol(*self, *other, tol) } #[inline] fn debug_r1st_all_tol( &self, other: &&$($b)? B, tol: &Self::AllTol ) -> Self::AllDebugTol { AssertFloatEqAll::debug_r1st_all_tol(*self, *other, tol) } #[inline] fn debug_r2nd_all_tol( &self, other: &&$($b)? B, tol: &Self::AllTol ) -> Self::AllDebugTol { AssertFloatEqAll::debug_r2nd_all_tol(*self, *other, tol) } #[inline] fn debug_ulps_all_tol( &self, other: &&$($b)? B, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized { AssertFloatEqAll::debug_ulps_all_tol(*self, *other, tol) } } }; } impl_for_refs!(&, &); impl_for_refs!(&, &mut); impl_for_refs!(&mut, &); impl_for_refs!(&mut, &mut); //------------------------------------------------------------------------------ // Option // // Note: The Option impls are over `impl` and not `impl` since that breaks // type inference and makes it harder to use `None`. // // Open question: should None == None? it currently does not. //------------------------------------------------------------------------------ impl FloatEqUlpsTol for Option where UlpsTol: Sized, { type UlpsTol = Option>; } impl FloatEqDebugUlpsDiff for Option { type DebugUlpsDiff = Option>; } impl FloatEq for Option where T::Tol: Sized, UlpsTol: Sized, { type Tol = Option; #[inline] fn eq_abs(&self, other: &Option, tol: &Self::Tol) -> bool { if let (Some(s), Some(o), Some(t)) = (self, other, tol) { s.eq_abs(o, t) } else { false } } #[inline] fn eq_rmax(&self, other: &Option, tol: &Self::Tol) -> bool { if let (Some(s), Some(o), Some(t)) = (self, other, tol) { s.eq_rmax(o, t) } else { false } } #[inline] fn eq_rmin(&self, other: &Option, tol: &Self::Tol) -> bool { if let (Some(s), Some(o), Some(t)) = (self, other, tol) { s.eq_rmin(o, t) } else { false } } #[inline] fn eq_r1st(&self, other: &Option, tol: &Self::Tol) -> bool { if let (Some(s), Some(o), Some(t)) = (self, other, tol) { s.eq_r1st(o, t) } else { false } } #[inline] fn eq_r2nd(&self, other: &Option, tol: &Self::Tol) -> bool { if let (Some(s), Some(o), Some(t)) = (self, other, tol) { s.eq_r2nd(o, t) } else { false } } #[inline] fn eq_ulps(&self, other: &Option, tol: &UlpsTol) -> bool { if let (Some(s), Some(o), Some(t)) = (self, other, tol) { s.eq_ulps(o, t) } else { false } } } impl FloatEqAll> for Option where T::AllTol: Sized, UlpsTol: Sized, { type AllTol = Option; #[inline] fn eq_abs_all(&self, other: &Option, tol: &Self::AllTol) -> bool { if let (Some(s), Some(o), Some(t)) = (self, other, tol) { s.eq_abs_all(o, t) } else { false } } #[inline] fn eq_rmax_all(&self, other: &Option, tol: &Self::AllTol) -> bool { if let (Some(s), Some(o), Some(t)) = (self, other, tol) { s.eq_rmax_all(o, t) } else { false } } #[inline] fn eq_rmin_all(&self, other: &Option, tol: &Self::AllTol) -> bool { if let (Some(s), Some(o), Some(t)) = (self, other, tol) { s.eq_rmin_all(o, t) } else { false } } #[inline] fn eq_r1st_all(&self, other: &Option, tol: &Self::AllTol) -> bool { if let (Some(s), Some(o), Some(t)) = (self, other, tol) { s.eq_r1st_all(o, t) } else { false } } #[inline] fn eq_r2nd_all(&self, other: &Option, tol: &Self::AllTol) -> bool { if let (Some(s), Some(o), Some(t)) = (self, other, tol) { s.eq_r2nd_all(o, t) } else { false } } #[inline] fn eq_ulps_all(&self, other: &Option, tol: &UlpsTol) -> bool { if let (Some(s), Some(o), Some(t)) = (self, other, tol) { s.eq_ulps_all(o, t) } else { false } } } impl AssertFloatEq for Option where T::Tol: Sized, UlpsTol: Sized, UlpsTol: Sized, { type DebugAbsDiff = Option; type DebugTol = Option; #[inline] fn debug_abs_diff(&self, other: &Option) -> Self::DebugAbsDiff { Some(AssertFloatEq::debug_abs_diff( self.as_ref()?, other.as_ref()?, )) } #[inline] fn debug_ulps_diff(&self, other: &Option) -> DebugUlpsDiff { Some(AssertFloatEq::debug_ulps_diff( self.as_ref()?, other.as_ref()?, )) } #[inline] fn debug_abs_tol(&self, other: &Option, tol: &Self::Tol) -> Self::DebugTol { Some(AssertFloatEq::debug_abs_tol( &self.as_ref()?, &other.as_ref()?, tol.as_ref()?, )) } #[inline] fn debug_rmax_tol(&self, other: &Option, tol: &Self::Tol) -> Self::DebugTol { Some(AssertFloatEq::debug_rmax_tol( &self.as_ref()?, &other.as_ref()?, tol.as_ref()?, )) } #[inline] fn debug_rmin_tol(&self, other: &Option, tol: &Self::Tol) -> Self::DebugTol { Some(AssertFloatEq::debug_rmin_tol( &self.as_ref()?, &other.as_ref()?, tol.as_ref()?, )) } #[inline] fn debug_r1st_tol(&self, other: &Option, tol: &Self::Tol) -> Self::DebugTol { Some(AssertFloatEq::debug_r1st_tol( &self.as_ref()?, &other.as_ref()?, tol.as_ref()?, )) } #[inline] fn debug_r2nd_tol(&self, other: &Option, tol: &Self::Tol) -> Self::DebugTol { Some(AssertFloatEq::debug_r2nd_tol( &self.as_ref()?, &other.as_ref()?, tol.as_ref()?, )) } #[inline] fn debug_ulps_tol( &self, other: &Option, tol: &UlpsTol, ) -> UlpsTol { Some(AssertFloatEq::debug_ulps_tol( &self.as_ref()?, &other.as_ref()?, tol.as_ref()?, )) } } impl AssertFloatEqAll for Option where T::AllTol: Sized, UlpsTol: Sized, UlpsTol: Sized, { type AllDebugTol = Option; #[inline] fn debug_abs_all_tol(&self, other: &Option, tol: &Self::AllTol) -> Self::AllDebugTol { Some(AssertFloatEqAll::debug_abs_all_tol( &self.as_ref()?, &other.as_ref()?, tol.as_ref()?, )) } #[inline] fn debug_rmax_all_tol(&self, other: &Option, tol: &Self::AllTol) -> Self::AllDebugTol { Some(AssertFloatEqAll::debug_rmax_all_tol( &self.as_ref()?, &other.as_ref()?, tol.as_ref()?, )) } #[inline] fn debug_rmin_all_tol(&self, other: &Option, tol: &Self::AllTol) -> Self::AllDebugTol { Some(AssertFloatEqAll::debug_rmin_all_tol( &self.as_ref()?, &other.as_ref()?, tol.as_ref()?, )) } #[inline] fn debug_r1st_all_tol(&self, other: &Option, tol: &Self::AllTol) -> Self::AllDebugTol { Some(AssertFloatEqAll::debug_r1st_all_tol( &self.as_ref()?, &other.as_ref()?, tol.as_ref()?, )) } #[inline] fn debug_r2nd_all_tol(&self, other: &Option, tol: &Self::AllTol) -> Self::AllDebugTol { Some(AssertFloatEqAll::debug_r2nd_all_tol( &self.as_ref()?, &other.as_ref()?, tol.as_ref()?, )) } #[inline] fn debug_ulps_all_tol( &self, other: &Option, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized, { Some(AssertFloatEqAll::debug_ulps_all_tol( &self.as_ref()?, &other.as_ref()?, tol.as_ref()?, )) } } //------------------------------------------------------------------------------ // Cell //------------------------------------------------------------------------------ impl FloatEq> for Cell where A: FloatEq + Copy, B: Copy, { type Tol = A::Tol; #[inline] fn eq_abs(&self, other: &Cell, tol: &Self::Tol) -> bool { FloatEq::eq_abs(&self.get(), &other.get(), tol) } #[inline] fn eq_rmax(&self, other: &Cell, tol: &Self::Tol) -> bool { FloatEq::eq_rmax(&self.get(), &other.get(), tol) } #[inline] fn eq_rmin(&self, other: &Cell, tol: &Self::Tol) -> bool { FloatEq::eq_rmin(&self.get(), &other.get(), tol) } #[inline] fn eq_r1st(&self, other: &Cell, tol: &Self::Tol) -> bool { FloatEq::eq_r1st(&self.get(), &other.get(), tol) } #[inline] fn eq_r2nd(&self, other: &Cell, tol: &Self::Tol) -> bool { FloatEq::eq_r2nd(&self.get(), &other.get(), tol) } #[inline] fn eq_ulps(&self, other: &Cell, tol: &UlpsTol) -> bool { FloatEq::eq_ulps(&self.get(), &other.get(), tol) } } impl FloatEqAll> for Cell where A: FloatEqAll + Copy, B: Copy, { type AllTol = A::AllTol; #[inline] fn eq_abs_all(&self, other: &Cell, tol: &Self::AllTol) -> bool { FloatEqAll::eq_abs_all(&self.get(), &other.get(), tol) } #[inline] fn eq_rmax_all(&self, other: &Cell, tol: &Self::AllTol) -> bool { FloatEqAll::eq_rmax_all(&self.get(), &other.get(), tol) } #[inline] fn eq_rmin_all(&self, other: &Cell, tol: &Self::AllTol) -> bool { FloatEqAll::eq_rmin_all(&self.get(), &other.get(), tol) } #[inline] fn eq_r1st_all(&self, other: &Cell, tol: &Self::AllTol) -> bool { FloatEqAll::eq_r1st_all(&self.get(), &other.get(), tol) } #[inline] fn eq_r2nd_all(&self, other: &Cell, tol: &Self::AllTol) -> bool { FloatEqAll::eq_r2nd_all(&self.get(), &other.get(), tol) } #[inline] fn eq_ulps_all(&self, other: &Cell, tol: &UlpsTol) -> bool { FloatEqAll::eq_ulps_all(&self.get(), &other.get(), tol) } } impl AssertFloatEq> for Cell where A: AssertFloatEq + Copy, B: Copy, { type DebugAbsDiff = A::DebugAbsDiff; type DebugTol = A::DebugTol; #[inline] fn debug_abs_diff(&self, other: &Cell) -> Self::DebugAbsDiff { AssertFloatEq::debug_abs_diff(&self.get(), &other.get()) } #[inline] fn debug_ulps_diff(&self, other: &Cell) -> DebugUlpsDiff { AssertFloatEq::debug_ulps_diff(&self.get(), &other.get()) } #[inline] fn debug_abs_tol(&self, other: &Cell, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_abs_tol(&self.get(), &other.get(), tol) } #[inline] fn debug_rmax_tol(&self, other: &Cell, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_rmax_tol(&self.get(), &other.get(), tol) } #[inline] fn debug_rmin_tol(&self, other: &Cell, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_rmin_tol(&self.get(), &other.get(), tol) } #[inline] fn debug_r1st_tol(&self, other: &Cell, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_r1st_tol(&self.get(), &other.get(), tol) } #[inline] fn debug_r2nd_tol(&self, other: &Cell, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_r2nd_tol(&self.get(), &other.get(), tol) } #[inline] fn debug_ulps_tol(&self, other: &Cell, tol: &UlpsTol) -> UlpsTol where UlpsTol: Sized, { AssertFloatEq::debug_ulps_tol(&self.get(), &other.get(), tol) } } impl AssertFloatEqAll> for Cell where A: AssertFloatEqAll + Copy, B: Copy, { type AllDebugTol = A::AllDebugTol; #[inline] fn debug_abs_all_tol(&self, other: &Cell, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_abs_all_tol(&self.get(), &other.get(), tol) } #[inline] fn debug_rmax_all_tol(&self, other: &Cell, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_rmax_all_tol(&self.get(), &other.get(), tol) } #[inline] fn debug_rmin_all_tol(&self, other: &Cell, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_rmin_all_tol(&self.get(), &other.get(), tol) } #[inline] fn debug_r1st_all_tol(&self, other: &Cell, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_r1st_all_tol(&self.get(), &other.get(), tol) } #[inline] fn debug_r2nd_all_tol(&self, other: &Cell, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_r2nd_all_tol(&self.get(), &other.get(), tol) } #[inline] fn debug_ulps_all_tol( &self, other: &Cell, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized, { AssertFloatEqAll::debug_ulps_all_tol(&self.get(), &other.get(), tol) } } //------------------------------------------------------------------------------ // RefCell //------------------------------------------------------------------------------ impl FloatEq> for RefCell where A: FloatEq, { type Tol = A::Tol; #[inline] fn eq_abs(&self, other: &RefCell, tol: &Self::Tol) -> bool { FloatEq::eq_abs(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn eq_rmax(&self, other: &RefCell, tol: &Self::Tol) -> bool { FloatEq::eq_rmax(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn eq_rmin(&self, other: &RefCell, tol: &Self::Tol) -> bool { FloatEq::eq_rmin(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn eq_r1st(&self, other: &RefCell, tol: &Self::Tol) -> bool { FloatEq::eq_r1st(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn eq_r2nd(&self, other: &RefCell, tol: &Self::Tol) -> bool { FloatEq::eq_r2nd(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn eq_ulps(&self, other: &RefCell, tol: &UlpsTol) -> bool { FloatEq::eq_ulps(&*self.borrow(), &*other.borrow(), tol) } } impl FloatEqAll> for RefCell where A: FloatEqAll, { type AllTol = A::AllTol; #[inline] fn eq_abs_all(&self, other: &RefCell, tol: &Self::AllTol) -> bool { FloatEqAll::eq_abs_all(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn eq_rmax_all(&self, other: &RefCell, tol: &Self::AllTol) -> bool { FloatEqAll::eq_rmax_all(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn eq_rmin_all(&self, other: &RefCell, tol: &Self::AllTol) -> bool { FloatEqAll::eq_rmin_all(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn eq_r1st_all(&self, other: &RefCell, tol: &Self::AllTol) -> bool { FloatEqAll::eq_r1st_all(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn eq_r2nd_all(&self, other: &RefCell, tol: &Self::AllTol) -> bool { FloatEqAll::eq_r2nd_all(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn eq_ulps_all(&self, other: &RefCell, tol: &UlpsTol) -> bool { FloatEqAll::eq_ulps_all(&*self.borrow(), &*other.borrow(), tol) } } impl AssertFloatEq> for RefCell where A: AssertFloatEq + Copy, B: Copy, { type DebugAbsDiff = A::DebugAbsDiff; type DebugTol = A::DebugTol; #[inline] fn debug_abs_diff(&self, other: &RefCell) -> Self::DebugAbsDiff { AssertFloatEq::debug_abs_diff(&*self.borrow(), &*other.borrow()) } #[inline] fn debug_ulps_diff(&self, other: &RefCell) -> DebugUlpsDiff { AssertFloatEq::debug_ulps_diff(&*self.borrow(), &*other.borrow()) } #[inline] fn debug_abs_tol(&self, other: &RefCell, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_abs_tol(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn debug_rmax_tol(&self, other: &RefCell, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_rmax_tol(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn debug_rmin_tol(&self, other: &RefCell, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_rmin_tol(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn debug_r1st_tol(&self, other: &RefCell, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_r1st_tol(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn debug_r2nd_tol(&self, other: &RefCell, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_r2nd_tol(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn debug_ulps_tol( &self, other: &RefCell, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized, { AssertFloatEq::debug_ulps_tol(&*self.borrow(), &*other.borrow(), tol) } } impl AssertFloatEqAll> for RefCell where A: AssertFloatEqAll + Copy, B: Copy, { type AllDebugTol = A::AllDebugTol; #[inline] fn debug_abs_all_tol(&self, other: &RefCell, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_abs_all_tol(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn debug_rmax_all_tol(&self, other: &RefCell, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_rmax_all_tol(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn debug_rmin_all_tol(&self, other: &RefCell, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_rmin_all_tol(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn debug_r1st_all_tol(&self, other: &RefCell, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_r1st_all_tol(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn debug_r2nd_all_tol(&self, other: &RefCell, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_r2nd_all_tol(&*self.borrow(), &*other.borrow(), tol) } #[inline] fn debug_ulps_all_tol( &self, other: &RefCell, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized, { AssertFloatEqAll::debug_ulps_all_tol(&*self.borrow(), &*other.borrow(), tol) } } //------------------------------------------------------------------------------ // Slices //------------------------------------------------------------------------------ impl FloatEqUlpsTol for [T] where UlpsTol: Sized, { type UlpsTol = [UlpsTol]; } impl FloatEq<[B]> for [A] where A: FloatEq, A::Tol: Sized, UlpsTol: Sized, { type Tol = [A::Tol]; #[inline] fn eq_abs(&self, other: &[B], tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self .iter() .zip(other.iter()) .zip(tol.iter()) .all(|((a, b), eps)| a.eq_abs(b, eps)) } #[inline] fn eq_rmax(&self, other: &[B], tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self .iter() .zip(other.iter()) .zip(tol.iter()) .all(|((a, b), eps)| a.eq_rmax(b, eps)) } #[inline] fn eq_rmin(&self, other: &[B], tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self .iter() .zip(other.iter()) .zip(tol.iter()) .all(|((a, b), eps)| a.eq_rmin(b, eps)) } #[inline] fn eq_r1st(&self, other: &[B], tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self .iter() .zip(other.iter()) .zip(tol.iter()) .all(|((a, b), eps)| a.eq_r1st(b, eps)) } #[inline] fn eq_r2nd(&self, other: &[B], tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self .iter() .zip(other.iter()) .zip(tol.iter()) .all(|((a, b), eps)| a.eq_r2nd(b, eps)) } #[inline] fn eq_ulps(&self, other: &[B], tol: &UlpsTol) -> bool { self.len() == other.len() && self.len() == tol.len() && self .iter() .zip(other.iter()) .zip(tol.iter()) .all(|((a, b), eps)| a.eq_ulps(b, eps)) } } impl FloatEqAll<[B]> for [A] where A: FloatEqAll, { type AllTol = A::AllTol; #[inline] fn eq_abs_all(&self, other: &[B], tol: &Self::AllTol) -> bool { self.len() == other.len() && self .iter() .zip(other.iter()) .all(|(a, b)| a.eq_abs_all(b, tol)) } #[inline] fn eq_rmax_all(&self, other: &[B], tol: &Self::AllTol) -> bool { self.len() == other.len() && self .iter() .zip(other.iter()) .all(|(a, b)| a.eq_rmax_all(b, tol)) } #[inline] fn eq_rmin_all(&self, other: &[B], tol: &Self::AllTol) -> bool { self.len() == other.len() && self .iter() .zip(other.iter()) .all(|(a, b)| a.eq_rmin_all(b, tol)) } #[inline] fn eq_r1st_all(&self, other: &[B], tol: &Self::AllTol) -> bool { self.len() == other.len() && self .iter() .zip(other.iter()) .all(|(a, b)| a.eq_r1st_all(b, tol)) } #[inline] fn eq_r2nd_all(&self, other: &[B], tol: &Self::AllTol) -> bool { self.len() == other.len() && self .iter() .zip(other.iter()) .all(|(a, b)| a.eq_r2nd_all(b, tol)) } #[inline] fn eq_ulps_all(&self, other: &[B], tol: &UlpsTol) -> bool { self.len() == other.len() && self .iter() .zip(other.iter()) .all(|(a, b)| a.eq_ulps_all(b, tol)) } } float_eq-1.0.1/src/trait_impls/num_complex.rs000064400000000000000000000203320072674642500174570ustar 00000000000000use crate::{ AssertFloatEq, AssertFloatEqAll, DebugUlpsDiff, FloatEq, FloatEqAll, FloatEqDebugUlpsDiff, FloatEqUlpsTol, UlpsTol, }; use num_complex::Complex; /// The absolute difference between two floating point [`num::Complex`] instances /// in ULPs. /// /// The `T` in [`num::Complex`] is constrained by `Clone` and `PartialEq`, so this /// implements those too. /// /// [`num::Complex`]: https://docs.rs/num/0.3.0/num/struct.Complex.html #[allow(clippy::derive_partial_eq_without_eq)] // Most likely this is going to use floats, and we don't want to derive Eq for those #[derive(Clone, Debug, PartialEq)] pub struct ComplexUlps { /// Real portion of the complex number in ULPs. pub re: T, /// Imaginary portion of the complex number in ULPs. pub im: T, } impl ComplexUlps { /// Create a new ComplexUlps pub fn new(re: T, im: T) -> Self { ComplexUlps { re, im } } } impl FloatEqUlpsTol for Complex where UlpsTol: Sized, { type UlpsTol = ComplexUlps>; } impl FloatEqDebugUlpsDiff for Complex { type DebugUlpsDiff = ComplexUlps>; } /// [`ComplexUlps`] type matching [`num::Complex32`]. /// /// [`num::Complex32`]: https://docs.rs/num-complex/0.3/num_complex/type.Complex32.html pub type ComplexUlps32 = UlpsTol>; /// [`ComplexUlps`] type matching [`num::Complex64`]. /// /// [`num::Complex64`]: https://docs.rs/num-complex/0.3/num_complex/type.Complex64.html pub type ComplexUlps64 = UlpsTol>; impl FloatEq for Complex where T::Tol: Sized, UlpsTol: Sized, { type Tol = Complex; #[inline] fn eq_abs(&self, other: &Self, tol: &Self::Tol) -> bool { self.re.eq_abs(&other.re, &tol.re) && self.im.eq_abs(&other.im, &tol.im) } #[inline] fn eq_rmax(&self, other: &Self, tol: &Self::Tol) -> bool { self.re.eq_rmax(&other.re, &tol.re) && self.im.eq_rmax(&other.im, &tol.im) } #[inline] fn eq_rmin(&self, other: &Self, tol: &Self::Tol) -> bool { self.re.eq_rmin(&other.re, &tol.re) && self.im.eq_rmin(&other.im, &tol.im) } #[inline] fn eq_r1st(&self, other: &Self, tol: &Self::Tol) -> bool { self.re.eq_r1st(&other.re, &tol.re) && self.im.eq_r1st(&other.im, &tol.im) } #[inline] fn eq_r2nd(&self, other: &Self, tol: &Self::Tol) -> bool { self.re.eq_r2nd(&other.re, &tol.re) && self.im.eq_r2nd(&other.im, &tol.im) } #[inline] fn eq_ulps(&self, other: &Self, tol: &UlpsTol) -> bool { self.re.eq_ulps(&other.re, &tol.re) && self.im.eq_ulps(&other.im, &tol.im) } } impl FloatEqAll for Complex { type AllTol = T::AllTol; #[inline] fn eq_abs_all(&self, other: &Self, tol: &Self::AllTol) -> bool { self.re.eq_abs_all(&other.re, tol) && self.im.eq_abs_all(&other.im, tol) } #[inline] fn eq_rmax_all(&self, other: &Self, tol: &Self::AllTol) -> bool { self.re.eq_rmax_all(&other.re, tol) && self.im.eq_rmax_all(&other.im, tol) } #[inline] fn eq_rmin_all(&self, other: &Self, tol: &Self::AllTol) -> bool { self.re.eq_rmin_all(&other.re, tol) && self.im.eq_rmin_all(&other.im, tol) } #[inline] fn eq_r1st_all(&self, other: &Self, tol: &Self::AllTol) -> bool { self.re.eq_r1st_all(&other.re, tol) && self.im.eq_r1st_all(&other.im, tol) } #[inline] fn eq_r2nd_all(&self, other: &Self, tol: &Self::AllTol) -> bool { self.re.eq_r2nd_all(&other.re, tol) && self.im.eq_r2nd_all(&other.im, tol) } #[inline] fn eq_ulps_all(&self, other: &Self, tol: &UlpsTol) -> bool { self.re.eq_ulps_all(&other.re, tol) && self.im.eq_ulps_all(&other.im, tol) } } impl AssertFloatEq for Complex where T: AssertFloatEq, T::Tol: Sized, T::DebugTol: Sized, UlpsTol: Sized, UlpsTol: Sized, { type DebugAbsDiff = Complex; type DebugTol = Complex; #[inline] fn debug_abs_diff(&self, other: &Self) -> Self::DebugAbsDiff { Self::DebugAbsDiff { re: self.re.debug_abs_diff(&other.re), im: self.im.debug_abs_diff(&other.im), } } #[inline] fn debug_ulps_diff(&self, other: &Self) -> DebugUlpsDiff { DebugUlpsDiff:: { re: self.re.debug_ulps_diff(&other.re), im: self.im.debug_ulps_diff(&other.im), } } #[inline] fn debug_abs_tol(&self, other: &Self, tol: &Self::Tol) -> Self::DebugTol { Self::DebugTol { re: self.re.debug_abs_tol(&other.re, &tol.re), im: self.im.debug_abs_tol(&other.im, &tol.im), } } #[inline] fn debug_rmax_tol(&self, other: &Self, tol: &Self::Tol) -> Self::DebugTol { Self::DebugTol { re: self.re.debug_rmax_tol(&other.re, &tol.re), im: self.im.debug_rmax_tol(&other.im, &tol.im), } } #[inline] fn debug_rmin_tol(&self, other: &Self, tol: &Self::Tol) -> Self::DebugTol { Self::DebugTol { re: self.re.debug_rmin_tol(&other.re, &tol.re), im: self.im.debug_rmin_tol(&other.im, &tol.im), } } #[inline] fn debug_r1st_tol(&self, other: &Self, tol: &Self::Tol) -> Self::DebugTol { Self::DebugTol { re: self.re.debug_r1st_tol(&other.re, &tol.re), im: self.im.debug_r1st_tol(&other.im, &tol.im), } } #[inline] fn debug_r2nd_tol(&self, other: &Self, tol: &Self::Tol) -> Self::DebugTol { Self::DebugTol { re: self.re.debug_r2nd_tol(&other.re, &tol.re), im: self.im.debug_r2nd_tol(&other.im, &tol.im), } } #[inline] fn debug_ulps_tol(&self, other: &Self, tol: &UlpsTol) -> UlpsTol where UlpsTol: Sized, { UlpsTol:: { re: self.re.debug_ulps_tol(&other.re, &tol.re), im: self.im.debug_ulps_tol(&other.im, &tol.im), } } } impl AssertFloatEqAll for Complex where T: AssertFloatEqAll, T::AllDebugTol: Sized, UlpsTol: Sized, { type AllDebugTol = Complex; #[inline] fn debug_abs_all_tol(&self, other: &Self, tol: &Self::AllTol) -> Self::AllDebugTol { Self::AllDebugTol { re: self.re.debug_abs_all_tol(&other.re, tol), im: self.im.debug_abs_all_tol(&other.im, tol), } } #[inline] fn debug_rmax_all_tol(&self, other: &Self, tol: &Self::AllTol) -> Self::AllDebugTol { Self::AllDebugTol { re: self.re.debug_rmax_all_tol(&other.re, tol), im: self.im.debug_rmax_all_tol(&other.im, tol), } } #[inline] fn debug_rmin_all_tol(&self, other: &Self, tol: &Self::AllTol) -> Self::AllDebugTol { Self::AllDebugTol { re: self.re.debug_rmin_all_tol(&other.re, tol), im: self.im.debug_rmin_all_tol(&other.im, tol), } } #[inline] fn debug_r1st_all_tol(&self, other: &Self, tol: &Self::AllTol) -> Self::AllDebugTol { Self::AllDebugTol { re: self.re.debug_r1st_all_tol(&other.re, tol), im: self.im.debug_r1st_all_tol(&other.im, tol), } } #[inline] fn debug_r2nd_all_tol(&self, other: &Self, tol: &Self::AllTol) -> Self::AllDebugTol { Self::AllDebugTol { re: self.re.debug_r2nd_all_tol(&other.re, tol), im: self.im.debug_r2nd_all_tol(&other.im, tol), } } #[inline] fn debug_ulps_all_tol( &self, other: &Self, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized, { UlpsTol:: { re: self.re.debug_ulps_all_tol(&other.re, tol), im: self.im.debug_ulps_all_tol(&other.im, tol), } } } float_eq-1.0.1/src/trait_impls/primitives.rs000064400000000000000000000176440072674642500173400ustar 00000000000000#![allow(clippy::float_cmp)] use crate::{ AssertFloatEq, AssertFloatEqAll, DebugUlpsDiff, FloatEq, FloatEqAll, FloatEqDebugUlpsDiff, FloatEqUlpsTol, UlpsTol, }; macro_rules! impl_traits { ($float:ident, $uint:ident) => { mod $float { #[cfg(feature = "std")] #[inline] pub(crate) fn abs(value: $float) -> $float { // use the intrinsic for std builds value.abs() } #[cfg(not(feature = "std"))] #[inline] pub(crate) fn abs(value: $float) -> $float { // mask away only the sign bit for no_std builds since the abs // method is not available const MASK: $uint = !(1 << ((::core::mem::size_of::<$float>() * 8) - 1)); $float::from_bits(value.to_bits() & MASK) } } impl FloatEqUlpsTol for $float { type UlpsTol = $uint; } impl FloatEqDebugUlpsDiff for $float { type DebugUlpsDiff = Option<$uint>; } impl FloatEq for $float { type Tol = Self; #[inline] fn eq_abs(&self, other: &Self, tol: &Self::Tol) -> bool { // the PartialEq check covers equality of infinities self == other || $float::abs(self - other).le(tol) } #[inline] fn eq_rmax(&self, other: &Self, tol: &Self::Tol) -> bool { // the PartialEq check covers equality of infinities self == other || { let largest = $float::abs(*self).max($float::abs(*other)); let tol = largest * tol; $float::abs(self - other) <= tol } } #[inline] fn eq_rmin(&self, other: &Self, tol: &Self::Tol) -> bool { // the PartialEq check covers equality of infinities self == other || { let largest = $float::abs(*self).min($float::abs(*other)); let tol = largest * tol; $float::abs(self - other) <= tol } } #[inline] fn eq_r1st(&self, other: &Self, tol: &Self::Tol) -> bool { // the PartialEq check covers equality of infinities self == other || { let tol = $float::abs(*self) * tol; $float::abs(self - other) <= tol } } #[inline] fn eq_r2nd(&self, other: &Self, tol: &Self::Tol) -> bool { // the PartialEq check covers equality of infinities self == other || { let tol = $float::abs(*other) * tol; $float::abs(self - other) <= tol } } #[inline] fn eq_ulps(&self, other: &Self, tol: &UlpsTol) -> bool { if self.is_nan() || other.is_nan() { false // NaNs are never equal } else if self.is_sign_positive() != other.is_sign_positive() { self == other // account for zero == negative zero } else { let a = self.to_bits(); let b = other.to_bits(); let max = a.max(b); let min = a.min(b); (max - min).le(tol) } } } impl FloatEqAll for $float { type AllTol = $float; #[inline] fn eq_abs_all(&self, other: &Self, tol: &Self::AllTol) -> bool { self.eq_abs(other, tol) } #[inline] fn eq_rmax_all(&self, other: &Self, tol: &Self::AllTol) -> bool { self.eq_rmax(other, tol) } #[inline] fn eq_rmin_all(&self, other: &Self, tol: &Self::AllTol) -> bool { self.eq_rmin(other, tol) } #[inline] fn eq_r1st_all(&self, other: &Self, tol: &Self::AllTol) -> bool { self.eq_r1st(other, tol) } #[inline] fn eq_r2nd_all(&self, other: &Self, tol: &Self::AllTol) -> bool { self.eq_r2nd(other, tol) } #[inline] fn eq_ulps_all(&self, other: &Self, tol: &UlpsTol) -> bool { self.eq_ulps(other, tol) } } impl AssertFloatEq for $float { type DebugAbsDiff = Self; type DebugTol = Self::Tol; #[inline] fn debug_abs_diff(&self, other: &Self) -> Self::DebugAbsDiff { $float::abs(self - other) } #[inline] fn debug_ulps_diff(&self, other: &Self) -> DebugUlpsDiff { if self == other { Some(0) } else if self.is_nan() || other.is_nan() { None } else if self.is_sign_positive() != other.is_sign_positive() { None } else { let a = self.to_bits(); let b = other.to_bits(); let max = a.max(b); let min = a.min(b); Some(max - min) } } #[inline] fn debug_abs_tol(&self, _other: &Self, tol: &Self::Tol) -> Self::DebugTol { *tol } #[inline] fn debug_rmax_tol(&self, other: &Self, tol: &Self::Tol) -> Self::DebugTol { $float::abs(*self).max($float::abs(*other)) * tol } #[inline] fn debug_rmin_tol(&self, other: &Self, tol: &Self::Tol) -> Self::DebugTol { $float::abs(*self).min($float::abs(*other)) * tol } #[inline] fn debug_r1st_tol(&self, _other: &Self, tol: &Self::Tol) -> Self::DebugTol { $float::abs(*self) * tol } #[inline] fn debug_r2nd_tol(&self, other: &Self, tol: &Self::Tol) -> Self::DebugTol { $float::abs(*other) * tol } #[inline] fn debug_ulps_tol( &self, _other: &Self, tol: &UlpsTol, ) -> UlpsTol { *tol } } impl AssertFloatEqAll for $float { type AllDebugTol = Self::AllTol; #[inline] fn debug_abs_all_tol(&self, other: &Self, tol: &Self::AllTol) -> Self::AllDebugTol { self.debug_abs_tol(other, tol) } #[inline] fn debug_rmax_all_tol(&self, other: &Self, tol: &Self::AllTol) -> Self::AllDebugTol { self.debug_rmax_tol(other, tol) } #[inline] fn debug_rmin_all_tol(&self, other: &Self, tol: &Self::AllTol) -> Self::AllDebugTol { self.debug_rmin_tol(other, tol) } #[inline] fn debug_r1st_all_tol(&self, other: &Self, tol: &Self::AllTol) -> Self::AllDebugTol { self.debug_r1st_tol(other, tol) } #[inline] fn debug_r2nd_all_tol(&self, other: &Self, tol: &Self::AllTol) -> Self::AllDebugTol { self.debug_r2nd_tol(other, tol) } #[inline] fn debug_ulps_all_tol( &self, other: &Self, tol: &UlpsTol, ) -> UlpsTol { self.debug_ulps_tol(other, tol) } } }; } impl_traits!(f32, u32); impl_traits!(f64, u64); float_eq-1.0.1/src/trait_impls/std_types.rs000064400000000000000000001540010072674642500171500ustar 00000000000000use crate::{ AssertFloatEq, AssertFloatEqAll, DebugUlpsDiff, FloatEq, FloatEqAll, FloatEqDebugUlpsDiff, FloatEqUlpsTol, UlpsTol, }; use std::boxed::Box; use std::collections::{BTreeMap, HashMap, LinkedList, VecDeque}; use std::fmt; use std::hash::{BuildHasher, Hash}; use std::rc::Rc; use std::sync::Arc; //------------------------------------------------------------------------------ // Simple wrapper types //------------------------------------------------------------------------------ macro_rules! impl_traits_for_wrapper { ($t:ident) => { impl FloatEqUlpsTol for $t { type UlpsTol = $t>; } impl FloatEq<$t> for $t where A: FloatEq, { type Tol = A::Tol; #[inline] fn eq_abs(&self, other: &$t, tol: &Self::Tol) -> bool { FloatEq::eq_abs(&**self, &**other, tol) } #[inline] fn eq_rmax(&self, other: &$t, tol: &Self::Tol) -> bool { FloatEq::eq_rmax(&**self, &**other, tol) } #[inline] fn eq_rmin(&self, other: &$t, tol: &Self::Tol) -> bool { FloatEq::eq_rmin(&**self, &**other, tol) } #[inline] fn eq_r1st(&self, other: &$t, tol: &Self::Tol) -> bool { FloatEq::eq_r1st(&**self, &**other, tol) } #[inline] fn eq_r2nd(&self, other: &$t, tol: &Self::Tol) -> bool { FloatEq::eq_r2nd(&**self, &**other, tol) } #[inline] fn eq_ulps(&self, other: &$t, tol: &UlpsTol) -> bool { FloatEq::eq_ulps(&**self, &**other, tol) } } impl FloatEqAll<$t> for $t where A: FloatEqAll, { type AllTol = A::AllTol; #[inline] fn eq_abs_all(&self, other: &$t, tol: &Self::AllTol) -> bool { FloatEqAll::eq_abs_all(&**self, &**other, tol) } #[inline] fn eq_rmax_all(&self, other: &$t, tol: &Self::AllTol) -> bool { FloatEqAll::eq_rmax_all(&**self, &**other, tol) } #[inline] fn eq_rmin_all(&self, other: &$t, tol: &Self::AllTol) -> bool { FloatEqAll::eq_rmin_all(&**self, &**other, tol) } #[inline] fn eq_r1st_all(&self, other: &$t, tol: &Self::AllTol) -> bool { FloatEqAll::eq_r1st_all(&**self, &**other, tol) } #[inline] fn eq_r2nd_all(&self, other: &$t, tol: &Self::AllTol) -> bool { FloatEqAll::eq_r2nd_all(&**self, &**other, tol) } #[inline] fn eq_ulps_all(&self, other: &$t, tol: &UlpsTol) -> bool { FloatEqAll::eq_ulps_all(&**self, &**other, tol) } } impl AssertFloatEq<$t> for $t where A: AssertFloatEq + Copy, B: Copy, { type DebugAbsDiff = A::DebugAbsDiff; type DebugTol = A::DebugTol; #[inline] fn debug_abs_diff(&self, other: &$t) -> Self::DebugAbsDiff { AssertFloatEq::debug_abs_diff(&**self, &**other) } #[inline] fn debug_ulps_diff(&self, other: &$t) -> DebugUlpsDiff { AssertFloatEq::debug_ulps_diff(&**self, &**other) } #[inline] fn debug_abs_tol(&self, other: &$t, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_abs_tol(&**self, &**other, tol) } #[inline] fn debug_rmax_tol(&self, other: &$t, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_rmax_tol(&**self, &**other, tol) } #[inline] fn debug_rmin_tol(&self, other: &$t, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_rmin_tol(&**self, &**other, tol) } #[inline] fn debug_r1st_tol(&self, other: &$t, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_r1st_tol(&**self, &**other, tol) } #[inline] fn debug_r2nd_tol(&self, other: &$t, tol: &Self::Tol) -> Self::DebugTol { AssertFloatEq::debug_r2nd_tol(&**self, &**other, tol) } #[inline] fn debug_ulps_tol( &self, other: &$t, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized, { AssertFloatEq::debug_ulps_tol(&**self, &**other, tol) } } impl AssertFloatEqAll<$t> for $t where A: AssertFloatEqAll + Copy, B: Copy, { type AllDebugTol = A::AllDebugTol; #[inline] fn debug_abs_all_tol(&self, other: &$t, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_abs_all_tol(&**self, &**other, tol) } #[inline] fn debug_rmax_all_tol(&self, other: &$t, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_rmax_all_tol(&**self, &**other, tol) } #[inline] fn debug_rmin_all_tol(&self, other: &$t, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_rmin_all_tol(&**self, &**other, tol) } #[inline] fn debug_r1st_all_tol(&self, other: &$t, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_r1st_all_tol(&**self, &**other, tol) } #[inline] fn debug_r2nd_all_tol(&self, other: &$t, tol: &Self::AllTol) -> Self::AllDebugTol { AssertFloatEqAll::debug_r2nd_all_tol(&**self, &**other, tol) } #[inline] fn debug_ulps_all_tol( &self, other: &$t, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized, { AssertFloatEqAll::debug_ulps_all_tol(&**self, &**other, tol) } } }; } impl_traits_for_wrapper!(Arc); impl_traits_for_wrapper!(Box); impl_traits_for_wrapper!(Rc); //------------------------------------------------------------------------------ // Slices //------------------------------------------------------------------------------ impl AssertFloatEq<[B]> for [A] where A: AssertFloatEq, A::Tol: Sized, A::DebugTol: Sized, UlpsTol: Sized, UlpsTol: Sized, { type DebugAbsDiff = Option>; type DebugTol = Option>; #[inline] fn debug_abs_diff(&self, other: &[B]) -> Self::DebugAbsDiff { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| a.debug_abs_diff(b)) .collect(), ) } else { None } } #[inline] fn debug_ulps_diff(&self, other: &[B]) -> DebugUlpsDiff { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| a.debug_ulps_diff(b)) .collect(), ) } else { None } } #[inline] fn debug_abs_tol(&self, other: &[B], tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { Some( self.iter() .zip(other.iter()) .zip(tol) .map(|((a, b), eps)| AssertFloatEq::debug_abs_tol(a, b, eps)) .collect(), ) } else { None } } #[inline] fn debug_rmax_tol(&self, other: &[B], tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { Some( self.iter() .zip(other.iter()) .zip(tol) .map(|((a, b), eps)| AssertFloatEq::debug_rmax_tol(a, b, eps)) .collect(), ) } else { None } } #[inline] fn debug_rmin_tol(&self, other: &[B], tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { Some( self.iter() .zip(other.iter()) .zip(tol) .map(|((a, b), eps)| AssertFloatEq::debug_rmin_tol(a, b, eps)) .collect(), ) } else { None } } #[inline] fn debug_r1st_tol(&self, other: &[B], tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { Some( self.iter() .zip(other.iter()) .zip(tol) .map(|((a, b), eps)| AssertFloatEq::debug_r1st_tol(a, b, eps)) .collect(), ) } else { None } } #[inline] fn debug_r2nd_tol(&self, other: &[B], tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { Some( self.iter() .zip(other.iter()) .zip(tol) .map(|((a, b), eps)| AssertFloatEq::debug_r2nd_tol(a, b, eps)) .collect(), ) } else { None } } #[inline] fn debug_ulps_tol(&self, other: &[B], tol: &UlpsTol) -> UlpsTol { if self.len() == other.len() && self.len() == tol.len() { Some( self.iter() .zip(other.iter()) .zip(tol) .map(|((a, b), eps)| AssertFloatEq::debug_ulps_tol(a, b, eps)) .collect(), ) } else { None } } } impl AssertFloatEqAll<[B]> for [A] where A: AssertFloatEqAll, A::AllDebugTol: Sized, UlpsTol: Sized, { type AllDebugTol = Option>; #[inline] fn debug_abs_all_tol(&self, other: &[B], tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| a.debug_abs_all_tol(b, tol)) .collect(), ) } else { None } } #[inline] fn debug_rmax_all_tol(&self, other: &[B], tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| a.debug_rmax_all_tol(b, tol)) .collect(), ) } else { None } } #[inline] fn debug_rmin_all_tol(&self, other: &[B], tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| a.debug_rmin_all_tol(b, tol)) .collect(), ) } else { None } } #[inline] fn debug_r1st_all_tol(&self, other: &[B], tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| a.debug_r1st_all_tol(b, tol)) .collect(), ) } else { None } } #[inline] fn debug_r2nd_all_tol(&self, other: &[B], tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| a.debug_r2nd_all_tol(b, tol)) .collect(), ) } else { None } } #[inline] fn debug_ulps_all_tol( &self, other: &[B], tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized, { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| a.debug_ulps_all_tol(b, tol)) .collect(), ) } else { None } } } //------------------------------------------------------------------------------ // Linear collections //------------------------------------------------------------------------------ macro_rules! impl_traits_for_linear_collection { ($t:ident) => { impl FloatEqUlpsTol for $t where UlpsTol: Sized, { type UlpsTol = $t>; } impl FloatEqDebugUlpsDiff for $t { type DebugUlpsDiff = $t>; } impl FloatEq<$t> for $t where A: FloatEq, A::Tol: Sized, UlpsTol: Sized, { type Tol = $t; #[inline] fn eq_abs(&self, other: &$t, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self .iter() .zip(other.iter()) .zip(tol) .all(|((a, b), eps)| FloatEq::eq_abs(a, b, eps)) } #[inline] fn eq_rmax(&self, other: &$t, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self .iter() .zip(other.iter()) .zip(tol) .all(|((a, b), eps)| FloatEq::eq_rmax(a, b, eps)) } #[inline] fn eq_rmin(&self, other: &$t, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self .iter() .zip(other.iter()) .zip(tol) .all(|((a, b), eps)| FloatEq::eq_rmin(a, b, eps)) } #[inline] fn eq_r1st(&self, other: &$t, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self .iter() .zip(other.iter()) .zip(tol) .all(|((a, b), eps)| FloatEq::eq_r1st(a, b, eps)) } #[inline] fn eq_r2nd(&self, other: &$t, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self .iter() .zip(other.iter()) .zip(tol) .all(|((a, b), eps)| FloatEq::eq_r2nd(a, b, eps)) } #[inline] fn eq_ulps(&self, other: &$t, tol: &UlpsTol) -> bool { self.len() == other.len() && self.len() == tol.len() && self .iter() .zip(other.iter()) .zip(tol) .all(|((a, b), eps)| FloatEq::eq_ulps(a, b, eps)) } } impl FloatEqAll<$t> for $t where A: FloatEqAll, { type AllTol = A::AllTol; #[inline] fn eq_abs_all(&self, other: &$t, tol: &Self::AllTol) -> bool { self.len() == other.len() && self .iter() .zip(other.iter()) .all(|(a, b)| FloatEqAll::eq_abs_all(a, b, tol)) } #[inline] fn eq_rmax_all(&self, other: &$t, tol: &Self::AllTol) -> bool { self.len() == other.len() && self .iter() .zip(other.iter()) .all(|(a, b)| FloatEqAll::eq_rmax_all(a, b, tol)) } #[inline] fn eq_rmin_all(&self, other: &$t, tol: &Self::AllTol) -> bool { self.len() == other.len() && self .iter() .zip(other.iter()) .all(|(a, b)| FloatEqAll::eq_rmin_all(a, b, tol)) } #[inline] fn eq_r1st_all(&self, other: &$t, tol: &Self::AllTol) -> bool { self.len() == other.len() && self .iter() .zip(other.iter()) .all(|(a, b)| FloatEqAll::eq_r1st_all(a, b, tol)) } #[inline] fn eq_r2nd_all(&self, other: &$t, tol: &Self::AllTol) -> bool { self.len() == other.len() && self .iter() .zip(other.iter()) .all(|(a, b)| FloatEqAll::eq_r2nd_all(a, b, tol)) } #[inline] fn eq_ulps_all(&self, other: &$t, tol: &UlpsTol) -> bool { self.len() == other.len() && self .iter() .zip(other.iter()) .all(|(a, b)| FloatEqAll::eq_ulps_all(a, b, tol)) } } impl AssertFloatEq<$t> for $t where A: AssertFloatEq + Copy, B: Copy, A::Tol: Sized, A::DebugTol: Sized, UlpsTol: Sized, UlpsTol: Sized, { type DebugAbsDiff = Option<$t>; type DebugTol = Option<$t>; #[inline] fn debug_abs_diff(&self, other: &$t) -> Self::DebugAbsDiff { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| AssertFloatEq::debug_abs_diff(a, b)) .collect(), ) } else { None } } #[inline] fn debug_ulps_diff(&self, other: &$t) -> DebugUlpsDiff { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| AssertFloatEq::debug_ulps_diff(a, b)) .collect(), ) } else { None } } #[inline] fn debug_abs_tol(&self, other: &$t, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { Some( self.iter() .zip(other.iter()) .zip(tol) .map(|((a, b), eps)| AssertFloatEq::debug_abs_tol(a, b, eps)) .collect(), ) } else { None } } #[inline] fn debug_rmax_tol(&self, other: &$t, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { Some( self.iter() .zip(other.iter()) .zip(tol) .map(|((a, b), eps)| AssertFloatEq::debug_rmax_tol(a, b, eps)) .collect(), ) } else { None } } #[inline] fn debug_rmin_tol(&self, other: &$t, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { Some( self.iter() .zip(other.iter()) .zip(tol) .map(|((a, b), eps)| AssertFloatEq::debug_rmin_tol(a, b, eps)) .collect(), ) } else { None } } #[inline] fn debug_r1st_tol(&self, other: &$t, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { Some( self.iter() .zip(other.iter()) .zip(tol) .map(|((a, b), eps)| AssertFloatEq::debug_r1st_tol(a, b, eps)) .collect(), ) } else { None } } #[inline] fn debug_r2nd_tol(&self, other: &$t, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { Some( self.iter() .zip(other.iter()) .zip(tol) .map(|((a, b), eps)| AssertFloatEq::debug_r2nd_tol(a, b, eps)) .collect(), ) } else { None } } #[inline] fn debug_ulps_tol( &self, other: &$t, tol: &UlpsTol, ) -> UlpsTol { if self.len() == other.len() && self.len() == tol.len() { Some( self.iter() .zip(other.iter()) .zip(tol) .map(|((a, b), eps)| AssertFloatEq::debug_ulps_tol(a, b, eps)) .collect(), ) } else { None } } } impl AssertFloatEqAll<$t> for $t where A: AssertFloatEqAll + Copy, B: Copy, A::AllDebugTol: Sized, UlpsTol: Sized, { type AllDebugTol = Option<$t>; #[inline] fn debug_abs_all_tol(&self, other: &$t, tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| AssertFloatEqAll::debug_abs_all_tol(a, b, tol)) .collect(), ) } else { None } } #[inline] fn debug_rmax_all_tol(&self, other: &$t, tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| AssertFloatEqAll::debug_rmax_all_tol(a, b, tol)) .collect(), ) } else { None } } #[inline] fn debug_rmin_all_tol(&self, other: &$t, tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| AssertFloatEqAll::debug_rmin_all_tol(a, b, tol)) .collect(), ) } else { None } } #[inline] fn debug_r1st_all_tol(&self, other: &$t, tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| AssertFloatEqAll::debug_r1st_all_tol(a, b, tol)) .collect(), ) } else { None } } #[inline] fn debug_r2nd_all_tol(&self, other: &$t, tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| AssertFloatEqAll::debug_r2nd_all_tol(a, b, tol)) .collect(), ) } else { None } } #[inline] fn debug_ulps_all_tol( &self, other: &$t, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized, { if self.len() == other.len() { Some( self.iter() .zip(other.iter()) .map(|(a, b)| AssertFloatEqAll::debug_ulps_all_tol(a, b, tol)) .collect(), ) } else { None } } } }; } impl_traits_for_linear_collection!(Vec); impl_traits_for_linear_collection!(VecDeque); impl_traits_for_linear_collection!(LinkedList); //------------------------------------------------------------------------------ // HashMap //------------------------------------------------------------------------------ impl FloatEqUlpsTol for HashMap where V: FloatEqUlpsTol, UlpsTol: Sized, { type UlpsTol = HashMap, S>; } impl FloatEqDebugUlpsDiff for HashMap where V: FloatEqDebugUlpsDiff, { type DebugUlpsDiff = HashMap, S>; } impl FloatEq> for HashMap where K: Eq + Hash, S: BuildHasher, VA: FloatEq, VA::Tol: Sized, UlpsTol: Sized, { type Tol = HashMap; #[inline] fn eq_abs(&self, other: &HashMap, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { if let Some(eps) = tol.get(k) { FloatEq::eq_abs(a, b, eps) } else { false } } else { false } }) } #[inline] fn eq_rmax(&self, other: &HashMap, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { if let Some(eps) = tol.get(k) { FloatEq::eq_rmax(a, b, eps) } else { false } } else { false } }) } #[inline] fn eq_rmin(&self, other: &HashMap, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { if let Some(eps) = tol.get(k) { FloatEq::eq_rmin(a, b, eps) } else { false } } else { false } }) } #[inline] fn eq_r1st(&self, other: &HashMap, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { if let Some(eps) = tol.get(k) { FloatEq::eq_r1st(a, b, eps) } else { false } } else { false } }) } #[inline] fn eq_r2nd(&self, other: &HashMap, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { if let Some(eps) = tol.get(k) { FloatEq::eq_r2nd(a, b, eps) } else { false } } else { false } }) } #[inline] fn eq_ulps(&self, other: &HashMap, tol: &UlpsTol) -> bool { self.len() == other.len() && self.len() == tol.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { if let Some(eps) = tol.get(k) { FloatEq::eq_ulps(a, b, eps) } else { false } } else { false } }) } } impl FloatEqAll> for HashMap where K: Eq + Hash, S: BuildHasher, VA: FloatEqAll, { type AllTol = VA::AllTol; #[inline] fn eq_abs_all(&self, other: &HashMap, tol: &Self::AllTol) -> bool { self.len() == other.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { FloatEqAll::eq_abs_all(a, b, tol) } else { false } }) } #[inline] fn eq_rmax_all(&self, other: &HashMap, tol: &Self::AllTol) -> bool { self.len() == other.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { FloatEqAll::eq_rmax_all(a, b, tol) } else { false } }) } #[inline] fn eq_rmin_all(&self, other: &HashMap, tol: &Self::AllTol) -> bool { self.len() == other.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { FloatEqAll::eq_rmin_all(a, b, tol) } else { false } }) } #[inline] fn eq_r1st_all(&self, other: &HashMap, tol: &Self::AllTol) -> bool { self.len() == other.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { FloatEqAll::eq_r1st_all(a, b, tol) } else { false } }) } #[inline] fn eq_r2nd_all(&self, other: &HashMap, tol: &Self::AllTol) -> bool { self.len() == other.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { FloatEqAll::eq_r2nd_all(a, b, tol) } else { false } }) } #[inline] fn eq_ulps_all(&self, other: &HashMap, tol: &UlpsTol) -> bool { self.len() == other.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { FloatEqAll::eq_ulps_all(a, b, tol) } else { false } }) } } impl AssertFloatEq> for HashMap where K: Eq + Hash + Clone + fmt::Debug, S: BuildHasher + Clone, VA: AssertFloatEq, VA::Tol: Sized, UlpsTol: Sized, VA::DebugTol: Sized, UlpsTol: Sized, { type DebugAbsDiff = Option>; type DebugTol = Option>; #[inline] fn debug_abs_diff(&self, other: &HashMap) -> Self::DebugAbsDiff { if self.len() == other.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_abs_diff(other.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_ulps_diff(&self, other: &HashMap) -> DebugUlpsDiff { if self.len() == other.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_ulps_diff(other.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_abs_tol(&self, other: &HashMap, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_abs_tol(other.get(k)?, tol.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_rmax_tol(&self, other: &HashMap, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_rmax_tol(other.get(k)?, tol.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_rmin_tol(&self, other: &HashMap, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_rmin_tol(other.get(k)?, tol.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_r1st_tol(&self, other: &HashMap, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_r1st_tol(other.get(k)?, tol.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_r2nd_tol(&self, other: &HashMap, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_r2nd_tol(other.get(k)?, tol.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_ulps_tol( &self, other: &HashMap, tol: &UlpsTol, ) -> UlpsTol { if self.len() == other.len() && self.len() == tol.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_ulps_tol(other.get(k)?, tol.get(k)?)); } Some(result) } else { None } } } impl AssertFloatEqAll> for HashMap where K: Eq + Hash + Clone + fmt::Debug, S: BuildHasher + Clone, VA: AssertFloatEqAll, VA::AllDebugTol: Sized, UlpsTol: Sized, { type AllDebugTol = Option>; #[inline] fn debug_abs_all_tol( &self, other: &HashMap, tol: &Self::AllTol, ) -> Self::AllDebugTol { if self.len() == other.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_abs_all_tol(other.get(k)?, tol)); } Some(result) } else { None } } #[inline] fn debug_rmax_all_tol( &self, other: &HashMap, tol: &Self::AllTol, ) -> Self::AllDebugTol { if self.len() == other.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_rmax_all_tol(other.get(k)?, tol)); } Some(result) } else { None } } #[inline] fn debug_rmin_all_tol( &self, other: &HashMap, tol: &Self::AllTol, ) -> Self::AllDebugTol { if self.len() == other.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_rmin_all_tol(other.get(k)?, tol)); } Some(result) } else { None } } #[inline] fn debug_r1st_all_tol( &self, other: &HashMap, tol: &Self::AllTol, ) -> Self::AllDebugTol { if self.len() == other.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_r1st_all_tol(other.get(k)?, tol)); } Some(result) } else { None } } #[inline] fn debug_r2nd_all_tol( &self, other: &HashMap, tol: &Self::AllTol, ) -> Self::AllDebugTol { if self.len() == other.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_r2nd_all_tol(other.get(k)?, tol)); } Some(result) } else { None } } #[inline] fn debug_ulps_all_tol( &self, other: &HashMap, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized, { if self.len() == other.len() { let mut result = HashMap::with_hasher(self.hasher().clone()); for (k, v) in self { result.insert(k.clone(), v.debug_ulps_all_tol(other.get(k)?, tol)); } Some(result) } else { None } } } //------------------------------------------------------------------------------ // BTreeMap //------------------------------------------------------------------------------ impl FloatEqUlpsTol for BTreeMap where V: FloatEqUlpsTol, UlpsTol: Sized, { type UlpsTol = BTreeMap>; } impl FloatEqDebugUlpsDiff for BTreeMap where V: FloatEqDebugUlpsDiff, { type DebugUlpsDiff = BTreeMap>; } impl FloatEq> for BTreeMap where K: Eq + Ord, VA: FloatEq, VA::Tol: Sized, UlpsTol: Sized, { type Tol = BTreeMap; #[inline] fn eq_abs(&self, other: &BTreeMap, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { if let Some(eps) = tol.get(k) { FloatEq::eq_abs(a, b, eps) } else { false } } else { false } }) } #[inline] fn eq_rmax(&self, other: &BTreeMap, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { if let Some(eps) = tol.get(k) { FloatEq::eq_rmax(a, b, eps) } else { false } } else { false } }) } #[inline] fn eq_rmin(&self, other: &BTreeMap, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { if let Some(eps) = tol.get(k) { FloatEq::eq_rmin(a, b, eps) } else { false } } else { false } }) } #[inline] fn eq_r1st(&self, other: &BTreeMap, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { if let Some(eps) = tol.get(k) { FloatEq::eq_r1st(a, b, eps) } else { false } } else { false } }) } #[inline] fn eq_r2nd(&self, other: &BTreeMap, tol: &Self::Tol) -> bool { self.len() == other.len() && self.len() == tol.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { if let Some(eps) = tol.get(k) { FloatEq::eq_r2nd(a, b, eps) } else { false } } else { false } }) } #[inline] fn eq_ulps(&self, other: &BTreeMap, tol: &UlpsTol) -> bool { self.len() == other.len() && self.len() == tol.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { if let Some(eps) = tol.get(k) { FloatEq::eq_ulps(a, b, eps) } else { false } } else { false } }) } } impl FloatEqAll> for BTreeMap where K: Eq + Ord, VA: FloatEqAll, { type AllTol = VA::AllTol; #[inline] fn eq_abs_all(&self, other: &BTreeMap, tol: &Self::AllTol) -> bool { self.len() == other.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { FloatEqAll::eq_abs_all(a, b, tol) } else { false } }) } #[inline] fn eq_rmax_all(&self, other: &BTreeMap, tol: &Self::AllTol) -> bool { self.len() == other.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { FloatEqAll::eq_rmax_all(a, b, tol) } else { false } }) } #[inline] fn eq_rmin_all(&self, other: &BTreeMap, tol: &Self::AllTol) -> bool { self.len() == other.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { FloatEqAll::eq_rmin_all(a, b, tol) } else { false } }) } #[inline] fn eq_r1st_all(&self, other: &BTreeMap, tol: &Self::AllTol) -> bool { self.len() == other.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { FloatEqAll::eq_r1st_all(a, b, tol) } else { false } }) } #[inline] fn eq_r2nd_all(&self, other: &BTreeMap, tol: &Self::AllTol) -> bool { self.len() == other.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { FloatEqAll::eq_r2nd_all(a, b, tol) } else { false } }) } #[inline] fn eq_ulps_all(&self, other: &BTreeMap, tol: &UlpsTol) -> bool { self.len() == other.len() && self.iter().all(|(k, a)| { if let Some(b) = other.get(k) { FloatEqAll::eq_ulps_all(a, b, tol) } else { false } }) } } impl AssertFloatEq> for BTreeMap where K: Eq + Ord + Clone + fmt::Debug, VA: AssertFloatEq, VA::Tol: Sized, VA::DebugTol: Sized, UlpsTol: Sized, UlpsTol: Sized, { type DebugAbsDiff = Option>; type DebugTol = Option>; #[inline] fn debug_abs_diff(&self, other: &BTreeMap) -> Self::DebugAbsDiff { if self.len() == other.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_abs_diff(other.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_ulps_diff(&self, other: &BTreeMap) -> DebugUlpsDiff { if self.len() == other.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_ulps_diff(other.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_abs_tol(&self, other: &BTreeMap, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_abs_tol(other.get(k)?, tol.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_rmax_tol(&self, other: &BTreeMap, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_rmax_tol(other.get(k)?, tol.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_rmin_tol(&self, other: &BTreeMap, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_rmin_tol(other.get(k)?, tol.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_r1st_tol(&self, other: &BTreeMap, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_r1st_tol(other.get(k)?, tol.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_r2nd_tol(&self, other: &BTreeMap, tol: &Self::Tol) -> Self::DebugTol { if self.len() == other.len() && self.len() == tol.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_r2nd_tol(other.get(k)?, tol.get(k)?)); } Some(result) } else { None } } #[inline] fn debug_ulps_tol( &self, other: &BTreeMap, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized, { if self.len() == other.len() && self.len() == tol.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_ulps_tol(other.get(k)?, tol.get(k)?)); } Some(result) } else { None } } } impl AssertFloatEqAll> for BTreeMap where K: Eq + Ord + Clone + fmt::Debug, VA: AssertFloatEqAll, VA::AllDebugTol: Sized, UlpsTol: Sized, { type AllDebugTol = Option>; #[inline] fn debug_abs_all_tol(&self, other: &BTreeMap, tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_abs_all_tol(other.get(k)?, tol)); } Some(result) } else { None } } #[inline] fn debug_rmax_all_tol(&self, other: &BTreeMap, tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_rmax_all_tol(other.get(k)?, tol)); } Some(result) } else { None } } #[inline] fn debug_rmin_all_tol(&self, other: &BTreeMap, tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_rmin_all_tol(other.get(k)?, tol)); } Some(result) } else { None } } #[inline] fn debug_r1st_all_tol(&self, other: &BTreeMap, tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_r1st_all_tol(other.get(k)?, tol)); } Some(result) } else { None } } #[inline] fn debug_r2nd_all_tol(&self, other: &BTreeMap, tol: &Self::AllTol) -> Self::AllDebugTol { if self.len() == other.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_r2nd_all_tol(other.get(k)?, tol)); } Some(result) } else { None } } #[inline] fn debug_ulps_all_tol( &self, other: &BTreeMap, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized, { if self.len() == other.len() { let mut result = BTreeMap::new(); for (k, v) in self { result.insert(k.clone(), v.debug_ulps_all_tol(other.get(k)?, tol)); } Some(result) } else { None } } } float_eq-1.0.1/src/trait_impls/tuples.rs000064400000000000000000000173630072674642500164570ustar 00000000000000use crate::{AssertFloatEq, DebugUlpsDiff, FloatEq, FloatEqDebugUlpsDiff, FloatEqUlpsTol, UlpsTol}; use core::fmt; impl FloatEqUlpsTol for () { type UlpsTol = (); } impl FloatEqDebugUlpsDiff for () { type DebugUlpsDiff = (); } impl FloatEq for () { type Tol = (); #[inline] fn eq_abs(&self, _other: &(), _tol: &Self::Tol) -> bool { true } #[inline] fn eq_rmax(&self, _other: &(), _tol: &Self::Tol) -> bool { true } #[inline] fn eq_rmin(&self, _other: &(), _tol: &Self::Tol) -> bool { true } #[inline] fn eq_r1st(&self, _other: &(), _tol: &Self::Tol) -> bool { true } #[inline] fn eq_r2nd(&self, _other: &(), _tol: &Self::Tol) -> bool { true } #[inline] fn eq_ulps(&self, _other: &(), _tol: &UlpsTol) -> bool { true } } impl AssertFloatEq for () { type DebugAbsDiff = (); type DebugTol = (); #[inline] fn debug_abs_diff(&self, _other: &()) -> Self::DebugAbsDiff {} #[inline] fn debug_ulps_diff(&self, _other: &()) -> DebugUlpsDiff {} #[inline] fn debug_abs_tol(&self, _other: &(), _tol: &Self::Tol) -> Self::DebugTol {} #[inline] fn debug_rmax_tol(&self, _other: &(), _tol: &Self::Tol) -> Self::DebugTol {} #[inline] fn debug_rmin_tol(&self, _other: &(), _tol: &Self::Tol) -> Self::DebugTol {} #[inline] fn debug_r1st_tol(&self, _other: &(), _tol: &Self::Tol) -> Self::DebugTol {} #[inline] fn debug_r2nd_tol(&self, _other: &(), _tol: &Self::Tol) -> Self::DebugTol {} #[inline] fn debug_ulps_tol(&self, _other: &(), _tol: &UlpsTol) -> UlpsTol {} } // Non-unit type tuple impls, as for std PartialEq implementation macro_rules! tuple_impls { ($( $Tuple:ident { $(($idx:tt) -> $T:ident)+ } )+) => { $( impl<$($T:FloatEqUlpsTol),+> FloatEqUlpsTol for ($($T,)+) where last_type!($($T,)+): ?Sized, $(UlpsTol<$T>: Sized,)+ { type UlpsTol = ($(UlpsTol<$T>,)+); } impl<$($T:FloatEqDebugUlpsDiff),+> FloatEqDebugUlpsDiff for ($($T,)+) { type DebugUlpsDiff = ($(DebugUlpsDiff<$T>,)+); } impl<$($T:FloatEq),+> FloatEq for ($($T,)+) where last_type!($($T,)+): ?Sized, $($T::Tol: Sized,)+ $(UlpsTol<$T::Tol>: Sized,)+ { type Tol = ($($T::Tol,)+); #[inline] fn eq_abs(&self, other: &Self, tol: &Self::Tol) -> bool { $(self.$idx.eq_abs(&other.$idx, &tol.$idx))&&+ } #[inline] fn eq_rmax(&self, other: &Self, tol: &Self::Tol) -> bool { $(self.$idx.eq_rmax(&other.$idx, &tol.$idx))&&+ } #[inline] fn eq_rmin(&self, other: &Self, tol: &Self::Tol) -> bool { $(self.$idx.eq_rmin(&other.$idx, &tol.$idx))&&+ } #[inline] fn eq_r1st(&self, other: &Self, tol: &Self::Tol) -> bool { $(self.$idx.eq_r1st(&other.$idx, &tol.$idx))&&+ } #[inline] fn eq_r2nd(&self, other: &Self, tol: &Self::Tol) -> bool { $(self.$idx.eq_r2nd(&other.$idx, &tol.$idx))&&+ } #[inline] fn eq_ulps(&self, other: &Self, tol: &UlpsTol) -> bool { $(self.$idx.eq_ulps(&other.$idx, &tol.$idx))&&+ } } impl<$($T:AssertFloatEq + fmt::Debug),+> AssertFloatEq for ($($T,)+) where last_type!($($T,)+): ?Sized, $($T::Tol: Sized,)+ $($T::DebugTol: Sized,)+ $(UlpsTol<$T::Tol>: Sized,)+ $(UlpsTol<$T::DebugTol>: Sized,)+ { type DebugAbsDiff = ($($T::DebugAbsDiff,)+); type DebugTol = ($($T::DebugTol,)+); #[inline] fn debug_abs_diff(&self, other: &Self) -> Self::DebugAbsDiff { ($(self.$idx.debug_abs_diff(&other.$idx),)+) } #[inline] fn debug_ulps_diff(&self, other: &Self) -> DebugUlpsDiff { ($(self.$idx.debug_ulps_diff(&other.$idx),)+) } #[inline] fn debug_abs_tol(&self, other: &Self, tol: &Self::Tol) -> Self::DebugTol { ($(self.$idx.debug_abs_tol(&other.$idx, &tol.$idx),)+) } #[inline] fn debug_rmax_tol(&self, other: &Self, tol: &Self::Tol) -> Self::DebugTol { ($(self.$idx.debug_rmax_tol(&other.$idx, &tol.$idx),)+) } #[inline] fn debug_rmin_tol(&self, other: &Self, tol: &Self::Tol) -> Self::DebugTol { ($(self.$idx.debug_rmin_tol(&other.$idx, &tol.$idx),)+) } #[inline] fn debug_r1st_tol(&self, other: &Self, tol: &Self::Tol) -> Self::DebugTol { ($(self.$idx.debug_r1st_tol(&other.$idx, &tol.$idx),)+) } #[inline] fn debug_r2nd_tol(&self, other: &Self, tol: &Self::Tol) -> Self::DebugTol { ($(self.$idx.debug_r2nd_tol(&other.$idx, &tol.$idx),)+) } #[inline] fn debug_ulps_tol(&self, other: &Self, tol: &UlpsTol) -> UlpsTol { ($(self.$idx.debug_ulps_tol(&other.$idx, &tol.$idx),)+) } } )+ }; } macro_rules! last_type { ($a:ident,) => { $a }; ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) }; } tuple_impls! { Tuple1 { (0) -> A } Tuple2 { (0) -> A (1) -> B } Tuple3 { (0) -> A (1) -> B (2) -> C } Tuple4 { (0) -> A (1) -> B (2) -> C (3) -> D } Tuple5 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E } Tuple6 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F } Tuple7 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F (6) -> G } Tuple8 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F (6) -> G (7) -> H } Tuple9 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F (6) -> G (7) -> H (8) -> I } Tuple10 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F (6) -> G (7) -> H (8) -> I (9) -> J } Tuple11 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F (6) -> G (7) -> H (8) -> I (9) -> J (10) -> K } Tuple12 { (0) -> A (1) -> B (2) -> C (3) -> D (4) -> E (5) -> F (6) -> G (7) -> H (8) -> I (9) -> J (10) -> K (11) -> L } } float_eq-1.0.1/src/trait_impls.rs000064400000000000000000000003140072674642500151270ustar 00000000000000mod arrays; mod core_types; mod primitives; mod tuples; #[cfg(feature = "std")] mod std_types; #[cfg(feature = "num")] mod num_complex; #[cfg(feature = "num")] pub use self::num_complex::*; float_eq-1.0.1/src/traits.rs000064400000000000000000000733670072674642500141300ustar 00000000000000use core::fmt; /// Per-field tolerances for [ULPs comparisons](https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison). /// /// This trait establishes a one-to-one relation between an IEEE floating point /// type and a type whose fields are expected to be structurally identical but /// specified in [ULPs]. It is used by ULPs equality checks to specify per-field /// tolerances. /// /// By convention, this type is named `FooUlps` for a given type `Foo`. /// /// The [`UlpsTol`] type alias exists to simplify usage, for example `UlpsTol` /// is `u32`. /// /// To implement this trait over a new type, see [How to compare custom types]. /// /// [How to compare custom types]: https://jtempest.github.io/float_eq-rs/book/how_to/compare_custom_types.html /// [ULPs]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison pub trait FloatEqUlpsTol { /// A structurally identical type to `Self`, with fields recursively wrapped /// by `UlpsTol`. type UlpsTol: ?Sized; } /// Per-field tolerances for [ULPs comparisons]. /// /// [ULPs comparisons]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison pub type UlpsTol = ::UlpsTol; /// Per-field results of [ULPs](https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison) /// based diff calculations. /// /// This trait establishes a one-to-one relation between an IEEE floating point /// type and a type whose fields are expected to be structurally identical but /// specified as the result of calculating a diff in [ULPs]. This is usually /// [`UlpsTol`] wrapped in an `Option`, since the ULPs diff between two floats is /// a partial function that returns `None` when the signs differ. It is used by /// testing and debugging tools to show the difference between two values on a /// per-field basis and is built for clarity, not runtime efficiency. /// /// By convention, this type is named `FooDebugUlpsDiff` for a given type `Foo`. /// /// The [`DebugUlpsDiff`] type alias exists to simplify usage, for example /// `DebugUlpsDiff` is `Option`. /// /// To implement this trait over a new type, see [How to compare custom types]. /// /// [How to compare custom types]: https://jtempest.github.io/float_eq-rs/book/how_to/compare_custom_types.html /// [ULPs]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison pub trait FloatEqDebugUlpsDiff { /// A structurally identical type to `Self`, with fields recursively wrapped /// by `DebugUlpsDiff`. type DebugUlpsDiff; } /// Per-field results of [ULPs] based diff calculations. /// /// [ULPs]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison pub type DebugUlpsDiff = ::DebugUlpsDiff; /// Compare IEEE floating point values for equality using per-field tolerances. /// /// This trait is used in the implementation of the [`float_eq!`] and [`assert_float_eq!`] /// families of macros. /// /// To implement this trait over a new type, see [How to compare custom types]. /// /// ## Examples /// /// ``` /// # use float_eq::FloatEq; /// assert!(4.0_f32.eq_abs(&4.000_001_5, &0.000_001_6)); /// assert!(4.0_f32.ne_abs(&4.000_001_5, &0.000_001_4)); /// /// assert!(4.0_f32.eq_rel(&4.000_001_5, &0.000_000_4)); /// assert!(4.0_f32.ne_rel(&4.000_001_5, &0.000_000_3)); /// /// assert!(4.0_f32.eq_ulps(&4.000_001_5, &3)); /// assert!(4.0_f32.ne_ulps(&4.000_001_5, &2)); /// ``` /// /// [How to compare custom types]: https://jtempest.github.io/float_eq-rs/book/how_to/compare_custom_types.html pub trait FloatEq { /// Type of the maximum allowed difference between two values for them to be /// considered equal. type Tol: ?Sized + FloatEqUlpsTol; /// Check whether `self` is equal to `other`, using an [absolute tolerance /// comparison]. /// /// Implementations should be the equivalent of: /// /// ``` /// # trait TestFloatEq { fn eq_abs(&self, other: &Self, tol: &Self) -> bool; } /// # impl TestFloatEq for f32 { /// # fn eq_abs(&self, other: &Self, tol: &Self) -> bool { /// // the PartialEq check covers equality of infinities /// self == other || (self - other).abs().le(tol) /// # }} /// ``` /// /// [absolute tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#absolute-tolerance-comparison fn eq_abs(&self, other: &Rhs, tol: &Self::Tol) -> bool; /// Check whether `self` is not equal to `other`, using an [absolute tolerance /// comparison]. /// /// Equal to `!self.eq_abs(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [absolute tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#absolute-tolerance-comparison #[inline] fn ne_abs(&self, other: &Rhs, tol: &Self::Tol) -> bool { !self.eq_abs(other, tol) } /// Check whether `self` is equal to `other`, using a [relative tolerance /// comparison]. /// /// Equal to `self.eq_rmax(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison #[inline] fn eq_rel(&self, other: &Rhs, tol: &Self::Tol) -> bool { self.eq_rmax(other, tol) } /// Check whether `self` is not equal to `other`, using a [relative tolerance /// comparison]. /// /// Equal to `!self.eq_rel(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison #[inline] fn ne_rel(&self, other: &Rhs, tol: &Self::Tol) -> bool { !self.eq_rel(other, tol) } /// Check whether `self` is equal to `other`, using a [relative tolerance /// comparison], scaled to the granularity of the input with the largest /// magnitude. /// /// The implementation should be the equivalent of: /// /// ``` /// # trait TestFloatEq { fn eq_rel(&self, other: &Self, tol: &Self) -> bool; } /// # impl TestFloatEq for f32 { /// # fn eq_rel(&self, other: &Self, tol: &Self) -> bool { /// // the PartialEq check covers equality of infinities /// self == other || { /// let largest = self.abs().max(other.abs()); /// let tolerance = largest * tol; /// (self - other).abs() <= tolerance /// } /// # }} /// ``` /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison fn eq_rmax(&self, other: &Rhs, tol: &Self::Tol) -> bool; /// Check whether `self` is not equal to `other`, using a [relative tolerance /// comparison]. /// /// Equal to `!self.eq_rmax(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison #[inline] fn ne_rmax(&self, other: &Rhs, tol: &Self::Tol) -> bool { !self.eq_rmax(other, tol) } /// Check whether `self` is equal to `other`, using a [relative tolerance /// comparison], scaled to the granularity of the input with the smallest /// magnitude. /// /// The implementation should be the equivalent of: /// /// ``` /// # trait TestFloatEq { fn eq_rel(&self, other: &Self, tol: &Self) -> bool; } /// # impl TestFloatEq for f32 { /// # fn eq_rel(&self, other: &Self, tol: &Self) -> bool { /// // the PartialEq check covers equality of infinities /// self == other || { /// let smallest = self.abs().min(other.abs()); /// let tolerance = smallest * tol; /// (self - other).abs() <= tolerance /// } /// # }} /// ``` /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison fn eq_rmin(&self, other: &Rhs, tol: &Self::Tol) -> bool; /// Check whether `self` is not equal to `other`, using a [relative tolerance /// comparison]. /// /// Equal to `!self.eq_rmin(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison #[inline] fn ne_rmin(&self, other: &Rhs, tol: &Self::Tol) -> bool { !self.eq_rmin(other, tol) } /// Check whether `self` is equal to `other`, using a [relative tolerance /// comparison], scaled to the granularity of the first input. /// /// The implementation should be the equivalent of: /// /// ``` /// # trait TestFloatEq { fn eq_rel(&self, other: &Self, tol: &Self) -> bool; } /// # impl TestFloatEq for f32 { /// # fn eq_rel(&self, other: &Self, tol: &Self) -> bool { /// // the PartialEq check covers equality of infinities /// self == other || { /// let tolerance = self.abs() * tol; /// (self - other).abs() <= tolerance /// } /// # }} /// ``` /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison fn eq_r1st(&self, other: &Rhs, tol: &Self::Tol) -> bool; /// Check whether `self` is not equal to `other`, using a [relative tolerance /// comparison]. /// /// Equal to `!self.eq_r1st(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison #[inline] fn ne_r1st(&self, other: &Rhs, tol: &Self::Tol) -> bool { !self.eq_r1st(other, tol) } /// Check whether `self` is equal to `other`, using a [relative tolerance /// comparison], scaled to the granularity of the second input. /// /// The implementation should be the equivalent of: /// /// ``` /// # trait TestFloatEq { fn eq_rel(&self, other: &Self, tol: &Self) -> bool; } /// # impl TestFloatEq for f32 { /// # fn eq_rel(&self, other: &Self, tol: &Self) -> bool { /// // the PartialEq check covers equality of infinities /// self == other || { /// let tolerance = other.abs() * tol; /// (self - other).abs() <= tolerance /// } /// # }} /// ``` /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison fn eq_r2nd(&self, other: &Rhs, tol: &Self::Tol) -> bool; /// Check whether `self` is not equal to `other`, using a [relative tolerance /// comparison]. /// /// Equal to `!self.eq_r2nd(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison #[inline] fn ne_r2nd(&self, other: &Rhs, tol: &Self::Tol) -> bool { !self.eq_r2nd(other, tol) } /// Check whether `self` is equal to `other`, using an [ULPs comparison](https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison). /// /// The implementation should be the equivalent of: /// /// ``` /// # trait TestFloatEq { fn eq_ulps(&self, other: &Self, tol: &u32) -> bool; } /// # impl TestFloatEq for f32 { /// # fn eq_ulps(&self, other: &Self, tol: &u32) -> bool { /// if self.is_nan() || other.is_nan() { /// false // NaNs are never equal /// } /// else if self.is_sign_positive() != other.is_sign_positive() { /// self == other // account for zero == negative zero /// } else { /// let a = self.to_bits(); /// let b = other.to_bits(); /// let max = a.max(b); /// let min = a.min(b); /// (max - min).le(tol) /// } /// # }} /// ``` /// /// [ULPs comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison fn eq_ulps(&self, other: &Rhs, tol: &UlpsTol) -> bool; /// Check whether `self` is not equal to `other`, using an [ULPs comparison]. /// /// Equal to `!self.eq_ulps(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [ULPs comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison #[inline] fn ne_ulps(&self, other: &Rhs, tol: &UlpsTol) -> bool { !self.eq_ulps(other, tol) } } /// Compare IEEE floating point values for equality using a uniform tolerance. /// /// This trait is used in the implementation of the [`float_eq!`] and [`assert_float_eq!`] /// families of macros to provide the `*_all` variants of comparison algorithms /// for homogeneous types. /// /// To implement this trait over a new type, see [How to compare custom types]. /// /// ## Examples /// /// ``` /// # use float_eq::FloatEqAll; /// let a = [1.000_000_2f32, -2.0]; /// let b = [1.0f32, -2.000_002]; /// /// assert!(a.eq_abs_all(&b, &0.000_002)); /// assert!(a.ne_abs_all(&b, &0.000_001)); /// /// assert!(a.eq_rmax_all(&b, &0.000_001)); /// assert!(a.ne_rmax_all(&b, &0.000_000_5)); /// /// assert!(a.eq_ulps_all(&b, &8)); /// assert!(a.ne_ulps_all(&b, &7)); /// ``` /// /// [How to compare custom types]: https://jtempest.github.io/float_eq-rs/book/how_to/compare_custom_types.html /// [ULPs]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison /// [`AllTol`]: trait.FloatEqAll.html#associatedtype.AllTol pub trait FloatEqAll { /// Type of the maximum allowed difference between each of two values' fields /// for them to be considered equal. type AllTol: ?Sized + FloatEqUlpsTol; /// Check whether `self` is equal to `other`, using an [absolute tolerance /// comparison]. /// /// This must use the same algorithm as [`FloatEq::eq_abs`]. /// /// [absolute tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#absolute-tolerance-comparison fn eq_abs_all(&self, other: &Rhs, tol: &Self::AllTol) -> bool; /// Check whether `self` is not equal to `other`, using an [absolute tolerance /// comparison]. /// /// Equal to `!self.eq_abs_all(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [absolute tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#absolute-tolerance-comparison #[inline] fn ne_abs_all(&self, other: &Rhs, tol: &Self::AllTol) -> bool { !self.eq_abs_all(other, tol) } /// Check whether `self` is equal to `other`, using a [relative tolerance /// comparison]. /// /// Equal to `self.eq_rmax_all(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison #[inline] fn eq_rel_all(&self, other: &Rhs, tol: &Self::AllTol) -> bool { self.eq_rmax_all(other, tol) } /// Check whether `self` is not equal to `other`, using a [relative tolerance /// comparison]. /// /// Equal to `!self.eq_rel_all(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison #[inline] fn ne_rel_all(&self, other: &Rhs, tol: &Self::AllTol) -> bool { !self.eq_rel_all(other, tol) } /// Check whether `self` is equal to `other`, using a [relative tolerance /// comparison]. /// /// This must use the same algorithm as [`FloatEq::eq_rmax`]. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison fn eq_rmax_all(&self, other: &Rhs, tol: &Self::AllTol) -> bool; /// Check whether `self` is not equal to `other`, using a [relative tolerance /// comparison]. /// /// Equal to `!self.eq_rmax_all(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison #[inline] fn ne_rmax_all(&self, other: &Rhs, tol: &Self::AllTol) -> bool { !self.eq_rmax_all(other, tol) } /// Check whether `self` is equal to `other`, using a [relative tolerance /// comparison]. /// /// This must use the same algorithm as [`FloatEq::eq_rmin`]. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison fn eq_rmin_all(&self, other: &Rhs, tol: &Self::AllTol) -> bool; /// Check whether `self` is not equal to `other`, using a [relative tolerance /// comparison]. /// /// Equal to `!self.eq_rmin_all(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison #[inline] fn ne_rmin_all(&self, other: &Rhs, tol: &Self::AllTol) -> bool { !self.eq_rmin_all(other, tol) } /// Check whether `self` is equal to `other`, using a [relative tolerance /// comparison]. /// /// This must use the same algorithm as [`FloatEq::eq_r1st`]. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison fn eq_r1st_all(&self, other: &Rhs, tol: &Self::AllTol) -> bool; /// Check whether `self` is not equal to `other`, using a [relative tolerance /// comparison]. /// /// Equal to `!self.eq_r1st_all(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison #[inline] fn ne_r1st_all(&self, other: &Rhs, tol: &Self::AllTol) -> bool { !self.eq_r1st_all(other, tol) } /// Check whether `self` is equal to `other`, using a [relative tolerance /// comparison]. /// /// This must use the same algorithm as [`FloatEq::eq_r2nd`]. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison fn eq_r2nd_all(&self, other: &Rhs, tol: &Self::AllTol) -> bool; /// Check whether `self` is not equal to `other`, using a [relative tolerance /// comparison]. /// /// Equal to `!self.eq_r2nd_all(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [relative tolerance comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#relative-tolerance-comparison #[inline] fn ne_r2nd_all(&self, other: &Rhs, tol: &Self::AllTol) -> bool { !self.eq_r2nd_all(other, tol) } /// Check whether `self` is equal to `other`, using an [ULPs comparison]. /// /// This must use the same algorithm as [`FloatEq::eq_ulps`]. /// /// [ULPs comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison fn eq_ulps_all(&self, other: &Rhs, tol: &UlpsTol) -> bool; /// Check whether `self` is not equal to `other`, using an [ULPs comparison]. /// /// Equal to `!self.eq_ulps_all(other, tol)`, there is no need to reimplement /// this for your own types. /// /// [ULPs comparison]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison #[inline] fn ne_ulps_all(&self, other: &Rhs, tol: &UlpsTol) -> bool { !self.eq_ulps_all(other, tol) } } /// Debug context for when an assert fails. /// /// This trait is used by [`assert_float_eq!`] and [`assert_float_ne!`]. /// /// To implement this trait over a new type, see [How to compare custom types]. /// /// [How to compare custom types]: https://jtempest.github.io/float_eq-rs/book/how_to/compare_custom_types.html /// [ULPs]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison pub trait AssertFloatEq: FloatEq { /// The absolute difference between two values, displayed to the user via /// `fmt::Debug` when an assert fails. /// /// This is usually the wider of `Self` and `Rhs`. type DebugAbsDiff: fmt::Debug + Sized + FloatEqDebugUlpsDiff; /// The per-field tolerance value used for comparison between two values, /// displayed to the user via `fmt::Debug` when an assert fails. /// /// This should match [`Self::Tol`]. /// /// [`Self::Tol`]: trait.FloatEq.html#associatedtype.Tol type DebugTol: fmt::Debug + FloatEqUlpsTol; /// Always positive absolute difference between two values. /// /// Implementations should be the equivalent of: /// /// ``` /// # trait TestFloatDiff { fn abs_diff(&self, other: &Self) -> Self; } /// # impl TestFloatDiff for f32 { /// # fn abs_diff(&self, other: &Self) -> Self { /// (self - other).abs() /// # }} /// ``` fn debug_abs_diff(&self, other: &Rhs) -> Self::DebugAbsDiff; /// Always positive absolute difference between two values in terms of [ULPs]. /// /// For primitive values, this should be a partial function that returns: /// - `Some(0)` if both arguments are either `0.0` or `-0.0` /// - `None` if either argument is `NaN` /// - `None` if the arguments have differing signs /// - `Some(bitwise-difference)` otherwise /// /// For composite types, this should return per-field recursively calculated /// results in order to present the most possible context to the user. /// /// Implementations over primitive types should be the equivalent of (using /// `f32` as an example): /// /// ``` /// # trait TestFloatDiff { fn ulps_diff(&self, other: &Self) -> Option; } /// # impl TestFloatDiff for f32 { /// # fn ulps_diff(&self, other: &Self) -> Option { /// if self == other { /// Some(0) /// } else if self.is_nan() || other.is_nan() { /// None /// } else if self.is_sign_positive() != other.is_sign_positive() { /// None /// } else { /// let a = self.to_bits(); /// let b = other.to_bits(); /// let max = a.max(b); /// let min = a.min(b); /// Some(max - min) /// } /// # }} /// ``` /// /// [ULPs]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison fn debug_ulps_diff(&self, other: &Rhs) -> DebugUlpsDiff; /// The tolerance used by an `abs` [comparison], displayed when an assert fails. /// /// [comparison]: index.html#comparison-algorithms fn debug_abs_tol(&self, other: &Rhs, tol: &Self::Tol) -> Self::DebugTol; /// The tolerance used by a `rel` [comparison], displayed when an assert fails. /// /// Equivalent to `self.debug_rmax_tol(self, other, tol)`, there is /// no need to reimplement this for your own types. /// /// [comparison]: index.html#comparison-algorithms #[inline] fn debug_rel_tol(&self, other: &Rhs, tol: &Self::Tol) -> Self::DebugTol { self.debug_rmax_tol(other, tol) } /// The tolerance used by an `rmax` [comparison], displayed when an assert fails. /// /// Returns `tol` scaled by the magnitude of the larger operand. /// /// [comparison]: index.html#comparison-algorithms fn debug_rmax_tol(&self, other: &Rhs, tol: &Self::Tol) -> Self::DebugTol; /// The tolerance used by an `rmin` [comparison], displayed when an assert fails. /// /// Returns `tol` scaled by the magnitude of the smaller operand. /// /// [comparison]: index.html#comparison-algorithms fn debug_rmin_tol(&self, other: &Rhs, tol: &Self::Tol) -> Self::DebugTol; /// The tolerance used by an `r1st` [comparison], displayed when an assert fails. /// /// Returns `tol` scaled by the magnitude of the first operand. /// /// [comparison]: index.html#comparison-algorithms fn debug_r1st_tol(&self, other: &Rhs, tol: &Self::Tol) -> Self::DebugTol; /// The tolerance used by an `r2nd` [comparison], displayed when an assert fails. /// /// Returns `tol` scaled by the magnitude of the second operand. /// /// [comparison]: index.html#comparison-algorithms fn debug_r2nd_tol(&self, other: &Rhs, tol: &Self::Tol) -> Self::DebugTol; /// The tolerance used by an `ulps` [comparison], displayed when an assert fails. /// /// [comparison]: index.html#comparison-algorithms fn debug_ulps_tol(&self, other: &Rhs, tol: &UlpsTol) -> UlpsTol where UlpsTol: Sized; } /// Debug context for when an assert using an `all` check fails. /// /// This trait is used by [`assert_float_eq!`] and [`assert_float_ne!`]. /// /// To implement this trait over a new type, see [How to compare custom types]. /// /// [How to compare custom types]: https://jtempest.github.io/float_eq-rs/book/how_to/compare_custom_types.html /// [ULPs]: https://jtempest.github.io/float_eq-rs/book/background/float_comparison_algorithms.html#units-in-the-last-place-ulps-comparison pub trait AssertFloatEqAll: FloatEqAll { /// Displayed to the user when an assert fails, using `fmt::Debug`. /// /// This should match the fields of the the most complex type in the comparison. type AllDebugTol: fmt::Debug + FloatEqUlpsTol; /// The tolerance used by an `abs_all` [comparison], displayed when an assert fails. /// /// [comparison]: index.html#comparison-algorithms fn debug_abs_all_tol(&self, other: &Rhs, tol: &Self::AllTol) -> Self::AllDebugTol; /// The tolerance used by a `rel_all` [comparison], displayed when an assert fails. /// /// Equivalent to `self.debug_rmax_all_tol(self, other, tol)`, there /// is no need to reimplement this for your own types. /// /// [comparison]: index.html#comparison-algorithms #[inline] fn debug_rel_all_tol(&self, other: &Rhs, tol: &Self::AllTol) -> Self::AllDebugTol { self.debug_rmax_all_tol(other, tol) } /// The tolerance used by an `rmax_all` [comparison], displayed when an assert fails. /// /// Returns `tol` scaled by the magnitude of the larger operand. /// /// [comparison]: index.html#comparison-algorithms fn debug_rmax_all_tol(&self, other: &Rhs, tol: &Self::AllTol) -> Self::AllDebugTol; /// The tolerance used by an `rmin_all` [comparison], displayed when an assert fails. /// /// Returns `tol` scaled by the magnitude of the smaller operand. /// /// [comparison]: index.html#comparison-algorithms fn debug_rmin_all_tol(&self, other: &Rhs, tol: &Self::AllTol) -> Self::AllDebugTol; /// The tolerance used by an `r1st_all` [comparison], displayed /// when an assert fails. /// /// Returns `tol` scaled by the magnitude of the first operand. /// /// [comparison]: index.html#comparison-algorithms fn debug_r1st_all_tol(&self, other: &Rhs, tol: &Self::AllTol) -> Self::AllDebugTol; /// The tolerance used by an `r2nd_all` [comparison], displayed when an assert fails. /// /// Returns `tol` scaled by the magnitude of the second operand. /// /// [comparison]: index.html#comparison-algorithms fn debug_r2nd_all_tol(&self, other: &Rhs, tol: &Self::AllTol) -> Self::AllDebugTol; /// The tolerance used by an `ulps_all` [comparison], displayed when an assert fails. /// /// [comparison]: index.html#comparison-algorithms fn debug_ulps_all_tol( &self, other: &Rhs, tol: &UlpsTol, ) -> UlpsTol where UlpsTol: Sized; }