├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── example_error.png └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | /Cargo.lock 3 | /.idea 4 | tarpaulin-report.html 5 | **/*.rs.bk 6 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "assert_unordered" 3 | version = "0.3.5" 4 | authors = ["Scott Meeuwsen "] 5 | license = "MIT OR Apache-2.0" 6 | description = "A direct replacement for `assert_eq` for unordered collections" 7 | repository = "https://github.com/nu11ptr/assert_unordered" 8 | documentation = "https://docs.rs/assert_unordered" 9 | keywords = ["testing", "assert", "assertion", "diff"] 10 | categories = ["development-tools::testing", "no-std", "rust-patterns"] 11 | readme = "README.md" 12 | edition = "2021" 13 | 14 | [package.metadata.docs.rs] 15 | all-features = true 16 | rustdoc-args = ["--cfg", "docsrs"] 17 | 18 | [features] 19 | color = ["ansi_term", "std"] 20 | default = ["color"] 21 | std = [] 22 | 23 | [dependencies] 24 | ansi_term = { version = "0.12", optional = true } 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # assert_unordered 2 | 3 | [![Crate](https://img.shields.io/crates/v/assert_unordered)](https://crates.io/crates/assert_unordered) 4 | [![Docs](https://docs.rs/assert_unordered/badge.svg)](https://docs.rs/assert_unordered) 5 | 6 | A direct replacement for `assert_eq` for unordered collections 7 | 8 | This macro is useful for any situation where the ordering of the collection doesn't matter, even 9 | if they are always in the same order. This is because the stdlib `assert_eq` shows the entire 10 | collection for both left and right and leaves it up to the user to visually scan for differences. 11 | In contrast, this crate only works with collections (types that implement `IntoIterator`) and 12 | therefore can show only the differences (see below for an example of what the output looks like). 13 | 14 | NOTE: As of 0.3.2, the output by default is in color similar to `pretty_assertions` 15 | 16 | ## Usage 17 | 18 | NOTE: `no-default-features` can be used to disable color output (and enable `no-std` support) 19 | 20 | ```toml 21 | [dev-dependencies] 22 | assert_unordered = "0.3" 23 | ``` 24 | 25 | # Which Macro? 26 | 27 | TLDR; - favor `assert_eq_unordered_sort` unless the trait requirements can't be met 28 | 29 | * [assert_eq_unordered](https://docs.rs/assert_unordered/latest/assert_unordered/macro.assert_eq_unordered.html) 30 | * Requires only `Debug` and `PartialEq` on the elements 31 | * Collection level equality check, and if unequal, falls back to item by item compare (O(n^2)) 32 | * [assert_eq_unordered_sort](https://docs.rs/assert_unordered/latest/assert_unordered/macro.assert_eq_unordered_sort.html) 33 | * Requires `Debug`, `Eq` and `Ord` on the elements 34 | * Collection level equality check, and if unequal, sorts and then compares again, 35 | and if still unequal, falls back to item by item compare (O(n^2)) 36 | 37 | 38 | ## Example 39 | ```rust, should_panic 40 | use assert_unordered::assert_eq_unordered; 41 | 42 | #[derive(Debug, PartialEq)] 43 | struct MyType(i32); 44 | 45 | fn main() { 46 | let expected = vec![MyType(1), MyType(2), MyType(4), MyType(5)]; 47 | let actual = vec![MyType(2), MyType(0), MyType(4)]; 48 | 49 | assert_eq_unordered!(expected, actual); 50 | } 51 | ``` 52 | 53 | Output: 54 | 55 | ![example_error](example_error.png) 56 | 57 | ## License 58 | 59 | This project is licensed optionally under either: 60 | 61 | * Apache License, Version 2.0, (LICENSE-APACHE 62 | or https://www.apache.org/licenses/LICENSE-2.0) 63 | * MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT) 64 | -------------------------------------------------------------------------------- /example_error.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nu11ptr/assert_unordered/dc35c752c44837356a57c0fbced837174b86d686/example_error.png -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A direct replacement for `assert_eq` for unordered collections 2 | //! 3 | //! This macro is useful for any situation where the ordering of the collection doesn't matter, even 4 | //! if they are always in the same order. This is because the stdlib `assert_eq` shows the entire 5 | //! collection for both left and right and leaves it up to the user to visually scan for differences. 6 | //! In contrast, this crate only works with collections (types that implement `IntoIterator`) and 7 | //! therefore can show only the differences (see below for an example of what the output looks like). 8 | //! 9 | //! # Which Macro? 10 | //! 11 | //! TLDR; - favor `assert_eq_unordered_sort` unless the trait requirements can't be met 12 | //! 13 | //! * [assert_eq_unordered] 14 | //! * Requires only `Debug` and `PartialEq` on the elements 15 | //! * Collection level equality check, and if unequal, falls back to item by item compare (O(n^2)) 16 | //! * [assert_eq_unordered_sort] 17 | //! * Requires `Debug`, `Eq` and `Ord` on the elements 18 | //! * Collection level equality check, and if unequal, sorts and then compares again, 19 | //! and if still unequal, falls back to item by item compare (O(n^2)) 20 | 21 | //! 22 | //! # Example 23 | //! ```should_panic 24 | //! use assert_unordered::assert_eq_unordered; 25 | //! 26 | //! #[derive(Debug, PartialEq)] 27 | //! struct MyType(i32); 28 | //! 29 | //! let expected = vec![MyType(1), MyType(2), MyType(4), MyType(5)]; 30 | //! let actual = vec![MyType(2), MyType(0), MyType(4)]; 31 | //! 32 | //! assert_eq_unordered!(expected, actual); 33 | //! ``` 34 | //! 35 | //! Output: 36 | //! 37 | //! ![example_error](https://raw.githubusercontent.com/nu11ptr/assert_unordered/master/example_error.png) 38 | 39 | #![cfg_attr(not(feature = "std"), no_std)] 40 | #![cfg_attr(docsrs, feature(doc_cfg))] 41 | #![warn(missing_docs)] 42 | 43 | // Trick to test README samples (from: https://github.com/rust-lang/cargo/issues/383#issuecomment-720873790) 44 | #[cfg(doctest)] 45 | mod test_readme { 46 | macro_rules! external_doc_test { 47 | ($x:expr) => { 48 | #[doc = $x] 49 | extern "C" {} 50 | }; 51 | } 52 | 53 | external_doc_test!(include_str!("../README.md")); 54 | } 55 | 56 | extern crate alloc; 57 | extern crate core; 58 | 59 | use alloc::format; 60 | use alloc::string::String; 61 | use alloc::vec::Vec; 62 | use core::fmt::{Arguments, Debug}; 63 | #[cfg(feature = "color")] 64 | #[cfg(windows)] 65 | use std::sync::Once; 66 | 67 | #[cfg(feature = "color")] 68 | #[cfg(windows)] 69 | static INIT_COLOR: Once = Once::new(); 70 | 71 | #[cfg(feature = "color")] 72 | #[cfg(windows)] 73 | static mut COLOR_ENABLED: bool = false; 74 | 75 | /// Assert that `$left` and `$right` are "unordered" equal. That is, they contain the same elements, 76 | /// but not necessarily in the same order. If this assertion is false, a panic is raised, and the 77 | /// elements that are different between `$left` and `$right` are shown (when possible). 78 | /// 79 | /// Both `$left` and `$right` must be of the same type and implement [PartialEq] and [Iterator] or 80 | /// [IntoIterator], but otherwise can be any type. The iterator `Item` type can be any type that 81 | /// implements [Debug] and [PartialEq]. Optional `$arg` parameters may be given to customize the 82 | /// error message, if any (these are the same as the parameters passed to [format!]). 83 | /// 84 | /// # Efficiency 85 | /// If `$left` and `$right` are equal, this assertion is quite efficient just doing a regular equality 86 | /// check and then returning. If they are not equal, `$left` and `$right` are collected into a [Vec] 87 | /// and the elements compared one by one for both `$left` and `$right` (meaning it is at least 88 | /// O(n^2) algorithmic complexity in the non-equality path). 89 | /// 90 | /// # Example 91 | /// ```should_panic 92 | /// use assert_unordered::assert_eq_unordered; 93 | /// 94 | /// #[derive(Debug, PartialEq)] 95 | /// struct MyType(i32); 96 | /// 97 | /// let expected = vec![MyType(1), MyType(2), MyType(4), MyType(5)]; 98 | /// let actual = vec![MyType(2), MyType(0), MyType(4)]; 99 | /// 100 | /// assert_eq_unordered!(expected, actual); 101 | /// ``` 102 | /// 103 | /// Output: 104 | /// 105 | /// ![example_error](https://raw.githubusercontent.com/nu11ptr/assert_unordered/master/example_error.png) 106 | #[macro_export] 107 | macro_rules! assert_eq_unordered { 108 | ($left:expr, $right:expr $(,)?) => { 109 | $crate::pass_or_panic($crate::compare_unordered($left, $right), core::option::Option::None); 110 | }; 111 | ($left:expr, $right:expr, $($arg:tt)+) => { 112 | $crate::pass_or_panic( 113 | $crate::compare_unordered($left, $right), 114 | core::option::Option::Some(core::format_args!($($arg)+)) 115 | ); 116 | }; 117 | } 118 | 119 | /// Assert that `$left` and `$right` are "unordered" equal. That is, they contain the same elements, 120 | /// but not necessarily in the same order. If this assertion is false, a panic is raised, and the 121 | /// elements that are different between `$left` and `$right` are shown (when possible). 122 | /// 123 | /// Both `$left` and `$right` must be of the same type and implement [PartialEq] and [Iterator] or 124 | /// [IntoIterator], but otherwise can be any type. The iterator `Item` type can be any type that 125 | /// implements [Debug], [Ord], and [Eq]. Optional `$arg` parameters may be given to customize the 126 | /// error message, if any (these are the same as the parameters passed to [format!]). 127 | /// 128 | /// # Efficiency 129 | /// If `$left` and `$right` are equal, this assertion is quite efficient just doing a regular equality 130 | /// check and then returning. If they are not equal, `$left` and `$right` are sorted and compared again. 131 | /// If still not equal, the elements compared one by one for both `$left` and `$right` (meaning it 132 | /// is at least O(n^2) algorithmic complexity, if not equal by this point). 133 | /// 134 | /// # Example 135 | /// ```should_panic 136 | /// use assert_unordered::assert_eq_unordered_sort; 137 | /// 138 | /// #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] 139 | /// struct MyType(i32); 140 | /// 141 | /// let expected = vec![MyType(1), MyType(2), MyType(4), MyType(5)]; 142 | /// let actual = vec![MyType(2), MyType(0), MyType(4)]; 143 | /// 144 | /// assert_eq_unordered_sort!(expected, actual); 145 | /// ``` 146 | /// 147 | /// Output: 148 | /// 149 | /// ![example_error](https://raw.githubusercontent.com/nu11ptr/assert_unordered/master/example_error.png) 150 | #[macro_export] 151 | macro_rules! assert_eq_unordered_sort { 152 | ($left:expr, $right:expr $(,)?) => { 153 | $crate::pass_or_panic($crate::compare_unordered_sort($left, $right), core::option::Option::None); 154 | }; 155 | ($left:expr, $right:expr, $($arg:tt)+) => { 156 | $crate::pass_or_panic( 157 | $crate::compare_unordered_sort($left, $right), 158 | core::option::Option::Some(core::format_args!($($arg)+)) 159 | ); 160 | }; 161 | } 162 | 163 | #[cfg(feature = "color")] 164 | #[cfg(windows)] 165 | #[inline] 166 | fn init_color() -> bool { 167 | // SAFETY: This is the example given in stdlib docs for how to init a mutable static var 168 | unsafe { 169 | INIT_COLOR.call_once(|| { 170 | COLOR_ENABLED = ansi_term::enable_ansi_support().is_ok(); 171 | }); 172 | COLOR_ENABLED 173 | } 174 | } 175 | 176 | #[cfg(feature = "color")] 177 | #[cfg(not(windows))] 178 | #[inline] 179 | const fn init_color() -> bool { 180 | true 181 | } 182 | 183 | #[doc(hidden)] 184 | pub enum CompareResult { 185 | Equal, 186 | NotEqualDiffElements(String, String, String), 187 | } 188 | 189 | #[cfg(feature = "color")] 190 | #[doc(hidden)] 191 | #[inline] 192 | pub fn pass_or_panic(result: CompareResult, msg: Option) { 193 | if init_color() { 194 | color_pass_or_panic(result, msg) 195 | } else { 196 | plain_pass_or_panic(result, msg); 197 | } 198 | } 199 | 200 | #[cfg(not(feature = "color"))] 201 | #[doc(hidden)] 202 | #[inline] 203 | pub fn pass_or_panic(result: CompareResult, msg: Option) { 204 | plain_pass_or_panic(result, msg); 205 | } 206 | 207 | #[cfg(feature = "color")] 208 | fn color_pass_or_panic(result: CompareResult, msg: Option) { 209 | match result { 210 | CompareResult::NotEqualDiffElements(in_both, in_left_not_right, in_right_not_left) => { 211 | use ansi_term::Color::{Green, Red, Yellow}; 212 | 213 | let msg = match msg { 214 | Some(msg) => msg.to_string(), 215 | None => { 216 | format!( 217 | "The {} did not contain the {} as the {}", 218 | Red.paint("left"), 219 | Yellow.paint("same items"), 220 | Green.paint("right"), 221 | ) 222 | } 223 | }; 224 | 225 | let both = Yellow.paint(format!("In both: {in_both}")); 226 | let left = Red.paint(format!("In left: {in_left_not_right}")); 227 | let right = Green.paint(format!("In right: {in_right_not_left}")); 228 | 229 | panic!("{msg}:\n{both}\n{left}\n{right}\n"); 230 | } 231 | CompareResult::Equal => {} 232 | } 233 | } 234 | 235 | fn plain_pass_or_panic(result: CompareResult, msg: Option) { 236 | match result { 237 | CompareResult::NotEqualDiffElements(in_both, in_left_not_right, in_right_not_left) => { 238 | let msg = match msg { 239 | Some(msg) => msg, 240 | // TODO: 1.60 `format_args` not yet stable on 'const fn'. Maybe soon? 241 | None => format_args!("The left did not contain the same items as the right"), 242 | }; 243 | 244 | panic!( 245 | "{msg}:\nIn both: {in_both}\nIn left: {in_left_not_right}\nIn right: {in_right_not_left}" 246 | ); 247 | } 248 | CompareResult::Equal => {} 249 | } 250 | } 251 | 252 | fn compare_elem_by_elem(left: I, right: Vec) -> CompareResult 253 | where 254 | I: IntoIterator + PartialEq, 255 | T: Debug + PartialEq, 256 | { 257 | let mut in_right_not_left: Vec<_> = right; 258 | let mut in_left_not_right = Vec::new(); 259 | // Optimistically assume we likely got it close to right 260 | let mut in_both = Vec::with_capacity(in_right_not_left.len()); 261 | 262 | for elem1 in left { 263 | match in_right_not_left.iter().position(|elem2| &elem1 == elem2) { 264 | Some(idx) => { 265 | in_both.push(elem1); 266 | in_right_not_left.remove(idx); 267 | } 268 | None => { 269 | in_left_not_right.push(elem1); 270 | } 271 | } 272 | } 273 | 274 | if !in_left_not_right.is_empty() || !in_right_not_left.is_empty() { 275 | CompareResult::NotEqualDiffElements( 276 | format!("{in_both:#?}"), 277 | format!("{in_left_not_right:#?}"), 278 | format!("{in_right_not_left:#?}"), 279 | ) 280 | } else { 281 | CompareResult::Equal 282 | } 283 | } 284 | 285 | #[doc(hidden)] 286 | pub fn compare_unordered(left: I, right: I) -> CompareResult 287 | where 288 | I: IntoIterator + PartialEq, 289 | T: Debug + PartialEq, 290 | { 291 | // First, try for the easy (and faster compare) 292 | if left != right { 293 | // Fallback on the slow one by one compare 294 | let right = right.into_iter().collect(); 295 | compare_elem_by_elem(left, right) 296 | } else { 297 | CompareResult::Equal 298 | } 299 | } 300 | 301 | #[doc(hidden)] 302 | pub fn compare_unordered_sort(left: I, right: I) -> CompareResult 303 | where 304 | I: IntoIterator + PartialEq, 305 | T: Debug + Ord + PartialEq, 306 | { 307 | // First, try for the easy (and faster compare) 308 | if left != right { 309 | // Next, try and sort under assumption these are equal, but might be out of order 310 | let mut left: Vec<_> = left.into_iter().collect(); 311 | let mut right: Vec<_> = right.into_iter().collect(); 312 | 313 | left.sort_unstable(); 314 | right.sort_unstable(); 315 | 316 | if left != right { 317 | // Fallback on the slow one by one compare 318 | compare_elem_by_elem(left, right) 319 | } else { 320 | CompareResult::Equal 321 | } 322 | } else { 323 | CompareResult::Equal 324 | } 325 | } 326 | 327 | #[cfg(test)] 328 | mod tests { 329 | use crate::{compare_unordered, compare_unordered_sort, CompareResult}; 330 | use alloc::vec::Vec; 331 | use alloc::{format, vec}; 332 | use core::fmt::Debug; 333 | 334 | #[derive(Debug, PartialEq)] 335 | struct MyType(i32); 336 | 337 | #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] 338 | struct MyTypeSort(i32); 339 | 340 | fn validate_results( 341 | result: CompareResult, 342 | both_expected: Vec, 343 | left_expected: Vec, 344 | right_expected: Vec, 345 | ) { 346 | match result { 347 | CompareResult::NotEqualDiffElements(both_actual, left_actual, right_actual) => { 348 | assert_eq!(format!("{both_expected:#?}"), both_actual); 349 | assert_eq!(format!("{left_expected:#?}"), left_actual); 350 | assert_eq!(format!("{right_expected:#?}"), right_actual); 351 | } 352 | _ => { 353 | panic!("Left and right were expected to have have different elements"); 354 | } 355 | } 356 | } 357 | 358 | macro_rules! make_tests { 359 | ($func:ident, $type:ident) => { 360 | #[test] 361 | fn compare_unordered_not_equal_diff_elem() { 362 | let left = vec![$type(1), $type(2), $type(4), $type(5)]; 363 | let right = vec![$type(2), $type(0), $type(4)]; 364 | 365 | validate_results( 366 | $func(left, right), 367 | vec![$type(2), $type(4)], 368 | vec![$type(1), $type(5)], 369 | vec![$type(0)], 370 | ); 371 | } 372 | 373 | #[test] 374 | fn compare_unordered_not_equal_dup_elem_diff_len() { 375 | let left = vec![$type(2), $type(4), $type(4)]; 376 | let right = vec![$type(4), $type(2)]; 377 | 378 | validate_results( 379 | $func(left, right), 380 | vec![$type(2), $type(4)], 381 | vec![$type(4)], 382 | vec![], 383 | ); 384 | } 385 | 386 | #[test] 387 | fn compare_unordered_not_equal_dup_elem() { 388 | let left = vec![$type(2), $type(2), $type(2), $type(4)]; 389 | let right = vec![$type(2), $type(4), $type(4), $type(4)]; 390 | 391 | validate_results( 392 | $func(left, right), 393 | vec![$type(2), $type(4)], 394 | vec![$type(2), $type(2)], 395 | vec![$type(4), $type(4)], 396 | ); 397 | } 398 | 399 | #[test] 400 | fn compare_unordered_equal_diff_order() { 401 | let left = vec![$type(1), $type(2), $type(4), $type(5)]; 402 | let right = vec![$type(5), $type(2), $type(1), $type(4)]; 403 | 404 | assert!(matches!($func(left, right), CompareResult::Equal)); 405 | } 406 | 407 | #[test] 408 | fn compare_unordered_equal_same_order() { 409 | let left = vec![$type(1), $type(2), $type(4), $type(5)]; 410 | let right = vec![$type(1), $type(2), $type(4), $type(5)]; 411 | 412 | assert!(matches!($func(left, right), CompareResult::Equal)); 413 | } 414 | }; 415 | } 416 | 417 | mod regular { 418 | use super::*; 419 | 420 | make_tests!(compare_unordered, MyType); 421 | } 422 | 423 | mod sort { 424 | use super::*; 425 | 426 | make_tests!(compare_unordered_sort, MyTypeSort); 427 | } 428 | } 429 | --------------------------------------------------------------------------------