├── .github ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md └── workflows │ └── ci.yaml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src ├── from_parallel_stream.rs ├── from_stream.rs ├── into_parallel_stream.rs ├── lib.rs ├── par_stream │ ├── for_each.rs │ ├── map.rs │ ├── mod.rs │ ├── next.rs │ └── take.rs ├── prelude.rs ├── utils.rs └── vec.rs └── tests └── test.rs /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of 9 | experience, 10 | education, socio-economic status, nationality, personal appearance, race, 11 | religion, or sexual identity and orientation. 12 | 13 | ## Our Standards 14 | 15 | Examples of behavior that contributes to creating a positive environment 16 | include: 17 | 18 | - Using welcoming and inclusive language 19 | - Being respectful of differing viewpoints and experiences 20 | - Gracefully accepting constructive criticism 21 | - Focusing on what is best for the community 22 | - Showing empathy towards other community members 23 | 24 | Examples of unacceptable behavior by participants include: 25 | 26 | - The use of sexualized language or imagery and unwelcome sexual attention or 27 | advances 28 | - Trolling, insulting/derogatory comments, and personal or political attacks 29 | - Public or private harassment 30 | - Publishing others' private information, such as a physical or electronic 31 | address, without explicit permission 32 | - Other conduct which could reasonably be considered inappropriate in a 33 | professional setting 34 | 35 | 36 | ## Our Responsibilities 37 | 38 | Project maintainers are responsible for clarifying the standards of acceptable 39 | behavior and are expected to take appropriate and fair corrective action in 40 | response to any instances of unacceptable behavior. 41 | 42 | Project maintainers have the right and responsibility to remove, edit, or 43 | reject comments, commits, code, wiki edits, issues, and other contributions 44 | that are not aligned to this Code of Conduct, or to ban temporarily or 45 | permanently any contributor for other behaviors that they deem inappropriate, 46 | threatening, offensive, or harmful. 47 | 48 | ## Scope 49 | 50 | This Code of Conduct applies both within project spaces and in public spaces 51 | when an individual is representing the project or its community. Examples of 52 | representing a project or community include using an official project e-mail 53 | address, posting via an official social media account, or acting as an appointed 54 | representative at an online or offline event. Representation of a project may be 55 | further defined and clarified by project maintainers. 56 | 57 | ## Enforcement 58 | 59 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 60 | reported by contacting the project team at yoshuawuyts@gmail.com, or through 61 | IRC. All complaints will be reviewed and investigated and will result in a 62 | response that is deemed necessary and appropriate to the circumstances. The 63 | project team is obligated to maintain confidentiality with regard to the 64 | reporter of an incident. 65 | Further details of specific enforcement policies may be posted separately. 66 | 67 | Project maintainers who do not follow or enforce the Code of Conduct in good 68 | faith may face temporary or permanent repercussions as determined by other 69 | members of the project's leadership. 70 | 71 | ## Attribution 72 | 73 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4, 74 | available at 75 | https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 76 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | Contributions include code, documentation, answering user questions, running the 3 | project's infrastructure, and advocating for all types of users. 4 | 5 | The project welcomes all contributions from anyone willing to work in good faith 6 | with other contributors and the community. No contribution is too small and all 7 | contributions are valued. 8 | 9 | This guide explains the process for contributing to the project's GitHub 10 | Repository. 11 | 12 | - [Code of Conduct](#code-of-conduct) 13 | - [Bad Actors](#bad-actors) 14 | 15 | ## Code of Conduct 16 | The project has a [Code of Conduct](./CODE_OF_CONDUCT.md) that *all* 17 | contributors are expected to follow. This code describes the *minimum* behavior 18 | expectations for all contributors. 19 | 20 | As a contributor, how you choose to act and interact towards your 21 | fellow contributors, as well as to the community, will reflect back not only 22 | on yourself but on the project as a whole. The Code of Conduct is designed and 23 | intended, above all else, to help establish a culture within the project that 24 | allows anyone and everyone who wants to contribute to feel safe doing so. 25 | 26 | Should any individual act in any way that is considered in violation of the 27 | [Code of Conduct](./CODE_OF_CONDUCT.md), corrective actions will be taken. It is 28 | possible, however, for any individual to *act* in such a manner that is not in 29 | violation of the strict letter of the Code of Conduct guidelines while still 30 | going completely against the spirit of what that Code is intended to accomplish. 31 | 32 | Open, diverse, and inclusive communities live and die on the basis of trust. 33 | Contributors can disagree with one another so long as they trust that those 34 | disagreements are in good faith and everyone is working towards a common 35 | goal. 36 | 37 | ## Bad Actors 38 | All contributors to tacitly agree to abide by both the letter and 39 | spirit of the [Code of Conduct](./CODE_OF_CONDUCT.md). Failure, or 40 | unwillingness, to do so will result in contributions being respectfully 41 | declined. 42 | 43 | A *bad actor* is someone who repeatedly violates the *spirit* of the Code of 44 | Conduct through consistent failure to self-regulate the way in which they 45 | interact with other contributors in the project. In doing so, bad actors 46 | alienate other contributors, discourage collaboration, and generally reflect 47 | poorly on the project as a whole. 48 | 49 | Being a bad actor may be intentional or unintentional. Typically, unintentional 50 | bad behavior can be easily corrected by being quick to apologize and correct 51 | course *even if you are not entirely convinced you need to*. Giving other 52 | contributors the benefit of the doubt and having a sincere willingness to admit 53 | that you *might* be wrong is critical for any successful open collaboration. 54 | 55 | Don't be a bad actor. 56 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - master 8 | 9 | env: 10 | RUSTFLAGS: -Dwarnings 11 | 12 | jobs: 13 | build_and_test: 14 | name: Build and test 15 | runs-on: ${{ matrix.os }} 16 | strategy: 17 | matrix: 18 | os: [ubuntu-latest, macOS-latest] 19 | rust: [nightly] 20 | 21 | steps: 22 | - uses: actions/checkout@master 23 | 24 | - name: Install ${{ matrix.rust }} 25 | uses: actions-rs/toolchain@v1 26 | with: 27 | toolchain: ${{ matrix.rust }} 28 | override: true 29 | 30 | - name: check 31 | uses: actions-rs/cargo@v1 32 | with: 33 | command: check 34 | args: --all --bins --examples --benches --tests 35 | 36 | - name: tests 37 | uses: actions-rs/cargo@v1 38 | with: 39 | command: test 40 | args: --all 41 | 42 | check_fmt_and_docs: 43 | name: Checking fmt and docs 44 | runs-on: ubuntu-latest 45 | steps: 46 | - uses: actions/checkout@master 47 | - uses: actions-rs/toolchain@v1 48 | with: 49 | toolchain: nightly 50 | components: rustfmt, clippy 51 | override: true 52 | 53 | - name: fmt 54 | run: cargo fmt --all -- --check 55 | 56 | - name: clippy 57 | run: cargo clippy 58 | 59 | 60 | - name: Docs 61 | run: cargo doc 62 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | tmp/ 3 | Cargo.lock 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "parallel-stream" 3 | version = "2.1.3" 4 | license = "MIT OR Apache-2.0" 5 | repository = "https://github.com/async-rs/parallel-stream" 6 | documentation = "https://docs.rs/parallel-stream" 7 | description = "Data parallelism library for async-std" 8 | readme = "README.md" 9 | edition = "2018" 10 | keywords = [] 11 | categories = [] 12 | authors = [ 13 | "Yoshua Wuyts " 14 | ] 15 | 16 | [features] 17 | 18 | [dependencies] 19 | async-std = { version = "1.9.0", features = ["attributes", "unstable"] } 20 | pin-project-lite = "0.2.0" 21 | 22 | [dev-dependencies] 23 | -------------------------------------------------------------------------------- /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 | Copyright 2020 Yoshua Wuyts 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Yoshua Wuyts 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

parallel-stream

2 |
3 | 4 | Data parallelism library for async-std. 5 | 6 |
7 | 8 |
9 | 10 |
11 | 12 | 13 | Crates.io version 15 | 16 | 17 | 18 | Download 20 | 21 | 22 | 23 | docs.rs docs 25 | 26 |
27 | 28 |
29 |

30 | 31 | API Docs 32 | 33 | | 34 | 35 | Releases 36 | 37 | | 38 | 39 | Contributing 40 | 41 |

42 |
43 | 44 | ## Installation 45 | ```sh 46 | $ cargo add parallel-stream 47 | ``` 48 | 49 | ## Safety 50 | This crate uses ``#![deny(unsafe_code)]`` to ensure everything is implemented in 51 | 100% Safe Rust. 52 | 53 | ## Contributing 54 | Want to join us? Check out our ["Contributing" guide][contributing] and take a 55 | look at some of these issues: 56 | 57 | - [Issues labeled "good first issue"][good-first-issue] 58 | - [Issues labeled "help wanted"][help-wanted] 59 | 60 | [contributing]: https://github.com/async-rs/parallel-stream/blob/master.github/CONTRIBUTING.md 61 | [good-first-issue]: https://github.com/async-rs/parallel-stream/labels/good%20first%20issue 62 | [help-wanted]: https://github.com/async-rs/parallel-stream/labels/help%20wanted 63 | 64 | ## License 65 | 66 | 67 | Licensed under either of Apache License, Version 68 | 2.0 or MIT license at your option. 69 | 70 | 71 |
72 | 73 | 74 | Unless you explicitly state otherwise, any contribution intentionally submitted 75 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 76 | be dual licensed as above, without any additional terms or conditions. 77 | 78 | -------------------------------------------------------------------------------- /src/from_parallel_stream.rs: -------------------------------------------------------------------------------- 1 | use core::future::Future; 2 | use core::pin::Pin; 3 | 4 | use crate::IntoParallelStream; 5 | 6 | /// Conversion from a `ParallelStream`. 7 | pub trait FromParallelStream { 8 | /// Creates a value from a stream. 9 | fn from_par_stream<'a, S>(stream: S) -> Pin + 'a + Send>> 10 | where 11 | S: IntoParallelStream + 'a + Send; 12 | } 13 | 14 | #[async_std::test] 15 | async fn is_send() { 16 | use crate::prelude::*; 17 | async_std::task::spawn(async move { 18 | let v: Vec = vec![1, 2, 3, 4]; 19 | let stream = v.into_par_stream().map(|n| async move { n * n }); 20 | let mut res = Vec::from_par_stream(stream).await; 21 | res.sort_unstable(); 22 | assert_eq!(res, vec![1, 4, 9, 16]); 23 | }) 24 | .await; 25 | } 26 | -------------------------------------------------------------------------------- /src/from_stream.rs: -------------------------------------------------------------------------------- 1 | use core::pin::Pin; 2 | 3 | use async_std::stream::{IntoStream, Stream}; 4 | use async_std::task::{Context, Poll}; 5 | use pin_project_lite::pin_project; 6 | 7 | use crate::ParallelStream; 8 | 9 | pin_project! { 10 | /// A parallel stream that was created from sequential stream. 11 | /// 12 | /// This stream is created by the [`from_stream`] function. 13 | /// See it documentation for more. 14 | /// 15 | /// [`from_stream`]: fn.from_stream.html 16 | #[derive(Clone, Debug)] 17 | pub struct FromStream { 18 | #[pin] 19 | stream: S, 20 | limit: Option, 21 | } 22 | } 23 | 24 | /// Converts a stream into a parallel stream. 25 | pub fn from_stream(stream: S) -> FromStream 26 | where 27 | S: Send + Sync, 28 | { 29 | FromStream { 30 | limit: None, 31 | stream: stream.into_stream(), 32 | } 33 | } 34 | 35 | impl ParallelStream for FromStream 36 | where 37 | S::Item: Send, 38 | { 39 | type Item = S::Item; 40 | 41 | fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 42 | let this = self.project(); 43 | this.stream.poll_next(cx) 44 | } 45 | 46 | fn limit(mut self, limit: impl Into>) -> Self { 47 | self.limit = limit.into(); 48 | self 49 | } 50 | 51 | fn get_limit(&self) -> Option { 52 | self.limit 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/into_parallel_stream.rs: -------------------------------------------------------------------------------- 1 | use crate::ParallelStream; 2 | 3 | /// Conversion into a `ParallelStream`. 4 | pub trait IntoParallelStream { 5 | /// The type of the elements being iterated over. 6 | type Item: Send; 7 | 8 | /// Which kind of stream are we turning this into? 9 | type IntoParStream: ParallelStream; 10 | 11 | /// Creates a parallel stream from a value. 12 | fn into_par_stream(self) -> Self::IntoParStream; 13 | } 14 | 15 | impl IntoParallelStream for I { 16 | type Item = I::Item; 17 | type IntoParStream = I; 18 | 19 | #[inline] 20 | fn into_par_stream(self) -> I { 21 | self 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Data parallelism library for async-std. 2 | //! 3 | //! This library provides convenient parallel iteration of 4 | //! [`Streams`](https://docs.rs/futures-core). Analogous to how 5 | //! [Rayon](https://docs.rs/rayon/) provides parallel iteration of 6 | //! `Iterator`s. This allows processing data coming from a stream in parallel, 7 | //! enabling use of *all* system resources. 8 | //! 9 | //! You can read about the design decisions and motivation in the "parallel 10 | //! streams" section of the ["streams 11 | //! concurrency"](https://blog.yoshuawuyts.com/streams-concurrency/#parallel-streams) 12 | //! blog post. 13 | //! 14 | //! # Differences with Rayon 15 | //! 16 | //! Rayon is a data parallelism library built for synchronous Rust, powered by 17 | //! an underlying thread pool. async-std manages a thread pool as well, but the 18 | //! key difference with Rayon is that async-std (and futures) are optimized for 19 | //! *latency*, while Rayon is optimized for *throughput*. 20 | //! 21 | //! As a rule of thumb: if you want to speed up doing heavy calculations you 22 | //! probably want to use Rayon. If you want to parallelize network requests 23 | //! consider using `parallel-stream`. 24 | //! 25 | //! # Examples 26 | //! 27 | //! ``` 28 | //! use parallel_stream::prelude::*; 29 | //! 30 | //! #[async_std::main] 31 | //! async fn main() { 32 | //! let v = vec![1, 2, 3, 4]; 33 | //! let mut out: Vec = v 34 | //! .into_par_stream() 35 | //! .map(|n| async move { n * n }) 36 | //! .collect() 37 | //! .await; 38 | //! out.sort(); 39 | //! assert_eq!(out, vec![1, 4, 9, 16]); 40 | //! } 41 | //! ``` 42 | 43 | #![forbid(unsafe_code)] 44 | #![deny(missing_debug_implementations, nonstandard_style)] 45 | #![warn(missing_docs)] 46 | 47 | mod from_parallel_stream; 48 | mod from_stream; 49 | mod into_parallel_stream; 50 | mod par_stream; 51 | 52 | pub use from_parallel_stream::FromParallelStream; 53 | pub use from_stream::{from_stream, FromStream}; 54 | pub use into_parallel_stream::IntoParallelStream; 55 | pub use par_stream::{ForEach, Map, NextFuture, ParallelStream, Take}; 56 | 57 | pub mod prelude; 58 | pub mod vec; 59 | 60 | pub(crate) mod utils; 61 | -------------------------------------------------------------------------------- /src/par_stream/for_each.rs: -------------------------------------------------------------------------------- 1 | use async_std::channel::{self, Receiver, Sender}; 2 | use async_std::prelude::*; 3 | use async_std::task::{self, Context, Poll}; 4 | 5 | use std::pin::Pin; 6 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; 7 | use std::sync::Arc; 8 | 9 | use crate::ParallelStream; 10 | 11 | pin_project_lite::pin_project! { 12 | /// Call a closure on each element of the stream. 13 | #[derive(Debug)] 14 | pub struct ForEach { 15 | // Receiver that tracks whether all tasks have finished executing. 16 | #[pin] 17 | receiver: Receiver<()>, 18 | // Track whether the input stream has been exhausted. 19 | exhausted: Arc, 20 | // Count how many tasks are executing. 21 | ref_count: Arc, 22 | } 23 | } 24 | 25 | impl ForEach { 26 | /// Create a new instance of `ForEach`. 27 | pub fn new(mut stream: S, mut f: F) -> Self 28 | where 29 | S: ParallelStream, 30 | F: FnMut(S::Item) -> Fut + Send + Sync + Copy + 'static, 31 | Fut: Future + Send, 32 | { 33 | let exhausted = Arc::new(AtomicBool::new(false)); 34 | let ref_count = Arc::new(AtomicU64::new(0)); 35 | let (sender, receiver): (Sender<()>, Receiver<()>) = channel::bounded(1); 36 | let _limit = stream.get_limit(); 37 | 38 | // Initialize the return type here to prevent borrowing issues. 39 | let this = Self { 40 | receiver, 41 | exhausted: exhausted.clone(), 42 | ref_count: ref_count.clone(), 43 | }; 44 | 45 | task::spawn(async move { 46 | while let Some(item) = stream.next().await { 47 | let sender = sender.clone(); 48 | let exhausted = exhausted.clone(); 49 | let ref_count = ref_count.clone(); 50 | 51 | ref_count.fetch_add(1, Ordering::SeqCst); 52 | 53 | task::spawn(async move { 54 | // Execute the closure. 55 | f(item).await; 56 | 57 | // Wake up the receiver if we know we're done. 58 | ref_count.fetch_sub(1, Ordering::SeqCst); 59 | if exhausted.load(Ordering::SeqCst) && ref_count.load(Ordering::SeqCst) == 0 { 60 | sender.send(()).await.expect("message failed to send"); 61 | } 62 | }); 63 | } 64 | 65 | // The input stream will no longer yield items. 66 | exhausted.store(true, Ordering::SeqCst); 67 | }); 68 | 69 | this 70 | } 71 | } 72 | 73 | impl Future for ForEach { 74 | type Output = (); 75 | 76 | fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 77 | let this = self.project(); 78 | task::ready!(this.receiver.poll_next(cx)); 79 | Poll::Ready(()) 80 | } 81 | } 82 | 83 | #[async_std::test] 84 | async fn smoke() { 85 | let s = async_std::stream::repeat(5usize); 86 | crate::from_stream(s) 87 | .take(3) 88 | .for_each(|n| async move { 89 | // TODO: assert that this is called 3 times. 90 | dbg!(n); 91 | }) 92 | .await; 93 | } 94 | -------------------------------------------------------------------------------- /src/par_stream/map.rs: -------------------------------------------------------------------------------- 1 | // use async_std::prelude::*; 2 | use async_std::channel::{self, Receiver}; 3 | use async_std::future::Future; 4 | use async_std::task; 5 | 6 | use std::pin::Pin; 7 | use std::task::{Context, Poll}; 8 | 9 | use crate::ParallelStream; 10 | 11 | pin_project_lite::pin_project! { 12 | /// A parallel stream that maps value of another stream with a function. 13 | #[derive(Debug)] 14 | pub struct Map { 15 | #[pin] 16 | receiver: Receiver, 17 | limit: Option, 18 | } 19 | } 20 | 21 | impl Map { 22 | /// Create a new instance of `Map`. 23 | pub fn new(mut stream: S, mut f: F) -> Self 24 | where 25 | S: ParallelStream, 26 | F: FnMut(S::Item) -> Fut + Send + Sync + Copy + 'static, 27 | Fut: Future + Send, 28 | { 29 | let (sender, receiver) = channel::bounded(1); 30 | let limit = stream.get_limit(); 31 | task::spawn(async move { 32 | while let Some(item) = stream.next().await { 33 | let sender = sender.clone(); 34 | task::spawn(async move { 35 | let res = f(item).await; 36 | sender.send(res).await.expect("message failed to send"); 37 | }); 38 | } 39 | }); 40 | Map { receiver, limit } 41 | } 42 | } 43 | 44 | impl ParallelStream for Map { 45 | type Item = T; 46 | fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 47 | use async_std::prelude::*; 48 | let this = self.project(); 49 | this.receiver.poll_next(cx) 50 | } 51 | 52 | fn limit(mut self, limit: impl Into>) -> Self { 53 | self.limit = limit.into(); 54 | self 55 | } 56 | 57 | fn get_limit(&self) -> Option { 58 | self.limit 59 | } 60 | } 61 | 62 | #[async_std::test] 63 | async fn smoke() { 64 | use async_std::prelude::*; 65 | let s = async_std::stream::repeat(5usize).take(3); 66 | let mut output = vec![]; 67 | let mut stream = crate::from_stream(s).map(|n| async move { n * 2 }); 68 | while let Some(n) = stream.next().await { 69 | output.push(n); 70 | } 71 | assert_eq!(output, vec![10usize; 3]); 72 | } 73 | -------------------------------------------------------------------------------- /src/par_stream/mod.rs: -------------------------------------------------------------------------------- 1 | use async_std::future::Future; 2 | use async_std::task::{Context, Poll}; 3 | 4 | use std::pin::Pin; 5 | 6 | use crate::FromParallelStream; 7 | 8 | pub use for_each::ForEach; 9 | pub use map::Map; 10 | pub use next::NextFuture; 11 | pub use take::Take; 12 | 13 | mod for_each; 14 | mod map; 15 | mod next; 16 | mod take; 17 | 18 | /// Parallel version of the standard `Stream` trait. 19 | pub trait ParallelStream: Sized + Send + Sync + Unpin + 'static { 20 | /// The type of items yielded by this stream. 21 | type Item: Send; 22 | 23 | /// Attempts to receive the next item from the stream. 24 | fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll>; 25 | 26 | /// Set a max concurrency limit 27 | fn limit(self, limit: impl Into>) -> Self; 28 | 29 | /// Get the max concurrency limit 30 | fn get_limit(&self) -> Option; 31 | 32 | /// Applies `f` to each item of this stream in parallel, producing a new 33 | /// stream with the results. 34 | fn map(self, f: F) -> Map 35 | where 36 | F: FnMut(Self::Item) -> Fut + Send + Sync + Copy + 'static, 37 | T: Send + 'static, 38 | Fut: Future + Send, 39 | { 40 | Map::new(self, f) 41 | } 42 | 43 | /// Applies `f` to each item of this stream in parallel, producing a new 44 | /// stream with the results. 45 | fn next(&mut self) -> NextFuture<'_, Self> { 46 | NextFuture::new(self) 47 | } 48 | 49 | /// Creates a stream that yields its first `n` elements. 50 | fn take(self, n: usize) -> Take 51 | where 52 | Self: Sized, 53 | { 54 | Take::new(self, n) 55 | } 56 | 57 | /// Applies `f` to each item of this stream in parallel. 58 | fn for_each(self, f: F) -> ForEach 59 | where 60 | F: FnMut(Self::Item) -> Fut + Send + Sync + Copy + 'static, 61 | Fut: Future + Send, 62 | { 63 | ForEach::new(self, f) 64 | } 65 | 66 | /// Transforms a stream into a collection. 67 | /// 68 | ///`collect()` can take anything streamable, and turn it into a relevant 69 | /// collection. This is one of the more powerful methods in the async 70 | /// standard library, used in a variety of contexts. 71 | fn collect<'a, B>(self) -> Pin + 'a + Send>> 72 | where 73 | Self: Sized + 'a, 74 | B: FromParallelStream, 75 | { 76 | FromParallelStream::from_par_stream(self) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/par_stream/next.rs: -------------------------------------------------------------------------------- 1 | use core::future::Future; 2 | use core::pin::Pin; 3 | use core::task::{Context, Poll}; 4 | 5 | use crate::ParallelStream; 6 | 7 | #[doc(hidden)] 8 | #[allow(missing_debug_implementations)] 9 | pub struct NextFuture<'a, S: Unpin + ?Sized> { 10 | stream: &'a mut S, 11 | } 12 | 13 | impl<'a, S: ParallelStream + Unpin + ?Sized> NextFuture<'a, S> { 14 | pub(crate) fn new(stream: &'a mut S) -> Self { 15 | Self { stream } 16 | } 17 | } 18 | 19 | impl Future for NextFuture<'_, S> { 20 | type Output = Option; 21 | 22 | fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { 23 | Pin::new(&mut *self.stream).poll_next(cx) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/par_stream/take.rs: -------------------------------------------------------------------------------- 1 | use core::pin::Pin; 2 | use core::task::{Context, Poll}; 3 | 4 | use async_std::task::ready; 5 | use pin_project_lite::pin_project; 6 | 7 | use crate::ParallelStream; 8 | 9 | pin_project! { 10 | /// A stream that yields the first `n` items of another stream. 11 | /// 12 | /// This `struct` is created by the [`take`] method on [`ParallelStream`]. See its 13 | /// documentation for more. 14 | /// 15 | /// [`take`]: trait.ParallelStream.html#method.take 16 | /// [`ParallelStream`]: trait.ParallelStream.html 17 | #[derive(Clone, Debug)] 18 | pub struct Take { 19 | #[pin] 20 | stream: S, 21 | remaining: usize, 22 | limit: Option, 23 | } 24 | } 25 | 26 | impl Take { 27 | pub(super) fn new(stream: S, remaining: usize) -> Self { 28 | Self { 29 | limit: stream.get_limit(), 30 | remaining, 31 | stream, 32 | } 33 | } 34 | } 35 | 36 | impl ParallelStream for Take { 37 | type Item = S::Item; 38 | 39 | fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 40 | let this = self.project(); 41 | if *this.remaining == 0 { 42 | Poll::Ready(None) 43 | } else { 44 | let next = ready!(this.stream.poll_next(cx)); 45 | match next { 46 | Some(_) => *this.remaining -= 1, 47 | None => *this.remaining = 0, 48 | } 49 | Poll::Ready(next) 50 | } 51 | } 52 | 53 | fn limit(mut self, limit: impl Into>) -> Self { 54 | self.limit = limit.into(); 55 | self 56 | } 57 | 58 | fn get_limit(&self) -> Option { 59 | self.limit 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/prelude.rs: -------------------------------------------------------------------------------- 1 | //! The parallel stream prelude. 2 | pub use crate::{FromParallelStream, IntoParallelStream, ParallelStream}; 3 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | // use core::pin::Pin; 2 | // use core::task::{Context, Poll}; 3 | 4 | // use std::sync::atomic::{AtomicUsize, Ordering}; 5 | // use std::sync::Arc; 6 | 7 | // use async_std::stream::Stream; 8 | 9 | // /// A stream that has a max concurrency of N. 10 | // pub(crate) struct LimitStream { 11 | // limit: Option, 12 | // ref_count: Arc, 13 | // } 14 | 15 | // impl LimitStream { 16 | // /// Create a new instance of LimitStream. 17 | // pub(crate) fn new(limit: Option) -> Self { 18 | // Self { 19 | // limit, 20 | // ref_count: Arc::new(AtomicUsize::new(0)), 21 | // } 22 | // } 23 | // } 24 | 25 | // #[derive(Debug)] 26 | // pub(crate) struct Guard { 27 | // limit: Option, 28 | // ref_count: Arc, 29 | // } 30 | 31 | // impl Guard { 32 | // fn new(limit: Option, ref_count: Arc) -> Self { 33 | // Self { limit, ref_count } 34 | // } 35 | // } 36 | 37 | // impl Drop for Guard { 38 | // fn drop(&mut self) { 39 | // if self.limit.is_some() { 40 | // self.ref_count.fetch_sub(1, Ordering::SeqCst); 41 | // } 42 | // } 43 | // } 44 | 45 | // impl Stream for LimitStream { 46 | // type Item = Guard; 47 | 48 | // fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 49 | // if self.limit.is_none() { 50 | // let guard = Guard::new(self.limit, self.ref_count.clone()); 51 | // return Poll::Ready(Some(guard)); 52 | // } 53 | // todo!(); 54 | // } 55 | // } 56 | -------------------------------------------------------------------------------- /src/vec.rs: -------------------------------------------------------------------------------- 1 | //! Parallel types for `Vec`. 2 | //! 3 | //! You will rarely need to interact with this module directly unless you need to 4 | //! name one of the stream types. 5 | 6 | use core::future::Future; 7 | use core::pin::Pin; 8 | use core::task::{Context, Poll}; 9 | 10 | use crate::{from_stream, FromParallelStream, FromStream, IntoParallelStream, ParallelStream}; 11 | 12 | use async_std::stream::{from_iter, FromIter}; 13 | use std::vec; 14 | 15 | pin_project_lite::pin_project! { 16 | /// Parallel stream that moves out of a vector. 17 | #[derive(Debug)] 18 | pub struct IntoParStream { 19 | #[pin] 20 | stream: FromStream>>, 21 | limit: Option, 22 | } 23 | } 24 | 25 | impl ParallelStream for IntoParStream { 26 | type Item = T; 27 | fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 28 | let this = self.project(); 29 | this.stream.poll_next(cx) 30 | } 31 | 32 | fn limit(mut self, limit: impl Into>) -> Self { 33 | self.limit = limit.into(); 34 | self 35 | } 36 | 37 | fn get_limit(&self) -> Option { 38 | self.limit 39 | } 40 | } 41 | 42 | impl IntoParallelStream for Vec { 43 | type Item = T; 44 | type IntoParStream = IntoParStream; 45 | 46 | #[inline] 47 | fn into_par_stream(self) -> Self::IntoParStream { 48 | IntoParStream { 49 | stream: from_stream(from_iter(self)), 50 | limit: None, 51 | } 52 | } 53 | } 54 | 55 | /// Collect items from a parallel stream into a vector. 56 | /// 57 | /// # Examples 58 | /// ``` 59 | /// use parallel_stream::prelude::*; 60 | /// 61 | /// #[async_std::main] 62 | /// async fn main() { 63 | /// let v = vec![1, 2, 3, 4]; 64 | /// let mut stream = v.into_par_stream().map(|n| async move { n * n }); 65 | /// let mut res = Vec::from_par_stream(stream).await; 66 | /// res.sort(); 67 | /// assert_eq!(res, vec![1, 4, 9, 16]); 68 | /// } 69 | /// ``` 70 | impl FromParallelStream for Vec { 71 | fn from_par_stream<'a, S>(stream: S) -> Pin + 'a + Send>> 72 | where 73 | S: IntoParallelStream + Send + 'a, 74 | { 75 | Box::pin(async move { 76 | let mut stream = stream.into_par_stream(); 77 | let mut res = Vec::with_capacity(0); 78 | while let Some(item) = stream.next().await { 79 | res.push(item); 80 | } 81 | res 82 | }) 83 | } 84 | } 85 | 86 | #[async_std::test] 87 | async fn smoke() { 88 | use crate::IntoParallelStream; 89 | 90 | let v = vec![1, 2, 3, 4]; 91 | let mut stream = v.into_par_stream().map(|n| async move { n * n }); 92 | 93 | let mut out = vec![]; 94 | while let Some(n) = stream.next().await { 95 | out.push(n); 96 | } 97 | out.sort_unstable(); 98 | 99 | assert_eq!(out, vec![1usize, 4, 9, 16]); 100 | } 101 | -------------------------------------------------------------------------------- /tests/test.rs: -------------------------------------------------------------------------------- 1 | 2 | --------------------------------------------------------------------------------