rayon-cond-0.4.0/.cargo_vcs_info.json0000644000000001360000000000100131060ustar { "git": { "sha1": "aa6afe979c7eb2a5c9d1e6207711e50821a0a85e" }, "path_in_vcs": "" }rayon-cond-0.4.0/.github/workflows/ci.yaml000064400000000000000000000006661046102023000165620ustar 00000000000000name: CI on: push: branches: ["master"] pull_request: branches: ["master"] jobs: test: name: Test runs-on: ubuntu-latest strategy: matrix: rust: ["1.63.0", "stable", "beta", "nightly"] steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ matrix.rust }} - run: cargo build --verbose - run: cargo test --verbose rayon-cond-0.4.0/.gitignore000064400000000000000000000000361046102023000136650ustar 00000000000000/target **/*.rs.bk Cargo.lock rayon-cond-0.4.0/Cargo.lock0000644000000034210000000000100110610ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "crossbeam-deque" version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" dependencies = [ "crossbeam-epoch", "crossbeam-utils", ] [[package]] name = "crossbeam-epoch" version = "0.9.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "either" version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] name = "itertools" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" dependencies = [ "either", ] [[package]] name = "rayon" version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" dependencies = [ "either", "rayon-core", ] [[package]] name = "rayon-cond" version = "0.4.0" dependencies = [ "either", "itertools", "rayon", ] [[package]] name = "rayon-core" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" dependencies = [ "crossbeam-deque", "crossbeam-utils", ] rayon-cond-0.4.0/Cargo.toml0000644000000022160000000000100111050ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.63.0" name = "rayon-cond" version = "0.4.0" authors = ["Josh Stone "] build = false exclude = ["/.cirrus.yml"] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Experimental iterator wrapper that is conditionally parallel or serial." readme = "README.md" keywords = [ "parallel", "iterator", ] categories = ["concurrency"] license = "Apache-2.0/MIT" repository = "https://github.com/cuviper/rayon-cond" [lib] name = "rayon_cond" path = "src/lib.rs" [dependencies.either] version = "1.6" [dependencies.itertools] version = "0.14" [dependencies.rayon] version = "1.7" rayon-cond-0.4.0/Cargo.toml.orig000064400000000000000000000007371046102023000145740ustar 00000000000000[package] name = "rayon-cond" version = "0.4.0" authors = ["Josh Stone "] description = "Experimental iterator wrapper that is conditionally parallel or serial." repository = "https://github.com/cuviper/rayon-cond" license = "Apache-2.0/MIT" readme = "README.md" keywords = ["parallel", "iterator"] categories = ["concurrency"] exclude = ["/.cirrus.yml"] edition = "2021" rust-version = "1.63.0" [dependencies] rayon = "1.7" itertools = "0.14" either = "1.6" rayon-cond-0.4.0/LICENSE-APACHE000064400000000000000000000251371046102023000136320ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. rayon-cond-0.4.0/LICENSE-MIT000064400000000000000000000020361046102023000133330ustar 00000000000000Copyright (c) 2018 Josh Stone 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. rayon-cond-0.4.0/README.md000064400000000000000000000030541046102023000131570ustar 00000000000000# rayon-cond [![Crate](https://img.shields.io/crates/v/rayon-cond.svg)](https://crates.io/crates/rayon-cond) [![Documentation](https://docs.rs/rayon-cond/badge.svg)](https://docs.rs/rayon-cond) ![minimum rustc 1.63](https://img.shields.io/badge/rustc-1.63+-red.svg) [![Build Status](https://api.cirrus-ci.com/github/cuviper/rayon-cond.svg)](https://cirrus-ci.com/github/cuviper/rayon-cond) Experimental iterator wrapper that is conditionally parallel or serial, using Rayon's `ParallelIterator` or the standard `Iterator` respectively. ## Usage First add this crate to your `Cargo.toml`: ```toml [dependencies] rayon-cond = "0.4" ``` Then in your code, it may be used something like this: ```rust use rayon_cond::CondIterator; fn main() { let args: Vec<_> = std::env::args().collect(); // Run in parallel if there are an even number of args let par = args.len() % 2 == 0; CondIterator::new(args, par).enumerate().for_each(|(i, arg)| { println!("arg {}: {:?}", i, arg); }); } ``` `rayon-cond` currently requires `rustc 1.63.0` or greater. ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or https://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or https://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. rayon-cond-0.4.0/src/lib.rs000064400000000000000000000571731046102023000136160ustar 00000000000000//! Experimental iterator wrapper that is conditionally parallel or serial, using //! Rayon's `ParallelIterator` or the standard `Iterator` respectively. //! //! ## Usage //! //! First add this crate to your `Cargo.toml`: //! //! ```toml //! [dependencies] //! rayon-cond = "0.3" //! ``` //! //! Then in your code, it may be used something like this: //! //! ```rust //! use rayon_cond::CondIterator; //! //! let args: Vec<_> = std::env::args().collect(); //! //! // Run in parallel if there are an even number of args //! let par = args.len() % 2 == 0; //! //! CondIterator::new(args, par).enumerate().for_each(|(i, arg)| { //! println!("arg {}: {:?}", i, arg); //! }); //! ``` use either::Either; use itertools::Itertools; use rayon::prelude::*; use std::cmp::Ordering; use itertools::structs as it; use rayon::iter as ri; use std::iter as si; use crate::CondIterator::*; /// An iterator that could be parallel or serial, with a common API either way. /// /// The available methods mostly follow [`ParallelIterator`] and [`IndexedParallelIterator`], as /// `rayon` has the stricter requirements, and they are parallelized with [`rayon::iter`] types. /// Serial implementations use appropriate types from [`std::iter`] and [`itertools::structs`]. /// /// [`ParallelIterator`]: https://docs.rs/rayon/1/rayon/iter/trait.ParallelIterator.html /// [`IndexedParallelIterator`]: https://docs.rs/rayon/1/rayon/iter/trait.IndexedParallelIterator.html /// [`rayon::iter`]: https://docs.rs/rayon/1/rayon/iter/index.html#structs /// [`std::iter`]: https://doc.rust-lang.org/std/iter/index.html#structs /// [`itertools::structs`]: https://docs.rs/itertools/0.8/itertools/structs/index.html#structs pub enum CondIterator where P: ParallelIterator, S: Iterator, { Parallel(P), Serial(S), } impl CondIterator where P: ParallelIterator, S: Iterator, { pub fn new(iterable: I, parallel: bool) -> Self where I: IntoParallelIterator + IntoIterator, { if parallel { Self::from_parallel(iterable) } else { Self::from_serial(iterable) } } pub fn from_parallel(iterable: I) -> Self where I: IntoParallelIterator, { Parallel(iterable.into_par_iter()) } pub fn from_serial(iterable: I) -> Self where I: IntoIterator, { Serial(iterable.into_iter()) } pub fn is_parallel(&self) -> bool { matches!(self, Parallel(_)) } pub fn is_serial(&self) -> bool { matches!(self, Serial(_)) } } impl CondIterator where P: ParallelIterator, S: Iterator + Send, { pub fn into_parallel(self) -> Either> { match self { Parallel(iter) => Either::Left(iter), Serial(iter) => Either::Right(iter.par_bridge()), } } } macro_rules! either { ($self:ident, $pattern:pat => $result:expr) => { match $self { Parallel($pattern) => $result, Serial($pattern) => $result, } }; } macro_rules! wrap_either { ($self:ident, $pattern:pat => $result:expr) => { match $self { Parallel($pattern) => Parallel($result), Serial($pattern) => Serial($result), } }; } impl CondIterator where P: ParallelIterator, S: Iterator, { pub fn for_each(self, op: OP) where OP: Fn(P::Item) + Sync + Send, { either!(self, iter => iter.for_each(op)) } pub fn for_each_with(self, mut init: T, op: OP) where OP: Fn(&mut T, P::Item) + Sync + Send, T: Send + Clone, { match self { Parallel(iter) => iter.for_each_with(init, op), Serial(iter) => iter.for_each(move |item| op(&mut init, item)), } } pub fn for_each_init(self, init: INIT, op: OP) where OP: Fn(&mut T, P::Item) + Sync + Send, INIT: Fn() -> T + Sync + Send, { match self { Parallel(iter) => iter.for_each_init(init, op), Serial(iter) => { let mut init = init(); iter.for_each(move |item| op(&mut init, item)) } } } pub fn count(self) -> usize { either!(self, iter => iter.count()) } pub fn map(self, map_op: F) -> CondIterator, si::Map> where F: Fn(P::Item) -> R + Sync + Send, R: Send, { wrap_either!(self, iter => iter.map(map_op)) } // If we want to avoid `impl FnMut`, we'll need to implement a custom // serialized `MapWith` type to return. pub fn map_with( self, mut init: T, map_op: F, ) -> CondIterator, si::Map R>> where F: Fn(&mut T, P::Item) -> R + Sync + Send, T: Send + Clone, R: Send, { match self { Parallel(iter) => Parallel(iter.map_with(init, map_op)), Serial(iter) => Serial(iter.map(move |item| map_op(&mut init, item))), } } // If we want to avoid `impl FnMut`, we'll need to implement a custom // serialized `MapInit` type to return. pub fn map_init( self, init: INIT, map_op: F, ) -> CondIterator, si::Map R>> where F: Fn(&mut T, P::Item) -> R + Sync + Send, INIT: Fn() -> T + Sync + Send, R: Send, { match self { Parallel(iter) => Parallel(iter.map_init(init, map_op)), Serial(iter) => { let mut init = init(); Serial(iter.map(move |item| map_op(&mut init, item))) } } } pub fn cloned<'a, T>(self) -> CondIterator, si::Cloned> where T: 'a + Clone + Sync + Send, P: ParallelIterator, S: Iterator, { wrap_either!(self, iter => iter.cloned()) } pub fn copied<'a, T>(self) -> CondIterator, si::Copied> where T: 'a + Copy + Sync + Send, P: ParallelIterator, S: Iterator, { wrap_either!(self, iter => iter.copied()) } pub fn inspect(self, inspect_op: OP) -> CondIterator, si::Inspect> where OP: Fn(&P::Item) + Sync + Send, { wrap_either!(self, iter => iter.inspect(inspect_op)) } pub fn update(self, update_op: OP) -> CondIterator, it::Update> where OP: Fn(&mut P::Item) + Sync + Send, { wrap_either!(self, iter => iter.update(update_op)) } pub fn filter( self, filter_op: Pred, ) -> CondIterator, si::Filter> where Pred: Fn(&P::Item) -> bool + Sync + Send, { wrap_either!(self, iter => iter.filter(filter_op)) } pub fn filter_map( self, filter_op: Pred, ) -> CondIterator, si::FilterMap> where Pred: Fn(P::Item) -> Option + Sync + Send, R: Send, { wrap_either!(self, iter => iter.filter_map(filter_op)) } pub fn flat_map(self, map_op: F) -> CondIterator, si::FlatMap> where F: Fn(P::Item) -> I + Sync + Send, I: IntoParallelIterator + IntoIterator::Item>, { wrap_either!(self, iter => iter.flat_map(map_op)) } pub fn flat_map_iter( self, map_op: F, ) -> CondIterator, si::FlatMap> where F: Fn(P::Item) -> I + Sync + Send, I: IntoIterator, I::Item: Send, { match self { Parallel(iter) => Parallel(iter.flat_map_iter(map_op)), Serial(iter) => Serial(iter.flat_map(map_op)), } } pub fn flatten(self) -> CondIterator, si::Flatten> where P::Item: IntoParallelIterator, S::Item: IntoIterator::Item>, { wrap_either!(self, iter => iter.flatten()) } pub fn flatten_iter(self) -> CondIterator, si::Flatten> where P::Item: IntoIterator, ::Item: Send, { match self { Parallel(iter) => Parallel(iter.flatten_iter()), Serial(iter) => Serial(iter.flatten()), } } pub fn reduce(self, identity: ID, op: OP) -> P::Item where OP: Fn(P::Item, P::Item) -> P::Item + Sync + Send, ID: Fn() -> P::Item + Sync + Send, { match self { Parallel(iter) => iter.reduce(identity, op), Serial(iter) => iter.fold(identity(), op), } } pub fn reduce_with(self, op: OP) -> Option where OP: Fn(P::Item, P::Item) -> P::Item + Sync + Send, { match self { Parallel(iter) => iter.reduce_with(op), Serial(iter) => iter.reduce(op), } } // NB: Rayon's `fold` produces another iterator, so we have to fake that serially. pub fn fold( self, identity: ID, fold_op: F, ) -> CondIterator, si::Once> where F: Fn(T, P::Item) -> T + Sync + Send, ID: Fn() -> T + Sync + Send, T: Send, { match self { Parallel(iter) => Parallel(iter.fold(identity, fold_op)), Serial(iter) => Serial(si::once(iter.fold(identity(), fold_op))), } } pub fn fold_with( self, init: T, fold_op: F, ) -> CondIterator, si::Once> where F: Fn(T, P::Item) -> T + Sync + Send, T: Send + Clone, { match self { Parallel(iter) => Parallel(iter.fold_with(init, fold_op)), Serial(iter) => Serial(si::once(iter.fold(init, fold_op))), } } pub fn sum(self) -> Sum where Sum: Send + si::Sum + si::Sum, { either!(self, iter => iter.sum()) } pub fn product(self) -> Product where Product: Send + si::Product + si::Product, { either!(self, iter => iter.product()) } pub fn min(self) -> Option where P::Item: Ord, { either!(self, iter => iter.min()) } pub fn min_by(self, f: F) -> Option where F: Sync + Send + Fn(&P::Item, &P::Item) -> Ordering, { either!(self, iter => iter.min_by(f)) } pub fn min_by_key(self, f: F) -> Option where K: Ord + Send, F: Sync + Send + Fn(&P::Item) -> K, { either!(self, iter => iter.min_by_key(f)) } pub fn max(self) -> Option where P::Item: Ord, { either!(self, iter => iter.max()) } pub fn max_by(self, f: F) -> Option where F: Sync + Send + Fn(&P::Item, &P::Item) -> Ordering, { either!(self, iter => iter.max_by(f)) } pub fn max_by_key(self, f: F) -> Option where K: Ord + Send, F: Sync + Send + Fn(&P::Item) -> K, { either!(self, iter => iter.max_by_key(f)) } pub fn chain( self, chain: C, ) -> CondIterator, si::Chain> where C: IntoParallelIterator + IntoIterator, { wrap_either!(self, iter => iter.chain(chain)) } pub fn find_any(self, predicate: Pred) -> Option where Pred: Fn(&P::Item) -> bool + Sync + Send, { match self { Parallel(iter) => iter.find_any(predicate), Serial(mut iter) => iter.find(predicate), } } pub fn find_first(self, predicate: Pred) -> Option where Pred: Fn(&P::Item) -> bool + Sync + Send, { match self { Parallel(iter) => iter.find_first(predicate), Serial(mut iter) => iter.find(predicate), } } pub fn any(self, predicate: Pred) -> bool where Pred: Fn(P::Item) -> bool + Sync + Send, { match self { Parallel(iter) => iter.any(predicate), Serial(mut iter) => iter.any(predicate), } } pub fn all(self, predicate: Pred) -> bool where Pred: Fn(P::Item) -> bool + Sync + Send, { match self { Parallel(iter) => iter.all(predicate), Serial(mut iter) => iter.all(predicate), } } pub fn while_some(self) -> CondIterator, it::WhileSome> where P: ParallelIterator>, S: Iterator>, T: Send, { wrap_either!(self, iter => iter.while_some()) } pub fn collect(self) -> C where C: FromCondIterator, { either!(self, iter => iter.collect()) } pub fn unzip(self) -> (FromA, FromB) where P: ParallelIterator, S: Iterator, FromA: Default + Send + CondExtend, FromB: Default + Send + CondExtend, A: Send, B: Send, { either!(self, iter => iter.unzip()) } // NB: `Iterator::partition` only allows a single output type, but // we can be more flexible using `partition_map`! pub fn partition(self, predicate: Pred) -> (A, B) where A: Default + Send + CondExtend, B: Default + Send + CondExtend, Pred: Fn(&P::Item) -> bool + Sync + Send, { match self { Parallel(iter) => iter.partition(predicate), Serial(iter) => iter.partition_map(|item| { if predicate(&item) { Either::Left(item) } else { Either::Right(item) } }), } } pub fn partition_map(self, predicate: Pred) -> (A, B) where A: Default + Send + CondExtend, B: Default + Send + CondExtend, Pred: Fn(P::Item) -> Either + Sync + Send, L: Send, R: Send, { either!(self, iter => iter.partition_map(predicate)) } pub fn intersperse( self, element: P::Item, ) -> CondIterator, it::Intersperse> where P::Item: Clone, { match self { Parallel(iter) => Parallel(iter.intersperse(element)), Serial(iter) => Serial(Itertools::intersperse(iter, element)), } } pub fn opt_len(&self) -> Option { match self { Parallel(ref iter) => iter.opt_len(), Serial(ref iter) => match iter.size_hint() { (lo, Some(hi)) if lo == hi => Some(lo), _ => None, }, } } } impl CondIterator where P: ParallelIterator, S: DoubleEndedIterator, { pub fn find_last(self, predicate: Pred) -> Option where Pred: Fn(&P::Item) -> bool + Sync + Send, { match self { Parallel(iter) => iter.find_last(predicate), Serial(mut iter) => iter.rfind(predicate), } } } impl CondIterator where P: IndexedParallelIterator, S: Iterator, { pub fn collect_into_vec(self, target: &mut Vec) { match self { Parallel(iter) => iter.collect_into_vec(target), Serial(iter) => { target.clear(); let (lower, _) = iter.size_hint(); target.reserve(lower); target.extend(iter); } } } pub fn unzip_into_vecs(self, left: &mut Vec, right: &mut Vec) where P: IndexedParallelIterator, S: Iterator, A: Send, B: Send, { match self { Parallel(iter) => iter.unzip_into_vecs(left, right), Serial(iter) => { left.clear(); right.clear(); let (lower, _) = iter.size_hint(); left.reserve(lower); right.reserve(lower); iter.for_each(|(a, b)| { left.push(a); right.push(b); }) } } } pub fn zip(self, other: Z) -> CondIterator, si::Zip> where Z: IntoParallelIterator + IntoIterator::Item>, Z::Iter: IndexedParallelIterator, { wrap_either!(self, iter => iter.zip(other)) } pub fn zip_eq( self, other: Z, ) -> CondIterator, it::ZipEq> where Z: IntoParallelIterator + IntoIterator::Item>, Z::Iter: IndexedParallelIterator, { wrap_either!(self, iter => iter.zip_eq(other)) } pub fn interleave( self, other: I, ) -> CondIterator, it::Interleave> where I: IntoParallelIterator + IntoIterator, I::Iter: IndexedParallelIterator, { wrap_either!(self, iter => iter.interleave(other)) } pub fn interleave_shortest( self, other: I, ) -> CondIterator, it::InterleaveShortest> where I: IntoParallelIterator + IntoIterator, I::Iter: IndexedParallelIterator, { wrap_either!(self, iter => iter.interleave_shortest(other)) } pub fn cmp(self, other: I) -> Ordering where I: IntoParallelIterator + IntoIterator, I::Iter: IndexedParallelIterator, P::Item: Ord, { either!(self, iter => iter.cmp(other)) } pub fn partial_cmp(self, other: I) -> Option where I: IntoParallelIterator + IntoIterator::Item>, I::Iter: IndexedParallelIterator, P::Item: PartialOrd<::Item>, { either!(self, iter => iter.partial_cmp(other)) } pub fn eq(self, other: I) -> bool where I: IntoParallelIterator + IntoIterator::Item>, I::Iter: IndexedParallelIterator, P::Item: PartialEq<::Item>, { either!(self, iter => iter.eq(other)) } pub fn ne(self, other: I) -> bool where I: IntoParallelIterator + IntoIterator::Item>, I::Iter: IndexedParallelIterator, P::Item: PartialEq<::Item>, { either!(self, iter => iter.ne(other)) } pub fn lt(self, other: I) -> bool where I: IntoParallelIterator + IntoIterator::Item>, I::Iter: IndexedParallelIterator, P::Item: PartialOrd<::Item>, { either!(self, iter => iter.lt(other)) } pub fn le(self, other: I) -> bool where I: IntoParallelIterator + IntoIterator::Item>, I::Iter: IndexedParallelIterator, P::Item: PartialOrd<::Item>, { either!(self, iter => iter.le(other)) } pub fn gt(self, other: I) -> bool where I: IntoParallelIterator + IntoIterator::Item>, I::Iter: IndexedParallelIterator, P::Item: PartialOrd<::Item>, { either!(self, iter => iter.gt(other)) } pub fn ge(self, other: I) -> bool where I: IntoParallelIterator + IntoIterator::Item>, I::Iter: IndexedParallelIterator, P::Item: PartialOrd<::Item>, { either!(self, iter => iter.ge(other)) } pub fn enumerate(self) -> CondIterator, si::Enumerate> { wrap_either!(self, iter => iter.enumerate()) } pub fn skip(self, n: usize) -> CondIterator, si::Skip> { wrap_either!(self, iter => iter.skip(n)) } pub fn take(self, n: usize) -> CondIterator, si::Take> { wrap_either!(self, iter => iter.take(n)) } pub fn position_any(self, predicate: Pred) -> Option where Pred: Fn(P::Item) -> bool + Sync + Send, { match self { Parallel(iter) => iter.position_any(predicate), Serial(mut iter) => iter.position(predicate), } } pub fn position_first(self, predicate: Pred) -> Option where Pred: Fn(P::Item) -> bool + Sync + Send, { match self { Parallel(iter) => iter.position_first(predicate), Serial(mut iter) => iter.position(predicate), } } pub fn positions( self, predicate: Pred, ) -> CondIterator, it::Positions> where Pred: Fn(P::Item) -> bool + Sync + Send, { wrap_either!(self, iter => iter.positions(predicate)) } pub fn step_by(self, step: usize) -> CondIterator, si::StepBy> { wrap_either!(self, iter => iter.step_by(step)) } } impl CondIterator where P: IndexedParallelIterator, S: DoubleEndedIterator, { pub fn rev(self) -> CondIterator, si::Rev> { wrap_either!(self, iter => iter.rev()) } } impl CondIterator where P: IndexedParallelIterator, S: ExactSizeIterator, { #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> usize { either!(self, ref iter => iter.len()) } } impl CondIterator where P: IndexedParallelIterator, S: ExactSizeIterator + DoubleEndedIterator, { pub fn position_last(self, predicate: Pred) -> Option where Pred: Fn(P::Item) -> bool + Sync + Send, { match self { Parallel(iter) => iter.position_last(predicate), Serial(mut iter) => iter.rposition(predicate), } } } pub trait FromCondIterator: FromParallelIterator + si::FromIterator where T: Send, { fn from_cond_iter(cond_iter: CondIterator) -> Self where P: ParallelIterator, S: Iterator, { match cond_iter { Parallel(iter) => Self::from_par_iter(iter), Serial(iter) => Self::from_iter(iter), } } } impl FromCondIterator for C where C: FromParallelIterator + si::FromIterator, T: Send, { } pub trait CondExtend: ParallelExtend + Extend where T: Send, { fn cond_extend(&mut self, cond_iter: CondIterator) where P: ParallelIterator, S: Iterator, { match cond_iter { Parallel(iter) => self.par_extend(iter), Serial(iter) => self.extend(iter), } } } impl CondExtend for C where C: ParallelExtend + Extend, T: Send, { }