├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── deploy-docs.sh └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: false 3 | script: 4 | - cargo build 5 | - cargo test 6 | - cargo doc --no-deps 7 | after_success: | 8 | [ $TRAVIS_BRANCH = master ] && 9 | [ $TRAVIS_PULL_REQUEST = false ] && 10 | bash deploy-docs.sh 11 | notifications: 12 | webhooks: http://huon.me:54857/travis 13 | 14 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | 3 | name = "compare" 4 | version = "0.1.0" 5 | license = "MIT/Apache-2.0" 6 | description = "Experimental comparators for collections to be generic over" 7 | 8 | authors = [ 9 | "Alexis Beingessner ", 10 | "Andrew Paseltiner ", 11 | ] 12 | 13 | repository = "https://github.com/contain-rs/compare" 14 | homepage = "https://github.com/contain-rs/compare" 15 | documentation = "https://contain-rs.github.io/compare/compare" 16 | keywords = ["data-structures"] 17 | readme = "README.md" 18 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 The Rust Project Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Experimental comparators for collections to be generic over. 2 | 3 | Documentation is available at https://contain-rs.github.io/compare/compare. 4 | 5 | To use `compare` with Cargo, add this to `Cargo.toml`: 6 | 7 | ```toml 8 | [dependencies] 9 | compare = "0.1" 10 | ``` 11 | 12 | and this to the crate root: 13 | 14 | ```rust 15 | extern crate compare; 16 | ``` 17 | -------------------------------------------------------------------------------- /deploy-docs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -o errexit -o nounset 4 | 5 | rev=$(git rev-parse --short HEAD) 6 | 7 | cd target/doc 8 | 9 | git init 10 | git config user.email 'FlashCat@users.noreply.github.com' 11 | git config user.name 'FlashCat' 12 | git remote add upstream "https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git" 13 | git fetch upstream gh-pages 14 | git reset upstream/gh-pages 15 | 16 | touch . 17 | 18 | git add -A . 19 | git commit -m "rebuild pages at ${rev}" 20 | git push -q upstream HEAD:gh-pages 21 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Comparators. 2 | //! 3 | //! A comparator is any type that implements the [`Compare`](trait.Compare.html) trait, 4 | //! which imposes a [total order](https://en.wikipedia.org/wiki/Total_order). Its 5 | //! [`compare`](trait.Compare.html#tymethod.compare) method accepts two values, which may 6 | //! be of the same type or different types, and returns an ordering on them. 7 | //! 8 | //! Comparators are useful for parameterizing the behavior of sort methods and certain 9 | //! data structures. 10 | //! 11 | //! The most basic comparator is [`Natural`](struct.Natural.html), which simply delegates 12 | //! to the type's implementation of [`Ord`] 13 | //! (http://doc.rust-lang.org/std/cmp/trait.Ord.html): 14 | //! 15 | //! ``` 16 | //! use compare::{Compare, natural}; 17 | //! use std::cmp::Ordering::{Less, Equal, Greater}; 18 | //! 19 | //! let a = &1; 20 | //! let b = &2; 21 | //! 22 | //! let cmp = natural(); 23 | //! assert_eq!(cmp.compare(a, b), Less); 24 | //! assert_eq!(cmp.compare(b, a), Greater); 25 | //! assert_eq!(cmp.compare(a, a), Equal); 26 | //! ``` 27 | //! 28 | //! There are convenience methods for checking each of the six relations: 29 | //! 30 | //! ``` 31 | //! use compare::{Compare, natural}; 32 | //! 33 | //! let a = &1; 34 | //! let b = &2; 35 | //! 36 | //! let cmp = natural(); 37 | //! assert!(cmp.compares_lt(a, b)); 38 | //! assert!(cmp.compares_le(a, b)); 39 | //! assert!(cmp.compares_ge(b, a)); 40 | //! assert!(cmp.compares_gt(b, a)); 41 | //! assert!(cmp.compares_eq(a, a)); 42 | //! assert!(cmp.compares_ne(a, b)); 43 | //! ``` 44 | //! 45 | //! The `Compare` trait also provides default methods that 46 | //! consume a comparator to produce a new one with different behavior, similar to 47 | //! [iterator adaptors](http://doc.rust-lang.org/std/iter/trait.IteratorExt.html). For 48 | //! example, all comparators can be [reversed](trait.Compare.html#method.rev): 49 | //! 50 | //! ``` 51 | //! use compare::{Compare, natural}; 52 | //! use std::cmp::Ordering::Greater; 53 | //! 54 | //! let cmp = natural().rev(); 55 | //! assert_eq!(cmp.compare(&1, &2), Greater); 56 | //! ``` 57 | //! 58 | //! It is possible to implement a comparator that is not based on the natural ordering of 59 | //! a type by using a closure of type `Fn(&L, &R) -> Ordering`. For example, slices 60 | //! can be compared by their length instead of their contents: 61 | //! 62 | //! ``` 63 | //! use compare::Compare; 64 | //! use std::cmp::Ordering::{Less, Greater}; 65 | //! 66 | //! let a = [1, 2, 3]; 67 | //! let b = [4, 5]; 68 | //! 69 | //! let cmp = |l: &[i32], r: &[i32]| l.len().cmp(&r.len()); 70 | //! assert_eq!(cmp.compare(&a, &b), Greater); 71 | //! 72 | //! let cmp = cmp.rev(); 73 | //! assert_eq!(cmp.compare(&a, &b), Less); 74 | //! ``` 75 | //! 76 | //! Comparators can be combined [lexicographically] 77 | //! (https://en.wikipedia.org/wiki/Lexicographical_order) in order to compare values 78 | //! first by one key, [then](trait.Compare.html#method.then), if the first keys were 79 | //! equal, by another: 80 | //! 81 | //! ``` 82 | //! use compare::Compare; 83 | //! use std::cmp::Ordering::{Less, Equal, Greater}; 84 | //! 85 | //! struct Pet { name: &'static str, age: u8 } 86 | //! 87 | //! let fido4 = &Pet { name: "Fido", age: 4 }; 88 | //! let ruff2 = &Pet { name: "Ruff", age: 2 }; 89 | //! let fido3 = &Pet { name: "Fido", age: 3 }; 90 | //! 91 | //! let name_cmp = |l: &Pet, r: &Pet| l.name.cmp(r.name); 92 | //! assert_eq!(name_cmp.compare(fido4, ruff2), Less); 93 | //! assert_eq!(name_cmp.compare(fido4, fido3), Equal); 94 | //! assert_eq!(name_cmp.compare(ruff2, fido3), Greater); 95 | //! 96 | //! let age_cmp = |l: &Pet, r: &Pet| l.age.cmp(&r.age); 97 | //! assert_eq!(age_cmp.compare(fido4, ruff2), Greater); 98 | //! assert_eq!(age_cmp.compare(fido4, fido3), Greater); 99 | //! assert_eq!(age_cmp.compare(ruff2, fido3), Less); 100 | //! 101 | //! let name_age_cmp = name_cmp.then(age_cmp); 102 | //! assert_eq!(name_age_cmp.compare(fido4, ruff2), Less); 103 | //! assert_eq!(name_age_cmp.compare(fido4, fido3), Greater); 104 | //! assert_eq!(name_age_cmp.compare(ruff2, fido3), Greater); 105 | //! ``` 106 | //! 107 | //! It is often repetitive to compare two values of the same type by the same key, so the 108 | //! [key-extraction logic](struct.Extract.html) can be factored out, simplifying the 109 | //! previous example: 110 | //! 111 | //! ``` 112 | //! use compare::{Compare, Extract}; 113 | //! use std::cmp::Ordering::{Less, Greater}; 114 | //! 115 | //! struct Pet { name: &'static str, age: u8 } 116 | //! 117 | //! let fido4 = &Pet { name: "Fido", age: 4 }; 118 | //! let ruff2 = &Pet { name: "Ruff", age: 2 }; 119 | //! let fido3 = &Pet { name: "Fido", age: 3 }; 120 | //! 121 | //! let name_age_cmp = Extract::new(|p: &Pet| p.name) 122 | //! .then(Extract::new(|p: &Pet| p.age)); 123 | //! 124 | //! assert_eq!(name_age_cmp.compare(fido4, ruff2), Less); 125 | //! assert_eq!(name_age_cmp.compare(fido4, fido3), Greater); 126 | //! assert_eq!(name_age_cmp.compare(ruff2, fido3), Greater); 127 | //! ``` 128 | 129 | #![no_std] 130 | 131 | use core::borrow::Borrow; 132 | use core::cmp::Ordering::{self, Less, Equal, Greater}; 133 | use core::default::Default; 134 | use core::marker::PhantomData; 135 | use core::fmt::{self, Debug}; 136 | 137 | /// Returns the maximum of two values according to the given comparator, or `r` if they 138 | /// are equal. 139 | /// 140 | /// # Examples 141 | /// 142 | /// ``` 143 | /// use compare::{Extract, max}; 144 | /// 145 | /// struct Foo { key: char, id: u8 } 146 | /// 147 | /// let f1 = &Foo { key: 'a', id: 1}; 148 | /// let f2 = &Foo { key: 'a', id: 2}; 149 | /// let f3 = &Foo { key: 'b', id: 3}; 150 | /// 151 | /// let cmp = Extract::new(|f: &Foo| f.key); 152 | /// assert_eq!(max(&cmp, f1, f2).id, f2.id); 153 | /// assert_eq!(max(&cmp, f1, f3).id, f3.id); 154 | /// ``` 155 | // FIXME: convert to default method on `Compare` once where clauses permit equality 156 | // (https://github.com/rust-lang/rust/issues/20041) 157 | pub fn max<'a, C: ?Sized, T: ?Sized>(cmp: &C, l: &'a T, r: &'a T) -> &'a T 158 | where C: Compare { 159 | 160 | if cmp.compares_ge(r, l) { r } else { l } 161 | } 162 | 163 | /// Returns the minimum of two values according to the given comparator, or `l` if they 164 | /// are equal. 165 | /// 166 | /// # Examples 167 | /// 168 | /// ``` 169 | /// use compare::{Extract, min}; 170 | /// 171 | /// struct Foo { key: char, id: u8 } 172 | /// 173 | /// let f1 = &Foo { key: 'b', id: 1}; 174 | /// let f2 = &Foo { key: 'b', id: 2}; 175 | /// let f3 = &Foo { key: 'a', id: 3}; 176 | /// 177 | /// let cmp = Extract::new(|f: &Foo| f.key); 178 | /// assert_eq!(min(&cmp, f1, f2).id, f1.id); 179 | /// assert_eq!(min(&cmp, f1, f3).id, f3.id); 180 | /// ``` 181 | // FIXME: convert to default method on `Compare` once where clauses permit equality 182 | // (https://github.com/rust-lang/rust/issues/20041) 183 | pub fn min<'a, C: ?Sized, T: ?Sized>(cmp: &C, l: &'a T, r: &'a T) -> &'a T 184 | where C: Compare { 185 | 186 | if cmp.compares_le(l, r) { l } else { r } 187 | } 188 | 189 | /// A comparator imposing a [total order](https://en.wikipedia.org/wiki/Total_order). 190 | /// 191 | /// See the [`compare` module's documentation](index.html) for detailed usage. 192 | /// 193 | /// The `compares_*` methods may be overridden to provide more efficient implementations. 194 | pub trait Compare { 195 | /// Compares two values, returning `Less`, `Equal`, or `Greater` if `l` is less 196 | /// than, equal to, or greater than `r`, respectively. 197 | fn compare(&self, l: &L, r: &R) -> Ordering; 198 | 199 | /// Checks if `l` is less than `r`. 200 | fn compares_lt(&self, l: &L, r: &R) -> bool { self.compare(l, r) == Less } 201 | 202 | /// Checks if `l` is less than or equal to `r`. 203 | fn compares_le(&self, l: &L, r: &R) -> bool { self.compare(l, r) != Greater } 204 | 205 | /// Checks if `l` is greater than or equal to `r`. 206 | fn compares_ge(&self, l: &L, r: &R) -> bool { self.compare(l, r) != Less } 207 | 208 | /// Checks if `l` is greater than `r`. 209 | fn compares_gt(&self, l: &L, r: &R) -> bool { self.compare(l, r) == Greater } 210 | 211 | /// Checks if `l` is equal to `r`. 212 | fn compares_eq(&self, l: &L, r: &R) -> bool { self.compare(l, r) == Equal } 213 | 214 | /// Checks if `l` is not equal to `r`. 215 | fn compares_ne(&self, l: &L, r: &R) -> bool { self.compare(l, r) != Equal } 216 | 217 | /// Borrows the comparator's parameters before comparing them. 218 | /// 219 | /// # Examples 220 | /// 221 | /// ``` 222 | /// use compare::{Compare, natural}; 223 | /// use std::cmp::Ordering::{Less, Equal, Greater}; 224 | /// 225 | /// let a_str = "a"; 226 | /// let a_string = a_str.to_string(); 227 | /// 228 | /// let b_str = "b"; 229 | /// let b_string = b_str.to_string(); 230 | /// 231 | /// let cmp = natural().borrowing(); 232 | /// assert_eq!(cmp.compare(a_str, &a_string), Equal); 233 | /// assert_eq!(cmp.compare(a_str, b_str), Less); 234 | /// assert_eq!(cmp.compare(&b_string, a_str), Greater); 235 | /// ``` 236 | fn borrowing(self) -> Borrowing where Self: Sized { Borrowing(self, PhantomData) } 237 | 238 | /// Reverses the ordering of the comparator. 239 | /// 240 | /// # Examples 241 | /// 242 | /// ``` 243 | /// use compare::{Compare, natural}; 244 | /// use std::cmp::Ordering::{Less, Equal, Greater}; 245 | /// 246 | /// let a = &1; 247 | /// let b = &2; 248 | /// 249 | /// let cmp = natural().rev(); 250 | /// assert_eq!(cmp.compare(a, b), Greater); 251 | /// assert_eq!(cmp.compare(b, a), Less); 252 | /// assert_eq!(cmp.compare(a, a), Equal); 253 | /// ``` 254 | fn rev(self) -> Rev where Self: Sized { Rev(self) } 255 | 256 | /// Swaps the comparator's parameters, maintaining the underlying ordering. 257 | /// 258 | /// This is useful for providing a comparator `C: Compare` in a context that 259 | /// expects `C: Compare`. 260 | /// 261 | /// # Examples 262 | /// 263 | /// ``` 264 | /// use compare::Compare; 265 | /// use std::cmp::Ordering::{Less, Equal, Greater}; 266 | /// 267 | /// let cmp = |l: &u8, r: &u16| (*l as u16).cmp(r); 268 | /// assert_eq!(cmp.compare(&1u8, &2u16), Less); 269 | /// assert_eq!(cmp.compare(&2u8, &1u16), Greater); 270 | /// assert_eq!(cmp.compare(&1u8, &1u16), Equal); 271 | /// 272 | /// let cmp = cmp.swap(); 273 | /// assert_eq!(cmp.compare(&2u16, &1u8), Less); 274 | /// assert_eq!(cmp.compare(&1u16, &2u8), Greater); 275 | /// assert_eq!(cmp.compare(&1u16, &1u8), Equal); 276 | /// ``` 277 | fn swap(self) -> Swap where Self: Sized { Swap(self) } 278 | 279 | /// [Lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) combines 280 | /// the comparator with another. 281 | /// 282 | /// The retuned comparator compares values first using `self`, then, if they are 283 | /// equal, using `then`. 284 | /// 285 | /// # Examples 286 | /// 287 | /// ``` 288 | /// use compare::{Compare, Extract}; 289 | /// use std::cmp::Ordering::{Less, Equal}; 290 | /// 291 | /// struct Foo { key1: char, key2: u8 } 292 | /// 293 | /// let f1 = &Foo { key1: 'a', key2: 2}; 294 | /// let f2 = &Foo { key1: 'a', key2: 3}; 295 | /// 296 | /// let cmp = Extract::new(|foo: &Foo| foo.key1); 297 | /// assert_eq!(cmp.compare(f1, f2), Equal); 298 | /// 299 | /// let cmp = cmp.then(Extract::new(|foo: &Foo| foo.key2)); 300 | /// assert_eq!(cmp.compare(f1, f2), Less); 301 | /// ``` 302 | fn then(self, then: D) -> Then where D: Compare, Self: Sized { 303 | Then(self, then) 304 | } 305 | } 306 | 307 | impl Compare for F 308 | where F: Fn(&L, &R) -> Ordering { 309 | 310 | fn compare(&self, l: &L, r: &R) -> Ordering { (*self)(l, r) } 311 | } 312 | 313 | /// A comparator that borrows its parameters before comparing them. 314 | /// 315 | /// See [`Compare::borrow`](trait.Compare.html#method.borrow) for an example. 316 | pub struct Borrowing(C, PhantomData) 317 | where C: Compare; 318 | 319 | impl Compare for Borrowing 320 | where C: Compare, L: Borrow, R: Borrow { 321 | 322 | fn compare(&self, l: &L, r: &R) -> Ordering { self.0.compare(l.borrow(), r.borrow()) } 323 | fn compares_lt(&self, l: &L, r: &R) -> bool { self.0.compares_lt(l.borrow(), r.borrow()) } 324 | fn compares_le(&self, l: &L, r: &R) -> bool { self.0.compares_le(l.borrow(), r.borrow()) } 325 | fn compares_ge(&self, l: &L, r: &R) -> bool { self.0.compares_ge(l.borrow(), r.borrow()) } 326 | fn compares_gt(&self, l: &L, r: &R) -> bool { self.0.compares_gt(l.borrow(), r.borrow()) } 327 | fn compares_eq(&self, l: &L, r: &R) -> bool { self.0.compares_eq(l.borrow(), r.borrow()) } 328 | fn compares_ne(&self, l: &L, r: &R) -> bool { self.0.compares_ne(l.borrow(), r.borrow()) } 329 | } 330 | 331 | impl Clone for Borrowing 332 | where C: Compare + Clone { 333 | 334 | fn clone(&self) -> Self { Borrowing(self.0.clone(), PhantomData) } 335 | } 336 | 337 | impl Copy for Borrowing 338 | where C: Compare + Copy {} 339 | 340 | impl Default for Borrowing 341 | where C: Compare + Default { 342 | 343 | fn default() -> Self { Borrowing(Default::default(), PhantomData) } 344 | } 345 | 346 | impl PartialEq for Borrowing 347 | where C: Compare + PartialEq { 348 | 349 | fn eq(&self, other: &Self) -> bool { self.0 == other.0 } 350 | } 351 | 352 | impl Eq for Borrowing where C: Compare + Eq {} 353 | 354 | impl Debug for Borrowing 355 | where C: Compare + Debug { 356 | 357 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Borrowing({:?})", self.0) } 358 | } 359 | 360 | /// A comparator that extracts a sort key from a value. 361 | /// 362 | /// # Examples 363 | /// 364 | /// ``` 365 | /// use compare::{Compare, Extract}; 366 | /// use std::cmp::Ordering::Greater; 367 | /// 368 | /// let a = [1, 2, 3]; 369 | /// let b = [4, 5]; 370 | /// 371 | /// let cmp = Extract::new(|s: &[i32]| s.len()); 372 | /// assert_eq!(cmp.compare(&a, &b), Greater); 373 | /// ``` 374 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] 375 | pub struct Extract { 376 | ext: E, 377 | cmp: C, 378 | } 379 | 380 | impl Extract> where K: Ord { 381 | /// Returns a comparator that extracts a sort key using `ext` and compares it according to its 382 | /// natural ordering. 383 | pub fn new(ext: E) -> Self where E: Fn(&T) -> K { 384 | Extract { ext: ext, cmp: natural() } 385 | } 386 | } 387 | 388 | // FIXME: convert to default method on `Compare` once where clauses permit equality 389 | // (https://github.com/rust-lang/rust/issues/20041) 390 | impl Extract { 391 | /// Returns a comparator that extracts a sort key using `ext` and compares it using 392 | /// `cmp`. 393 | pub fn with_cmp(ext: E, cmp: C) -> Self 394 | where E: Fn(&T) -> K, C: Compare { Extract { ext: ext, cmp: cmp } } 395 | } 396 | 397 | impl Compare for Extract where E: Fn(&T) -> K, C: Compare { 398 | fn compare(&self, l: &T, r: &T) -> Ordering { 399 | self.cmp.compare(&(self.ext)(l), &(self.ext)(r)) 400 | } 401 | 402 | fn compares_lt(&self, l: &T, r: &T) -> bool { 403 | self.cmp.compares_lt(&(self.ext)(l), &(self.ext)(r)) 404 | } 405 | 406 | fn compares_le(&self, l: &T, r: &T) -> bool { 407 | self.cmp.compares_le(&(self.ext)(l), &(self.ext)(r)) 408 | } 409 | 410 | fn compares_ge(&self, l: &T, r: &T) -> bool { 411 | self.cmp.compares_ge(&(self.ext)(l), &(self.ext)(r)) 412 | } 413 | 414 | fn compares_gt(&self, l: &T, r: &T) -> bool { 415 | self.cmp.compares_gt(&(self.ext)(l), &(self.ext)(r)) 416 | } 417 | 418 | fn compares_eq(&self, l: &T, r: &T) -> bool { 419 | self.cmp.compares_eq(&(self.ext)(l), &(self.ext)(r)) 420 | } 421 | 422 | fn compares_ne(&self, l: &T, r: &T) -> bool { 423 | self.cmp.compares_ne(&(self.ext)(l), &(self.ext)(r)) 424 | } 425 | } 426 | 427 | /// A comparator that [lexicographically] 428 | /// (https://en.wikipedia.org/wiki/Lexicographical_order) combines two others. 429 | /// 430 | /// See [`Compare::then`](trait.Compare.html#method.then) for an example. 431 | #[derive(Clone, Copy, Default, PartialEq, Eq, Debug)] 432 | pub struct Then(C, D); 433 | 434 | impl Compare for Then 435 | where C: Compare, D: Compare { 436 | 437 | fn compare(&self, l: &L, r: &R) -> Ordering { 438 | match self.0.compare(l, r) { 439 | Equal => self.1.compare(l, r), 440 | order => order, 441 | } 442 | } 443 | } 444 | 445 | /// A comparator that delegates to [`Ord`] 446 | /// (http://doc.rust-lang.org/std/cmp/trait.Ord.html). 447 | /// 448 | /// # Examples 449 | /// 450 | /// ``` 451 | /// use compare::{Compare, natural}; 452 | /// use std::cmp::Ordering::{Less, Equal, Greater}; 453 | /// 454 | /// let a = &1; 455 | /// let b = &2; 456 | /// 457 | /// let cmp = natural(); 458 | /// assert_eq!(cmp.compare(a, b), Less); 459 | /// assert_eq!(cmp.compare(b, a), Greater); 460 | /// assert_eq!(cmp.compare(a, a), Equal); 461 | /// ``` 462 | pub struct Natural(PhantomData); 463 | 464 | /// Returns a comparator that delegates to `Ord`. 465 | pub fn natural() -> Natural { Natural(PhantomData) } 466 | 467 | impl Compare for Natural { 468 | fn compare(&self, l: &T, r: &T) -> Ordering { Ord::cmp(l, r) } 469 | fn compares_lt(&self, l: &T, r: &T) -> bool { PartialOrd::lt(l, r) } 470 | fn compares_le(&self, l: &T, r: &T) -> bool { PartialOrd::le(l, r) } 471 | fn compares_ge(&self, l: &T, r: &T) -> bool { PartialOrd::ge(l, r) } 472 | fn compares_gt(&self, l: &T, r: &T) -> bool { PartialOrd::gt(l, r) } 473 | fn compares_eq(&self, l: &T, r: &T) -> bool { PartialEq::eq(l, r) } 474 | fn compares_ne(&self, l: &T, r: &T) -> bool { PartialEq::ne(l, r) } 475 | } 476 | 477 | impl Clone for Natural { 478 | fn clone(&self) -> Self { *self } 479 | } 480 | 481 | impl Copy for Natural {} 482 | 483 | impl Default for Natural { 484 | fn default() -> Self { natural() } 485 | } 486 | 487 | impl PartialEq for Natural { 488 | fn eq(&self, _other: &Self) -> bool { true } 489 | } 490 | 491 | impl Eq for Natural {} 492 | 493 | impl Debug for Natural { 494 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Natural") } 495 | } 496 | 497 | /// A comparator that reverses the ordering of another. 498 | /// 499 | /// See [`Compare::rev`](trait.Compare.html#method.rev) for an example. 500 | #[derive(Clone, Copy, Default, PartialEq, Eq, Debug)] 501 | pub struct Rev(C); 502 | 503 | impl Compare for Rev where C: Compare { 504 | fn compare(&self, l: &L, r: &R) -> Ordering { self.0.compare(l, r).reverse() } 505 | fn compares_lt(&self, l: &L, r: &R) -> bool { self.0.compares_gt(l, r) } 506 | fn compares_le(&self, l: &L, r: &R) -> bool { self.0.compares_ge(l, r) } 507 | fn compares_ge(&self, l: &L, r: &R) -> bool { self.0.compares_le(l, r) } 508 | fn compares_gt(&self, l: &L, r: &R) -> bool { self.0.compares_lt(l, r) } 509 | fn compares_eq(&self, l: &L, r: &R) -> bool { self.0.compares_eq(l, r) } 510 | fn compares_ne(&self, l: &L, r: &R) -> bool { self.0.compares_ne(l, r) } 511 | } 512 | 513 | /// A comparator that swaps another's parameters, maintaining the underlying ordering. 514 | /// 515 | /// This is useful for providing a comparator `C: Compare` in a context that 516 | /// expects `C: Compare`. 517 | /// 518 | /// See [`Compare::swap`](trait.Compare.html#method.swap) for an example. 519 | #[derive(Clone, Copy, Default, PartialEq, Eq, Debug)] 520 | pub struct Swap(C); 521 | 522 | impl Compare for Swap 523 | where C: Compare { 524 | 525 | fn compare(&self, r: &R, l: &L) -> Ordering { self.0.compare(l, r) } 526 | fn compares_lt(&self, r: &R, l: &L) -> bool { self.0.compares_lt(l, r) } 527 | fn compares_le(&self, r: &R, l: &L) -> bool { self.0.compares_le(l, r) } 528 | fn compares_ge(&self, r: &R, l: &L) -> bool { self.0.compares_ge(l, r) } 529 | fn compares_gt(&self, r: &R, l: &L) -> bool { self.0.compares_gt(l, r) } 530 | fn compares_eq(&self, r: &R, l: &L) -> bool { self.0.compares_eq(l, r) } 531 | fn compares_ne(&self, r: &R, l: &L) -> bool { self.0.compares_ne(l, r) } 532 | } 533 | --------------------------------------------------------------------------------