ord_subset-3.1.1/.gitignore010066000017500001750000000000361305537140400140750ustar0000000000000000target Cargo.lock src/main.rs ord_subset-3.1.1/.travis.yml010066000017500001750000000003551334545405100142240ustar0000000000000000language: rust script: - cargo build --verbose --features="ops" - cargo test --verbose --features="ops" - cargo build --verbose --no-default-features --features="ops" - cargo test --verbose --no-default-features --features="ops" ord_subset-3.1.1/Cargo.toml.orig010066000017500001750000000017611334545347600150160ustar0000000000000000[package] name = "ord_subset" version = "3.1.1" authors = ["Emerentius"] license = "MIT/Apache-2.0" repository = "https://github.com/emerentius/ord_subset" documentation = "https://docs.rs/ord_subset/" description = "Tools for working with the Ord subset of certain PartialOrd types, like floats." keywords = ["iterator", "slice", "Ord", "PartialOrd", "float"] [features] default = ["std"] # Provides ord_subset_* versions of allocating sorts on slices std = [] # Currently does nothing # Provides in principle access to features dependent on unstable functionality unstable = [] # Forward core::ops implementations of T to OrdVar # e.g. impl Add for OrdVar where T: Add # all results are checked to be ordered by default # Does not yet allow OrdVar `op` OrdVar unless T: Add> ops = [] # Deactivate Ord checks for the result of overloaded ops # Because this is not a purely additive feature, it may cause # interoperability issues with other crates unchecked_ops = ["ops"] ord_subset-3.1.1/Cargo.toml0000644000000017130000000000000112460ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "ord_subset" version = "3.1.1" authors = ["Emerentius"] description = "Tools for working with the Ord subset of certain PartialOrd types, like floats." documentation = "https://docs.rs/ord_subset/" keywords = ["iterator", "slice", "Ord", "PartialOrd", "float"] license = "MIT/Apache-2.0" repository = "https://github.com/emerentius/ord_subset" [features] default = ["std"] ops = [] std = [] unchecked_ops = ["ops"] unstable = [] ord_subset-3.1.1/CHANGELOG.md010066000017500001750000000042741334545371300137340ustar0000000000000000Version 1.1.0 (2016-01-25) -------------------------- * Implement `Hash` for `OrdVar(T)`, if `T: Hash` Version 1.2.0 (2016-03-08) -------------------------- * Add two new default methods `ord_subset_min_by_key` and `ord_subset_max_by_key` for `OrdSubsetIterExt` to mimic std library. Version 2.0.0 (2017-02-28) ========================== * Allow `*_by_key()` functions for iterators and slices when the items aren't `OrdSubset`. Only the keys need to be. This changes the extension traits' bounds, therefore technically a [breaking change] (cause for major version bump) * Add long overdue `ord_subset_sort_by_key()` and `ord_subset_binary_search_by_key()` for slices Version 2.1.0 (2017-09-23) -------------------------- * `OrdVar::new_unchecked()` is no longer marked unsafe. Incorrectly constructed `OrdVar`s can cause crashes and surprising behaviour but no memory unsafety * In slice sorting, uphold sort stability for values outside total order. Version 3.0.0 (2017-10-21) ========================== * Add `sort_unstable*` variants, following the std library additions in 1.20. Technically a [breaking change]. * Generalized traits so that `.ord_subset_binary_search*` works on immutable slices and anything else that implements AsRef<[T]>, but not AsMut<[T]>. Fixing this major oversight is also technically a [breaking change]. * `#![no_std]` support with new opt-out feature `std` Stable sorts are unavailable in `no_std` mode. OrdSubset implementations for f32, f64 with `no_std` require the `unstable` feature of this crate (impls readded in 3.1 without `unstable`). * Stabilized `_rev()` variants Version 3.1.0 (2017-11-26) -------------------------- * Add `OrdSubset` impls for all `Ord` intrinsics, including arrays and tuples up to an arity of 32 and 12 respectively as well as slices. * Add `OrdSubset` impls for `f32`, `f64` in `no_std` mode without requiring `unstable`. * Add new feature `ops` for overloading operators for `OrdVar` for anything that `T` is overloaded for. Checks whether result can be ordered. This can be deactivated with `unchecked ops`. Version 3.1.1 (2018-09-10) -------------------------- * Code tarball doesn't unnecessarily contain files with executable bit set anymore. ord_subset-3.1.1/LICENSE-APACHE010066000017500001750000000251371334545401600140450ustar0000000000000000 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. ord_subset-3.1.1/LICENSE-MIT010066000017500001750000000020231334545403200135400ustar0000000000000000Copyright (c) 2015 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. ord_subset-3.1.1/README.md010066000017500001750000000020311320514373200133570ustar0000000000000000# ord_subset [![Build Status](https://travis-ci.org/Emerentius/ord_subset.svg?branch=master)](https://travis-ci.org/Emerentius/ord_subset) Crate for working with the `Ord` subset of certain types like `f32`, `f64`. Documentation is up at https://docs.rs/ord_subset/. # Usage Add this to your `Cargo.toml`: ```toml [dependencies] ord_subset = "3" ``` ```rust extern crate ord_subset; use ord_subset::{OrdSubsetIterExt, OrdSubsetSliceExt}; fn main() { // Slices. Works on vector, too. let mut s = [5.0, std::f64::NAN, 3.0, 2.0]; s.ord_subset_sort(); assert_eq!(&s[0..3], &[2.0, 3.0, 5.0]); assert_eq!(s.ord_subset_binary_search(&5.0), Ok(2)); // iterators assert_eq!( s.iter().ord_subset_max(), Some(&5.0) ); assert_eq!( s.iter().ord_subset_min(), Some(&2.0) ); } ``` # License Licensed under the Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0 or the MIT license http://opensource.org/licenses/MIT, at your option. This file may not be copied, modified, or distributed except according to those terms. ord_subset-3.1.1/src/iter_ext.rs010066000017500001750000000070361334545410600150770ustar0000000000000000// Licensed under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 or the MIT license // http://opensource.org/licenses/MIT, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ord_subset_trait::*; use ord_var::*; ///////////////////////////////////////////////////////////////////// pub trait OrdSubsetIterExt: Iterator //where Self::Item: OrdSubset { /// Consumes the entire iterator to return the maximum element. /// Values outside the ordered subset as given by `.is_outside_order()` are ignored. /// /// Returns the last element if the comparison determines multiple elements to be equally maximum. /// /// # Example /// /// ``` /// use ord_subset::OrdSubsetIterExt; /// /// let vec = vec![2.0, 3.0, 5.0, std::f64::NAN]; /// let max = vec.iter().ord_subset_max().unwrap(); /// assert_eq!(&5.0, max); /// ``` #[inline] fn ord_subset_max(self) -> Option where Self: Sized, Self::Item: OrdSubset, { self.filter_map(OrdVar::new_checked) .max() .map(OrdVar::into_inner) // Option> => Option } /// Consumes the entire iterator to return the minimum element. /// Values outside the ordered subset as given by `.is_outside_order()` are ignored. /// /// Returns the first element if the comparison determines multiple elements to be equally minimum. /// /// # Example /// /// ``` /// use ord_subset::OrdSubsetIterExt; /// /// let vec = vec![2.0, 3.0, 5.0, std::f64::NAN]; /// let min = vec.iter().ord_subset_min().unwrap(); /// assert_eq!(&2.0, min); /// ``` #[inline] fn ord_subset_min(self) -> Option where Self: Sized, Self::Item: OrdSubset, { self.filter_map(OrdVar::new_checked) .min() .map(OrdVar::into_inner) // Option> => Option } /// Returns the element that gives the minimum value from the specified function. /// Values outside the ordered subset as given by `.is_outside_order()` on the mapped value are ignored. /// /// Returns the first element if the comparison determines multiple elements to be equally minimum. /// /// # Example /// /// ``` /// extern crate ord_subset; /// use ord_subset::OrdSubsetIterExt; /// /// fn main() { /// let vec = vec![2.0, 3.0, 5.0, std::f64::NAN]; /// let min_by = vec.iter().ord_subset_min_by_key(|num| num.recip()).unwrap(); /// assert_eq!(&5.0, min_by); /// } /// ``` #[inline] fn ord_subset_min_by_key(self, mut f: F) -> Option where F: FnMut(&Self::Item) -> B, B: OrdSubset, Self: Sized, { // Ok < Err, always self.min_by_key(|it| OrdVar::new_checked(f(it)).ok_or(())) } /// Returns the element that gives the maximum value from the specified function. /// Values outside the ordered subset as given by `.is_outside_order()` on the mapped value are ignored. /// /// Returns the last element if the comparison determines multiple elements to be equally maximum. #[inline] fn ord_subset_max_by_key(self, mut f: F) -> Option where F: FnMut(&Self::Item) -> B, B: OrdSubset, Self: Sized, { // Some > None, always self.max_by_key(|it| OrdVar::new_checked(f(it))) } } impl OrdSubsetIterExt for T {} ord_subset-3.1.1/src/lib.rs010066000017500001750000000040431334545410200140110ustar0000000000000000#![cfg_attr(feature = "cargo-clippy", allow(inline_always, match_bool))] //! Ever wanted to call `.max()` on an iterator of floats? Now you can! Well, almost: `.ord_subset_max()`. //! //! This crate is for types like the float primitive types `f32` and `f64`: Types that are totally ordered *except for these particular values*. //! //! I call these types subset-ordered. They can be marked with the `OrdSubset` trait that this crate defines. //! Such types can be put in the `OrdVar` struct. Wrapping your value in this marks to other code that the contents are ordered, thus fulfilling generic `Ord` trait bounds. //! //! For convenience, iterators and slices are extended so that `OrdSubset` types have access to methods equivalent to `.max()` and `.sort()`. //! Values in the unordered subset of a type that is `OrdSubset` are handled in a consistent manner (Ignored or put at the end). //! //! # Usage //! //! Add this to your `Cargo.toml`: //! //! ```toml //! [dependencies] //! ord_subset = "3" //! ``` //! //! //! ``` //! use ord_subset::{OrdSubsetIterExt, OrdSubsetSliceExt}; //! //! // Slices. Works on vector, too. //! let mut s = [5.0, std::f64::NAN, 3.0, 2.0]; //! s.ord_subset_sort_unstable(); //! assert_eq!(&s[0..3], &[2.0, 3.0, 5.0]); //! assert_eq!(s.ord_subset_binary_search(&5.0), Ok(2)); //! //! // iterators //! assert_eq!( s.iter().ord_subset_max(), Some(&5.0) ); //! assert_eq!( s.iter().ord_subset_min(), Some(&2.0) ); //! ``` //! //! # License //! Licensed under the Apache License, Version 2.0 //! or the MIT license //! , at your //! option. This file may not be copied, modified, or distributed //! except according to those terms. //#![cfg_attr(feature="unstable", unstable)] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "std")] // attribute not necessary, but rls warns without extern crate core; mod iter_ext; mod ord_var; mod slice_ext; mod ord_subset_trait; pub use iter_ext::*; pub use ord_var::*; pub use slice_ext::*; pub use ord_subset_trait::*; ord_subset-3.1.1/src/ord_subset_trait.rs010066000017500001750000000130371334545410400166240ustar0000000000000000// Licensed under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 or the MIT license // http://opensource.org/licenses/MIT, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// Trait for types that form a total order when a few values are disallowed. /// /// `is_outside_order()` must return `true` for these outliers and `false` for anything else. /// /// `std::cmp::PartialOrd::partial_cmp(a,b)` must return `Some(_)` if a,b are both inside order and `None` if only one is outside order. Return value for two variables outside order is undefined. pub trait OrdSubset: PartialOrd + PartialEq { fn is_outside_order(&self) -> bool; } impl<'a, A> OrdSubset for &'a A where A: OrdSubset, { #[inline(always)] fn is_outside_order(&self) -> bool { (**self).is_outside_order() } } impl<'a, A> OrdSubset for &'a mut A where A: OrdSubset, { #[inline(always)] fn is_outside_order(&self) -> bool { (**self).is_outside_order() } } #[cfg_attr(feature = "cargo-clippy", allow(float_cmp, eq_op))] impl OrdSubset for f64 { #[inline(always)] fn is_outside_order(&self) -> bool { // only NaNs != itself *self != *self } } #[cfg_attr(feature = "cargo-clippy", allow(float_cmp, eq_op))] impl OrdSubset for f32 { #[inline(always)] fn is_outside_order(&self) -> bool { // only NaNs != itself *self != *self } } trait EnsureOrd: Ord {} macro_rules! impl_for_ord { ($($type:ty),+) => ( $( // safe guard against incorrect macro invocation // `where Self: Ord` on OrdSubset impl would be rendered in docs impl EnsureOrd for $type {} impl OrdSubset for $type { #[inline(always)] fn is_outside_order(&self) -> bool { false } } )+ ) } #[cfg_attr(rustfmt, rustfmt_skip)] impl_for_ord!((), u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, bool, char); macro_rules! array_impls { ($($N:expr),+) => { $( impl OrdSubset for [T; $N] { #[inline(always)] fn is_outside_order(&self) -> bool { (&self[..]).is_outside_order() } } )+ } } #[cfg_attr(rustfmt, rustfmt_skip)] array_impls!( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ); impl OrdSubset for [T] { #[inline(always)] fn is_outside_order(&self) -> bool { self.iter().any(OrdSubset::is_outside_order) } } // code stolen from std library macro_rules! tuple_impls { ($( $Tuple:ident { $(($idx:tt) -> $T:ident)+ } )+) => { $( impl<$($T:OrdSubset),+> OrdSubset for ($($T,)+) where last_type!($($T,)+): ?Sized { #[inline] fn is_outside_order(&self) -> bool { $(self.$idx.is_outside_order())||+ } } )+ } } 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 } } // Small helper used a lot in sorts pub(crate) trait CmpUnwrap: OrdSubset { #[inline(always)] fn cmp_unwrap(&self, other: &Self) -> ::core::cmp::Ordering { self.partial_cmp(other).expect( "Violated OrdSubset contract: a.partial_cmp(b) == None for a,b inside total order", ) } } impl CmpUnwrap for T {} // The tests here are primarily compile time tests // If the tuple macros were wrong, it would show up in the std library #[cfg(test)] mod test { use super::OrdSubset; #[test] fn heterogenous_tuple() { #[cfg_attr(rustfmt, rustfmt_skip)] let tup = ((), 0u8, 0u16, 0u32, 0u64, 0usize, 0i8, 0i16, 0i32, 0i64, 0isize, 'a'); assert!(!tup.is_outside_order()); } #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn slice() { let a = [0u8; 32]; assert!( ! a.is_outside_order() ); assert!( ! a.as_ref().is_outside_order() ); } } ord_subset-3.1.1/src/ord_var.rs010066000017500001750000000300031334545410000146700ustar0000000000000000// Licensed under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 or the MIT license // http://opensource.org/licenses/MIT, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use core::cmp::Ordering; use core::fmt::Debug; use ord_subset_trait::*; use core::ops::Deref; /// Wrapper to signal that the contained variables have a total order. It's illegal to compare two `OrdVar`s that are not ordered. /// For this reason, it's unsafe to create `OrdVar`s without checking. Checked constructors are available for `OrdSubset` types. /// /// # Panics /// /// Panics when `a.partial_cmp(b)` returns `None` for two values `a`,`b`. #[derive(PartialEq, PartialOrd, Clone, Copy, Debug, Hash)] pub struct OrdVar(T); impl OrdVar { /// Construct an ```OrdVar``` out of the argument. /// /// # Panics /// /// Panics if the argument is outside of the total order. #[inline] pub fn new(data: T) -> OrdVar where T: Debug + OrdSubset, { if data.is_outside_order() { panic!( "Attempted saving data outside of total order into OrdVar: {:?}", data ) }; OrdVar(data) } /// Constructs an ```Option``` out of the argument. Returns None if the argument is outside the total order. #[inline] pub fn new_checked(data: T) -> Option> where T: OrdSubset, { match data.is_outside_order() { true => None, false => Some(OrdVar(data)), } } /// Constructs an `OrdVar` without validity check. Incorrectly constructed `OrdVar`s may panic on calls to `.cmp()`. /// The comparison operators (`>`, `>=`, `=`, `!=`, `<`, `<=`) will not panic but may result in surprising behaviour. #[inline(always)] pub fn new_unchecked(data: T) -> OrdVar { OrdVar(data) } #[inline(always)] pub fn into_inner(self) -> T { self.0 } } impl Eq for OrdVar {} impl Ord for OrdVar { #[inline] fn cmp(&self, other: &Self) -> Ordering { self.partial_cmp(other) .expect("OrdVar contains value outside total order") } } impl Deref for OrdVar { type Target = T; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl AsRef for OrdVar { #[inline(always)] fn as_ref(&self) -> &T { &self.0 } } impl Default for OrdVar { #[inline(always)] fn default() -> Self { OrdVar::new(T::default()) } } #[cfg(feature = "ops")] mod ops { // would love to be able to macro these away somehow #[cfg_attr(rustfmt, rustfmt_skip)] use core::ops::{Add, Sub, Mul, Div, Rem, BitAnd, BitOr, BitXor, Shl, Shr, Neg, Not, AddAssign, SubAssign, MulAssign, DivAssign, RemAssign, BitAndAssign, BitOrAssign, BitXorAssign, ShlAssign, ShrAssign,}; use core::fmt::Debug; use ord_subset_trait::*; use super::OrdVar; #[inline(always)] fn construct(t: T) -> OrdVar { match cfg!(feature = "unchecked_ops") { true => OrdVar::new_unchecked(t), false => OrdVar::new(t), } } // ----------------- binary ops ----------------------------------------------- impl Add for OrdVar where T: PartialOrd + PartialEq + Add, T::Output: PartialOrd + PartialEq + Debug + OrdSubset, { type Output = OrdVar; fn add(self, rhs: RHS) -> Self::Output { construct(self.into_inner().add(rhs)) } } impl Sub for OrdVar where T: PartialOrd + PartialEq + Sub, T::Output: PartialOrd + PartialEq + Debug + OrdSubset, { type Output = OrdVar; fn sub(self, rhs: RHS) -> Self::Output { construct(self.into_inner().sub(rhs)) } } impl Mul for OrdVar where T: PartialOrd + PartialEq + Mul, T::Output: PartialOrd + PartialEq + Debug + OrdSubset, { type Output = OrdVar; fn mul(self, rhs: RHS) -> Self::Output { construct(self.into_inner().mul(rhs)) } } impl Div for OrdVar where T: PartialOrd + PartialEq + Div, T::Output: PartialOrd + PartialEq + Debug + OrdSubset, { type Output = OrdVar; fn div(self, rhs: RHS) -> Self::Output { construct(self.into_inner().div(rhs)) } } impl Rem for OrdVar where T: PartialOrd + PartialEq + Rem, T::Output: PartialOrd + PartialEq + Debug + OrdSubset, { type Output = OrdVar; fn rem(self, rhs: RHS) -> Self::Output { construct(self.into_inner().rem(rhs)) } } impl BitAnd for OrdVar where T: PartialOrd + PartialEq + BitAnd, T::Output: PartialOrd + PartialEq + Debug + OrdSubset, { type Output = OrdVar; fn bitand(self, rhs: RHS) -> Self::Output { construct(self.into_inner().bitand(rhs)) } } impl BitOr for OrdVar where T: PartialOrd + PartialEq + BitOr, T::Output: PartialOrd + PartialEq + Debug + OrdSubset, { type Output = OrdVar; fn bitor(self, rhs: RHS) -> Self::Output { construct(self.into_inner().bitor(rhs)) } } impl BitXor for OrdVar where T: PartialOrd + PartialEq + BitXor, T::Output: PartialOrd + PartialEq + Debug + OrdSubset, { type Output = OrdVar; fn bitxor(self, rhs: RHS) -> Self::Output { construct(self.into_inner().bitxor(rhs)) } } impl Shl for OrdVar where T: PartialOrd + PartialEq + Shl, T::Output: PartialOrd + PartialEq + Debug + OrdSubset, { type Output = OrdVar; fn shl(self, rhs: RHS) -> Self::Output { construct(self.into_inner().shl(rhs)) } } impl Shr for OrdVar where T: PartialOrd + PartialEq + Shr, T::Output: PartialOrd + PartialEq + Debug + OrdSubset, { type Output = OrdVar; fn shr(self, rhs: RHS) -> Self::Output { construct(self.into_inner().shr(rhs)) } } // ------------------------ binary assign ops ---------------------------------- impl AddAssign for OrdVar where T: PartialOrd + PartialEq + AddAssign + OrdSubset, { fn add_assign(&mut self, rhs: RHS) { self.0.add_assign(rhs); if !cfg!(feature = "unchecked_ops") { assert!( !self.0.is_outside_order(), "Result of {}= operation is outside order", "+" ); } } } impl SubAssign for OrdVar where T: PartialOrd + PartialEq + SubAssign + OrdSubset, { fn sub_assign(&mut self, rhs: RHS) { self.0.sub_assign(rhs); if !cfg!(feature = "unchecked_ops") { assert!( !self.0.is_outside_order(), "Result of {}= operation is outside order", "-" ); } } } impl MulAssign for OrdVar where T: PartialOrd + PartialEq + MulAssign + OrdSubset, { fn mul_assign(&mut self, rhs: RHS) { self.0.mul_assign(rhs); if !cfg!(feature = "unchecked_ops") { assert!( !self.0.is_outside_order(), "Result of {}= operation is outside order", "*" ); } } } impl DivAssign for OrdVar where T: PartialOrd + PartialEq + DivAssign + OrdSubset, { fn div_assign(&mut self, rhs: RHS) { self.0.div_assign(rhs); if !cfg!(feature = "unchecked_ops") { assert!( !self.0.is_outside_order(), "Result of {}= operation is outside order", "/" ); } } } impl RemAssign for OrdVar where T: PartialOrd + PartialEq + RemAssign + OrdSubset, { fn rem_assign(&mut self, rhs: RHS) { self.0.rem_assign(rhs); if !cfg!(feature = "unchecked_ops") { assert!( !self.0.is_outside_order(), "Result of {}= operation is outside order", "%" ); } } } impl BitAndAssign for OrdVar where T: PartialOrd + PartialEq + BitAndAssign + OrdSubset, { fn bitand_assign(&mut self, rhs: RHS) { self.0.bitand_assign(rhs); if !cfg!(feature = "unchecked_ops") { assert!( !self.0.is_outside_order(), "Result of {}= operation is outside order", "&" ); } } } impl BitOrAssign for OrdVar where T: PartialOrd + PartialEq + BitOrAssign + OrdSubset, { fn bitor_assign(&mut self, rhs: RHS) { self.0.bitor_assign(rhs); if !cfg!(feature = "unchecked_ops") { assert!( !self.0.is_outside_order(), "Result of {}= operation is outside order", "|" ); } } } impl BitXorAssign for OrdVar where T: PartialOrd + PartialEq + BitXorAssign + OrdSubset, { fn bitxor_assign(&mut self, rhs: RHS) { self.0.bitxor_assign(rhs); if !cfg!(feature = "unchecked_ops") { assert!( !self.0.is_outside_order(), "Result of {}= operation is outside order", "^" ); } } } impl ShlAssign for OrdVar where T: PartialOrd + PartialEq + ShlAssign + OrdSubset, { fn shl_assign(&mut self, rhs: RHS) { self.0.shl_assign(rhs); if !cfg!(feature = "unchecked_ops") { assert!( !self.0.is_outside_order(), "Result of {}= operation is outside order", "<<" ); } } } impl ShrAssign for OrdVar where T: PartialOrd + PartialEq + ShrAssign + OrdSubset, { fn shr_assign(&mut self, rhs: RHS) { self.0.shr_assign(rhs); if !cfg!(feature = "unchecked_ops") { assert!( !self.0.is_outside_order(), "Result of {}= operation is outside order", ">>" ); } } } // ------------------------ unary ops ------------------------------------------ impl Neg for OrdVar where T: PartialOrd + PartialEq + Neg, T::Output: PartialOrd + PartialEq + Debug + OrdSubset, { type Output = OrdVar; fn neg(self) -> Self::Output { construct(self.into_inner().neg()) } } impl Not for OrdVar where T: PartialOrd + PartialEq + Not, T::Output: PartialOrd + PartialEq + Debug + OrdSubset, { type Output = OrdVar; fn not(self) -> Self::Output { construct(self.into_inner().not()) } } } ord_subset-3.1.1/src/slice_ext.rs010066000017500001750000000333041334306667700152420ustar0000000000000000// Licensed under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 or the MIT license // http://opensource.org/licenses/MIT, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ord_subset_trait::*; use core::cmp::Ordering::{self, Equal, Greater, Less}; static ERROR_BINARY_SEARCH_OUTSIDE_ORDER: &str = "Attempted binary search for value outside total order"; static ERROR_BINARY_SEARCH_EXPECT: &str = "Unexpected None for a.partial_cmp(b), a,b inside order. Violated OrdSubset contract or attempted binary search on unsorted data"; // Wrapper for comparison functions // Treats unordered values as greater than any ordered #[inline] fn cmp_unordered_greater_all(a: &T, b: &T, mut compare: F) -> Ordering where F: FnMut(&T, &T) -> Ordering, { match (a.is_outside_order(), b.is_outside_order()) { // catch invalids and put them at the end // Ordering of two-non-ords in the (true, true) case is irrelevant // for the goal of collecting them at the end. However, comparing them // as equal will let the algorithm uphold its stability properties (true, true) => Equal, (true, false) => Greater, (false, true) => Less, (false, false) => compare(a, b), // the normal case, both valid. Here user function applies. } } pub trait OrdSubsetSliceExt { /// Sort the slice. Values outside the ordered subset are put at the end in their original order. /// /// This is equivalent to `self.ord_subset_sort_by(|a,b| a.partial_cmp(b).unwrap())` /// /// # Panics /// /// Panics when `a.partial_cmp(b)` returns `None` for two values `a`,`b` inside the total order (Violated OrdSubset contract). #[cfg(feature = "std")] fn ord_subset_sort(&mut self) where Self: AsMut<[T]>, T: OrdSubset; /// Sort the slice in reverse order. Values outside the ordered subset are put at the end in their original order (i.e. not reversed). /// /// # Panics /// /// Panics when `a.partial_cmp(b)` returns `None` for two values `a`,`b` inside the total order (Violated OrdSubset contract). #[cfg(feature = "std")] fn ord_subset_sort_rev(&mut self) where Self: AsMut<[T]>, T: OrdSubset; /// Sorts the slice, using `compare` to order elements. Values outside the total order are put at the end in their original order. /// `compare` will not be called on them. If you wish to handle these yourself, use the regular `.sort_by()`. /// /// **Warning:** The function interface is identical to the `.sort_by()` interface. Be careful not to miss `ord_subset_` in front. /// It would work until you have unordered values in your slice, then crash unexpectedly. /// /// This delegates to `.sort_by()` in the std library. See [official docs](https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by) for /// time and space complexity of the current implementation. /// /// # Panics /// /// Panics when `a.partial_cmp(b)` returns `None` for two values `a`,`b` inside the total order (Violated OrdSubset contract). #[cfg(feature = "std")] fn ord_subset_sort_by(&mut self, compare: F) where Self: AsMut<[T]>, T: OrdSubset, F: FnMut(&T, &T) -> Ordering; /// Sorts the slice, using `key` to extract a key by which to order the sort by. Entries mapping to values outside /// the total order will be put at the end in their original order. /// /// This delegates to `.sort_by()` in the std library. See [official docs](https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by) for /// time and space complexity of the current implementation. #[cfg(feature = "std")] fn ord_subset_sort_by_key(&mut self, f: F) where Self: AsMut<[T]>, B: OrdSubset, F: FnMut(&T) -> B; /// Sort the slice. Values outside the ordered subset are put at the end. /// /// This is equivalent to `self.ord_subset_sort_by(|a,b| a.partial_cmp(b).unwrap())` /// /// # Panics /// /// Panics when `a.partial_cmp(b)` returns `None` for two values `a`,`b` inside the total order (Violated OrdSubset contract). fn ord_subset_sort_unstable(&mut self) where Self: AsMut<[T]>, T: OrdSubset; /// Sort the slice in reverse order. Values outside the ordered subset are put at the end. /// /// # Panics /// /// Panics when `a.partial_cmp(b)` returns `None` for two values `a`,`b` inside the total order (Violated OrdSubset contract). fn ord_subset_sort_unstable_rev(&mut self) where Self: AsMut<[T]>, T: OrdSubset; /// Sorts the slice, using `compare` to order elements. Values outside the total order are put at the end. /// `compare` will not be called on them. If you wish to handle these yourself, use the regular `.sort_unstable_by()`. /// /// **Warning:** The function interface is identical to the `.sort_unstable_by()` interface. Be careful not to miss `ord_subset_` in front. /// It would work until you have unordered values in your slice, then crash unexpectedly. /// /// This delegates to `.sort_by_unstable()` in the std library. See [official docs](https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by_unstable) for /// time and space complexity of the current implementation. /// /// # Panics /// /// Panics when `a.partial_cmp(b)` returns `None` for two values `a`,`b` inside the total order (Violated OrdSubset contract). fn ord_subset_sort_unstable_by(&mut self, compare: F) where Self: AsMut<[T]>, T: OrdSubset, F: FnMut(&T, &T) -> Ordering; /// Sorts the slice, using `key` to extract a key by which to order the sort by. Entries mapping to values outside /// the total order will be put at the end. /// /// This delegates to `.sort_by_unstable()` in the std library. See [official docs](https://doc.rust-lang.org/std/primitive.slice.html#method.sort_by_unstable) for /// time and space complexity of the current implementation. fn ord_subset_sort_unstable_by_key(&mut self, f: F) where Self: AsMut<[T]>, B: OrdSubset, F: FnMut(&T) -> B; /// Binary search a sorted slice for a given element. Values outside the ordered subset need to be at the end of the slice. /// /// If the value is found then Ok is returned, containing the index of the matching element; if the value is not found then Err is returned, containing the index where a matching element could be inserted while maintaining sorted order. /// /// # Example /// /// Looks up a series of five elements. The first is found, with a uniquely determined position; the second and third are not found; the fourth could match any position in `[1,4]`. /// /// ``` /// use ord_subset::OrdSubsetSliceExt; /// use std::f64; /// /// let s = [0., 1., 1., 1., 1., 2., 3., 5., 8., 13., 21., 34., 55., f64::NAN, f64::NAN]; /// /// assert_eq!(s.ord_subset_binary_search(&13.), Ok(9)); /// assert_eq!(s.ord_subset_binary_search(&4.), Err(7)); /// assert_eq!(s.ord_subset_binary_search(&100.), Err(13)); /// let r = s.ord_subset_binary_search(&1.); /// assert!(match r { Ok(1...4) => true, _ => false, }); /// assert_eq!(s.ord_subset_binary_search(&f64::INFINITY), Err(13)); /// ``` /// /// # Panics /// /// Panics if the argument is outside of the total order. Also panics when `a.partial_cmp(b)` returns `None` for two values `a`,`b` inside the total order (Violated OrdSubset contract). fn ord_subset_binary_search(&self, x: &T) -> Result where T: OrdSubset; /// Binary search a sorted slice with a comparator function. /// /// The comparator function should implement an order consistent with the sort order of the underlying slice, returning an order code that indicates whether its argument is Less, Equal or Greater the desired target. The comparator will only be called for values inside the total order. /// /// It's imperative, that the comparator function doesn't compare its arguments with values outside the total order. This will result in bogus output which cannot be caught by this function. /// /// If a matching value is found then returns Ok, containing the index for the matched element; if no match is found then Err is returned, containing the index where a matching element could be inserted while maintaining sorted order. fn ord_subset_binary_search_by(&self, f: F) -> Result where T: OrdSubset, F: FnMut(&T) -> Ordering; /// Binary search a sorted slice with a key extraction function. /// /// Assumes that the slice is sorted by the key, for instance with `ord_subset_sort_by_key` using the same key extraction function. /// /// If a matching value is found then returns `Ok`, containing the index for the matched element; if no match is found then `Err` is returned, containing the index where a matching element could be inserted while maintaining sorted order. fn ord_subset_binary_search_by_key(&self, b: &B, f: F) -> Result where B: OrdSubset, F: FnMut(&T) -> B; /// Binary search a slice sorted in reverse order for a given element. Values outside the ordered subset need to be at the end of the slice. /// /// If a matching value is found then returns Ok, containing the index for the matched element; if no match is found then Err is returned, containing the index where a matching element could be inserted while maintaining sorted order. /// /// # Panics /// /// Panics if the argument is outside of the total order. Also panics when `a.partial_cmp(b)` returns `None` for two values `a`,`b` inside the total order (Violated OrdSubset contract). fn ord_subset_binary_search_rev(&self, x: &T) -> Result where T: OrdSubset; } impl OrdSubsetSliceExt for U where U: AsRef<[T]>, { #[cfg(feature = "std")] #[inline] fn ord_subset_sort(&mut self) where U: AsMut<[T]>, T: OrdSubset, { self.as_mut().ord_subset_sort_by(|a, b| a.cmp_unwrap(b)) } #[cfg(feature = "std")] #[inline] fn ord_subset_sort_by(&mut self, mut compare: F) where U: AsMut<[T]>, T: OrdSubset, F: FnMut(&T, &T) -> Ordering, { self.as_mut() .sort_by(|a, b| cmp_unordered_greater_all(a, b, &mut compare)) } #[cfg(feature = "std")] #[inline] fn ord_subset_sort_rev(&mut self) where U: AsMut<[T]>, T: OrdSubset, { self.as_mut().ord_subset_sort_by(|a, b| b.cmp_unwrap(a)) } #[cfg(feature = "std")] #[inline] fn ord_subset_sort_by_key(&mut self, mut f: F) where U: AsMut<[T]>, B: OrdSubset, F: FnMut(&T) -> B, { self.as_mut() .sort_by(|a, b| cmp_unordered_greater_all(&(f(a)), &(f(b)), CmpUnwrap::cmp_unwrap)) } #[inline] fn ord_subset_sort_unstable(&mut self) where U: AsMut<[T]>, T: OrdSubset, { self.as_mut() .ord_subset_sort_unstable_by(|a, b| a.cmp_unwrap(b)) } #[inline] fn ord_subset_sort_unstable_by(&mut self, mut compare: F) where U: AsMut<[T]>, T: OrdSubset, F: FnMut(&T, &T) -> Ordering, { self.as_mut() .sort_unstable_by(|a, b| cmp_unordered_greater_all(a, b, &mut compare)) } #[inline] fn ord_subset_sort_unstable_rev(&mut self) where U: AsMut<[T]>, T: OrdSubset, { self.as_mut() .ord_subset_sort_unstable_by(|a, b| b.cmp_unwrap(a)) } #[inline] fn ord_subset_sort_unstable_by_key(&mut self, mut f: F) where U: AsMut<[T]>, B: OrdSubset, F: FnMut(&T) -> B, { self.as_mut().sort_unstable_by(|a, b| { cmp_unordered_greater_all(&(f(a)), &(f(b)), CmpUnwrap::cmp_unwrap) }) } #[inline] fn ord_subset_binary_search(&self, x: &T) -> Result where T: OrdSubset, { if x.is_outside_order() { panic!(ERROR_BINARY_SEARCH_OUTSIDE_ORDER) }; self.ord_subset_binary_search_by(|other| { other.partial_cmp(x).expect(ERROR_BINARY_SEARCH_EXPECT) }) } #[inline] fn ord_subset_binary_search_by(&self, mut f: F) -> Result where T: OrdSubset, F: FnMut(&T) -> Ordering, { self.as_ref().binary_search_by(|other| { match other.is_outside_order() { true => Greater, // unordered always at end false => f(other), } }) } #[inline] fn ord_subset_binary_search_by_key(&self, b: &B, mut f: F) -> Result where B: OrdSubset, F: FnMut(&T) -> B, { if b.is_outside_order() { panic!(ERROR_BINARY_SEARCH_OUTSIDE_ORDER) }; // compare ordered values as expected // wrap it in a function that deals with unordered, so this one never sees them let cmp_ord = |a: &B, b: &B| a.partial_cmp(b).expect(ERROR_BINARY_SEARCH_EXPECT); self.as_ref() .binary_search_by(|k| cmp_unordered_greater_all(&f(k), b, &cmp_ord)) } #[inline] fn ord_subset_binary_search_rev(&self, x: &T) -> Result where T: OrdSubset, { if x.is_outside_order() { panic!(ERROR_BINARY_SEARCH_OUTSIDE_ORDER) }; self.ord_subset_binary_search_by(|other| { x.partial_cmp(other).expect(ERROR_BINARY_SEARCH_EXPECT) }) } } ord_subset-3.1.1/tests/lib.rs010066000017500001750000000321001334545406100143630ustar0000000000000000#![cfg_attr(feature = "cargo-clippy", allow(float_cmp, match_wild_err_arm))] extern crate ord_subset; extern crate core; use ord_subset::OrdSubsetIterExt; use ord_subset::OrdSubsetSliceExt; use ord_subset::OrdSubset; use ord_subset::OrdVar; use std::f64::INFINITY as INF; use std::f64::NAN; const N: usize = 32; const N_NO_NAN: usize = 30; const TEST_ARRAY: [f64; N] = [1.0, 7.0, 26.0, INF, NAN, 0.0, 14.0, 17.0, 27.0, 13.0, 10.0, 3.0, NAN, 25.0, 9.0, 20.0, 16.0, 8.0, -INF, 4.0, 2.0, 22.0, 18.0, 21.0, 15.0, 6.0, 24.0, 19.0, 12.0, 11.0, 5.0, 23.0]; // subset of TEST_ARRAY const TEST_ARRAY_NO_NAN: [f64; N_NO_NAN] = [1.0, 7.0, 26.0, INF, 0.0, 14.0, 17.0, 27.0, 13.0, 10.0, 3.0, 25.0, 9.0, 20.0, 16.0, 8.0, -INF, 4.0, 2.0, 22.0, 18.0, 21.0, 15.0, 6.0, 24.0, 19.0, 12.0, 11.0, 5.0, 23.0]; const SORTED_TEST_ARRAY: [f64; N] = [-INF, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, INF, NAN, NAN]; const SORTED_TEST_ARRAY_NO_NAN: [f64; N_NO_NAN] = [-INF, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, INF ]; #[derive(PartialEq, PartialOrd, Clone, Copy)] struct NotOrdSub(); #[derive(PartialEq, PartialOrd, Clone, Copy)] struct OrdSub(); impl OrdSubset for OrdSub { fn is_outside_order(&self) -> bool { true } } // ---------------------------- iter ext methods ------------------------------- #[test] fn ord_subset_max() { let arr = [2.0, 3.0, 5.0, std::f64::NAN]; let max = arr.iter().ord_subset_max().unwrap(); assert_eq!(&5.0, max); } #[test] fn ord_subset_max_by() { let arr = [2.0, 3.0, 5.0, std::f64::NAN]; let max_by = arr.iter().ord_subset_max_by_key(|num| num.recip()).unwrap(); assert_eq!(&2.0, max_by); } #[test] fn ord_subset_min() { let arr = [2.0, 3.0, 5.0, std::f64::NAN]; let min = arr.iter().ord_subset_min().unwrap(); assert_eq!(&2.0, min); } #[test] fn ord_subset_min_by() { let arr = [2.0, 3.0, 5.0, std::f64::NAN]; let min_by = arr.iter().ord_subset_min_by_key(|num| num.recip()).unwrap(); assert_eq!(&5.0, min_by); } // This is a compile time test. It can't fail at runtime. // The referenced functions must accept iters of values, that are not OrdSubset // if the closure produces OrdSubset values #[allow(unused)] fn ord_subset_min_or_max_by_key() { let array: [NotOrdSub; 0] = []; array.iter().ord_subset_min_by_key(|_| 0.0); array.iter().ord_subset_max_by_key(|_| 0.0); } // ---------------------------slice ext methods -------------------------------- // ----------------------------- stable sorts ---------------------------------- #[test] #[cfg(feature="std")] fn sort() { let mut array = TEST_ARRAY; array.ord_subset_sort(); assert_eq!(&array[0..N_NO_NAN], &SORTED_TEST_ARRAY_NO_NAN); } #[test] #[cfg(feature="std")] fn sort_rev() { let mut array = TEST_ARRAY; array.ord_subset_sort_rev(); let mut rev_sorted_array = SORTED_TEST_ARRAY_NO_NAN; rev_sorted_array.reverse(); assert_eq!(&array[0..N_NO_NAN], &rev_sorted_array); } #[test] #[cfg(feature="std")] fn sort_by_key() { fn key_function(el: &f64) -> f64 { (el - 13.0).recip() } let mut array = TEST_ARRAY; array.ord_subset_sort_by_key(key_function); let mut std_sorted_array = TEST_ARRAY_NO_NAN; std_sorted_array.sort_by_key(|num| OrdVar::new(key_function(num))); assert_eq!(&array[..N_NO_NAN], &std_sorted_array); } // ----------------------------- unstable sorts -------------------------------- #[test] fn sort_unstable() { let mut array = TEST_ARRAY; array.ord_subset_sort_unstable(); assert_eq!(&array[0..N_NO_NAN], &SORTED_TEST_ARRAY_NO_NAN); } #[test] fn sort_unstable_rev() { let mut array = TEST_ARRAY; array.ord_subset_sort_unstable_rev(); let mut rev_sorted_array = SORTED_TEST_ARRAY_NO_NAN; rev_sorted_array.reverse(); assert_eq!(&array[0..N_NO_NAN], &rev_sorted_array); } #[test] fn sort_unstable_by_key() { fn key_function(el: &f64) -> f64 { (el - 13.0).recip() } let mut array = TEST_ARRAY; array.ord_subset_sort_unstable_by_key(key_function); let mut std_sorted_array = TEST_ARRAY_NO_NAN; std_sorted_array.sort_unstable_by_key(|num| OrdVar::new(key_function(num))); assert_eq!(&array[..N_NO_NAN], &std_sorted_array); } // ---------------------------- binary searches -------------------------------- #[test] fn binary_search() { let array = SORTED_TEST_ARRAY; for (i, num) in array.iter().enumerate().take(N_NO_NAN) { assert_eq!(array.ord_subset_binary_search(num), Ok(i)); } } #[test] fn binary_search_rev() { let mut array = TEST_ARRAY; array.ord_subset_sort_unstable_rev(); for (i, num) in array.iter().enumerate().take(N_NO_NAN) { assert_eq!(array.ord_subset_binary_search_rev(num), Ok(i)); } } #[test] fn binary_search_by_key() { fn key_function(el: &f64) -> f64 { (el - 13.0).recip() } let mut array = TEST_ARRAY; array.ord_subset_sort_unstable_by_key(key_function); for num in array.iter().take(N_NO_NAN) { let key = key_function(num); match array.ord_subset_binary_search_by_key(&key, key_function) { Err(_) => panic!("Did not find correct location of element"), Ok(pos) => assert_eq!(key_function(&array[pos]), key), } } } // ------ binary search error cases ------ #[test] fn binary_search_err() { let array = SORTED_TEST_ARRAY; for (i, num) in array.iter() .enumerate() .filter(|&(_, num)| num.is_finite()) { let new_num = num + 0.5; assert_eq!(array.ord_subset_binary_search(&new_num), Err(i+1)); } } #[test] fn binary_search_rev_err() { let mut array = TEST_ARRAY; array.ord_subset_sort_unstable_rev(); for (i, num) in array.iter() .enumerate() .filter(|&(_, num)| num.is_finite()) { let new_num = num + 0.5; assert_eq!(array.ord_subset_binary_search_rev(&new_num), Err(i)); } } #[test] fn binary_search_by_key_err() { fn key_function(el: &f64) -> f64 { (el - 13.0).recip() } let mut array = TEST_ARRAY; array.ord_subset_sort_unstable_by_key(key_function); for num in array.iter().take(N_NO_NAN) { let key_diff = key_function(&(num+0.01))*1.01 + 0.01; let pos = array.ord_subset_binary_search_by_key(&key_diff, key_function); let pos_std = (&array[..N_NO_NAN]).binary_search_by_key( &OrdVar::new(key_diff), |num| OrdVar::new(key_function(num)) ); match (pos, pos_std) { (Err(pos), Err(pos_std)) => assert!(pos == pos_std), // the commented out match branch is also valid behaviour // but this function is supposed to test as many error cases as possible // by choosing key_diff the right way //(Ok(pos), Ok(pos_std)) => { // let key1 = key_function(&array[pos]); // let key2 = key_function(&array[pos_std]); // assert!(key1 == key2); //}, _ => panic!("Inconsistency between this library's and std's binary_search_by_key"), } } } // -------------------- compile time implementation tests ---------------------- // check that slices, arrays and vecs as well as references // all implement the OrdSubsetSliceExt trait, no matter the mutability. #[allow(unused)] fn ord_subset_slice_ext_impl_test() { fn foo + AsRef<[U]>, U: OrdSubset + Clone>(as_slice: T) { // would panic, good thing it doesn't run let element: &U = as_slice.as_ref().first().unwrap(); as_slice.ord_subset_binary_search(element); as_slice.ord_subset_binary_search_rev(element); as_slice.ord_subset_binary_search_by_key(element, |_| element.clone()); as_slice.ord_subset_binary_search_by(|_| std::cmp::Ordering::Equal); } let mut vec: Vec = vec![]; let mut arr: [OrdSub; 0] = []; // &vec foo(&vec); foo(&mut vec); // &array foo(&arr); foo(&mut arr); // &slice foo(&arr[..]); foo(&mut arr[..]); // &&slice foo(&&arr[..]); foo(&mut &mut arr[..]); foo(& &mut arr[..]); // owned foo(vec); foo(arr); } // check that mutable vecs, arrays and slices are all sortable #[allow(unused)] fn ord_subset_mut_slice_ext_impl_test() { fn sortable(mut as_slice: T) where T: OrdSubsetSliceExt + AsMut<[U]>, U: OrdSubset, { #[cfg(feature="std")] as_slice.ord_subset_sort(); #[cfg(feature="std")] as_slice.ord_subset_sort_rev(); #[cfg(feature="std")] as_slice.ord_subset_sort_by(|_, _| core::cmp::Ordering::Equal); #[cfg(feature="std")] as_slice.ord_subset_sort_by_key(|_| 0.0); as_slice.ord_subset_sort_unstable(); as_slice.ord_subset_sort_unstable_rev(); as_slice.ord_subset_sort_unstable_by(|_, _| core::cmp::Ordering::Equal); as_slice.ord_subset_sort_unstable_by_key(|_| 0.0); } let mut vec: Vec = vec![]; let mut arr: [OrdSub; 0] = []; sortable(&mut vec); sortable(&mut arr); sortable(&mut arr[..]); sortable(&mut &mut arr[..]); // owned sortable(vec); sortable(arr); } // check that slices, arrays and vecs as well as references of non-OrdSubset items // all implement the OrdSubsetSliceExt trait and allow binary_search_by_key. #[allow(unused)] fn non_ord_subset_slice_ext_impl_test() { /* fn foo + AsRef<[U]>, U: Clone>(as_slice: T) { // would panic, good thing it doesn't run let element: &U = as_slice.as_ref().first().unwrap(); as_slice.ord_subset_binary_search(element); as_slice.ord_subset_binary_search_rev(element); as_slice.ord_subset_binary_search_by_key(element, |_| element.clone()); as_slice.ord_subset_binary_search_by(|_| std::cmp::Ordering::Equal); } */ fn foo + AsRef<[U]>, U>(as_slice: T) { let key = OrdSub(); as_slice.ord_subset_binary_search_by_key(&key, |_| key); } let mut vec: Vec = vec![]; let mut arr: [NotOrdSub; 0] = []; // &vec foo(&vec); foo(&mut vec); // &array foo(&arr); foo(&mut arr); // &slice foo(&arr[..]); foo(&mut arr[..]); // &&slice foo(&&arr[..]); foo(&mut &mut arr[..]); foo(& &mut arr[..]); // owned foo(vec); foo(arr); } // check that mutable vecs, arrays and slices of non-OrdSubset types are all sortable by key #[allow(unused)] fn non_ord_subset_mut_slice_ext_impl_test() { fn sortable(mut as_slice: T) where T: OrdSubsetSliceExt + AsMut<[U]>, { let key = OrdSub(); #[cfg(feature="std")] as_slice.ord_subset_sort_by_key(|_| key); as_slice.ord_subset_sort_unstable_by_key(|_| key); } let mut vec: Vec = vec![]; let mut arr: [NotOrdSub; 0] = []; sortable(&mut vec); sortable(&mut arr); sortable(&mut arr[..]); sortable(&mut &mut arr[..]); // owned sortable(vec); sortable(arr); } // std-library bug: https://github.com/rust-lang/rust/issues/34683 // caused valid code not to compile due to elided lifetime parameters being too strict // this test is a compile test, it can't fail at runtime #[test] fn binary_search_lifetime() { #[derive(Debug)] struct Foo { property: f32, } let xs = vec![ Foo { property: 1. }, Foo { property: 2. }, Foo { property: 3. }, ]; let _r = xs.ord_subset_binary_search_by_key(&2., |entry| entry.property); } #[cfg(feature="ops")] use core::ops::{Add, Sub, Mul, Div, Rem, //BitAnd, BitOr, BitXor, Shl, Shr, Neg, //Not, AddAssign, SubAssign, MulAssign, DivAssign, RemAssign, //BitAndAssign, BitOrAssign, BitXorAssign, ShlAssign, ShrAssign, }; #[test] #[cfg(feature="ops")] fn ops_correctness_test() { let infix_ops = [ Add::add, Sub::sub, Mul::mul, Div::div, Rem::rem, //BitAnd::bitand, BitOr::bitor, BitXor::bitxor, Shl::shl, Shr::shr ]; let unary_ops = [ Neg::neg, //Not::not ]; let assign_ops = [ AddAssign::add_assign, SubAssign::sub_assign, MulAssign::mul_assign, DivAssign::div_assign, RemAssign::rem_assign, //BitAndAssign::bitand_assign, BitOrAssign::bitor_assign, BitXorAssign::bitxor_assign, //ShlAssign::shl_assign, ShrAssign::shr_assign ]; // same functions but for OrdVar variables let infix_ops_ordvar = [ Add::add, Sub::sub, Mul::mul, Div::div, Rem::rem, //BitAnd::bitand, BitOr::bitor, BitXor::bitxor, Shl::shl, Shr::shr ]; let unary_ops_ordvar = [ Neg::neg, //Not::not ]; let assign_ops_ordvar = [ AddAssign::add_assign, SubAssign::sub_assign, MulAssign::mul_assign, DivAssign::div_assign, RemAssign::rem_assign, //BitAndAssign::bitand_assign, BitOrAssign::bitor_assign, BitXorAssign::bitxor_assign, //ShlAssign::shl_assign, ShrAssign::shr_assign ]; // skip 0, can't divide by it let nums = (-10..0).chain(1..11i32).map(|n| n as f64).collect::>(); let combinations = nums.iter().flat_map(|&n1| nums.iter().map(move |&n2| (n1, n2))); for (num1, num2) in combinations { // infix ops for (op, op_ordvar) in infix_ops.iter().zip(infix_ops_ordvar.iter()) { let res = op(num1, num2); let res2 = op_ordvar(OrdVar::new(num1), num2); //let res2 = op_ordvar(num1, num2); assert!(res == res2.into_inner()) } // unary ops for (op, op_ordvar) in unary_ops.iter().zip(unary_ops_ordvar.iter()) { let res = op(num1); let res2 = op_ordvar(OrdVar::new(num1)); //let res2 = op_ordvar(num1, num2); assert!(res == res2.into_inner()) } // assign ops for (op, op_ordvar) in assign_ops.iter().zip(assign_ops_ordvar.iter()) { let mut num1 = num1; let mut ordvar = OrdVar::new(num1); op(&mut num1, num2); op_ordvar(&mut ordvar, num2); assert!(num1 == ordvar.into_inner()) } } } ord_subset-3.1.1/.cargo_vcs_info.json0000644000000001120000000000000132400ustar00{ "git": { "sha1": "07dbae7146e757d19b1768c80eb6824b904ca965" } }