├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ ├── bench.yml │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── Makefile ├── README.md ├── benches └── futures_batch_benchmark.rs └── src └── lib.rs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: mre 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "04:00" 8 | open-pull-requests-limit: 10 9 | -------------------------------------------------------------------------------- /.github/workflows/bench.yml: -------------------------------------------------------------------------------- 1 | on: 2 | - pull_request 3 | - workflow_dispatch 4 | 5 | name: criterion benchmark 6 | jobs: 7 | runBenchmark: 8 | name: run benchmark 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v3 12 | - uses: boa-dev/criterion-compare-action@v3 13 | with: 14 | # Use the base branch name as the branch to compare with 15 | branchName: ${{ github.base_ref }} 16 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - master 8 | workflow_dispatch: 9 | schedule: 10 | - cron: "00 04 * * *" 11 | 12 | jobs: 13 | ci: 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | fail-fast: false 17 | matrix: 18 | os: [ubuntu-latest, windows-latest, macOS-latest] 19 | rust: 20 | - stable 21 | - beta 22 | - nightly 23 | steps: 24 | - uses: actions/checkout@v1 25 | 26 | - name: Install Rust 27 | uses: actions-rs/toolchain/@v1 28 | with: 29 | profile: minimal 30 | toolchain: ${{ matrix.rust }} 31 | override: true 32 | components: clippy 33 | 34 | - name: Build 35 | uses: actions-rs/cargo@v1 36 | with: 37 | command: build 38 | 39 | - name: Run Tests 40 | uses: actions-rs/cargo@v1 41 | with: 42 | command: test 43 | 44 | - name: Audit for Security Vulnerabilities 45 | uses: actions-rs/audit-check@v1 46 | with: 47 | token: ${{ secrets.GITHUB_TOKEN }} 48 | 49 | - name: Generate Docs 50 | uses: actions-rs/cargo@v1 51 | with: 52 | command: doc 53 | args: --all-features --no-deps 54 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | .idea 13 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Matthias Endler "] 3 | description = "An adaptor that chunks up elements and flushes them after a timeout or when the buffer is full. (Formerly known as tokio-batch.)" 4 | license = "MIT OR Apache-2.0" 5 | name = "futures-batch" 6 | version = "0.6.1" 7 | edition = "2018" 8 | repository = "https://github.com/mre/futures-batch" 9 | 10 | [lib] 11 | # https://bheisler.github.io/criterion.rs/book/faq.html#cargo-bench-gives-unrecognized-option-errors-for-valid-command-line-options 12 | bench = false 13 | 14 | [dependencies] 15 | futures = { version = "0.3", features = ["async-await"] } 16 | pin-utils = "0.1.0" 17 | futures-timer = "3.0.2" 18 | 19 | [dev-dependencies] 20 | tokio = { version = "1.22", features = ["macros", "rt-multi-thread"] } 21 | criterion = { version = "0.6", features = ["html_reports", "async_tokio"] } 22 | 23 | [dev-dependencies.doc-comment] 24 | version = "0.3" 25 | 26 | [[bench]] 27 | name = "futures_batch_benchmark" 28 | harness = false 29 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Needed SHELL since I'm using zsh 2 | SHELL := /bin/bash 3 | 4 | .PHONY: help 5 | help: ## This help message 6 | @echo -e "$$(grep -hE '^\S+:.*##' $(MAKEFILE_LIST) | sed -e 's/:.*##\s*/:/' -e 's/^\(.\+\):\(.*\)/\\x1b[36m\1\\x1b[m:\2/' | column -c2 -t -s :)" 7 | 8 | .PHONY: build 9 | build: ## Build Rust code locally 10 | cargo build 11 | 12 | .PHONY: docs 13 | docs: ## Generate and show documentation 14 | cargo doc --open 15 | 16 | .PHONY: test 17 | test: ## Run tests 18 | cargo test 19 | 20 | .PHONY: lint 21 | lint: ## Run linter 22 | cargo clippy --all-targets --all-features -- -D warnings 23 | 24 | .PHONY: publish 25 | publish: ## Publish to crates.io 26 | cargo publish -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # futures-batch 2 | 3 | ![Build status](https://github.com/mre/futures-batch/workflows/Rust/badge.svg) 4 | [![Cargo](https://img.shields.io/crates/v/futures-batch.svg)](https://crates.io/crates/futures-batch) 5 | [![Documentation](https://docs.rs/futures-batch/badge.svg)](https://docs.rs/futures-batch) 6 | 7 | An adaptor that chunks up completed futures in a stream and flushes them after a timeout or when the buffer is full. 8 | It is based on the `Chunks` adaptor of [futures-util](https://github.com/rust-lang-nursery/futures-rs/blob/4613193023dd4071bbd32b666e3b85efede3a725/futures-util/src/stream/chunks.rs), to which we added a timeout. 9 | 10 | (The project was initially called `tokio-batch`, but was renamed as it has no dependency on Tokio anymore.) 11 | 12 | ## Usage 13 | 14 | Either as a standalone stream operator or directly as a combinator: 15 | 16 | ```rust 17 | use std::time::Duration; 18 | use futures::{stream, StreamExt}; 19 | use futures_batch::ChunksTimeoutStreamExt; 20 | 21 | #[tokio::main] 22 | async fn main() { 23 | let results = stream::iter(0..10) 24 | .chunks_timeout(5, Duration::new(10, 0)) 25 | .collect::>(); 26 | 27 | assert_eq!(vec![vec![0, 1, 2, 3, 4], vec![5, 6, 7, 8, 9]], results.await); 28 | } 29 | ``` 30 | 31 | The above code iterates over a stream and creates chunks of size 5 with a timeout of 10 seconds. 32 | _Note:_ This is using the [`futures 0.3`](https://crates.io/crates/futures) crate. 33 | 34 | ## Performance 35 | 36 | `futures-batch` imposes very low overhead on your application. For example, it [is even used to batch syscalls](https://github.com/mre/futures-batch/issues/4). 37 | Under the hood, we are using [`futures-timer`](https://github.com/async-rs/futures-timer), which allows for a microsecond timer resolution. 38 | If you find a use-case which is not covered, don't be reluctant to open an issue. 39 | 40 | ## Credits 41 | 42 | Thanks to [arielb1](https://github.com/arielb1), [alexcrichton](https://github.com/alexcrichton/), [doyoubi](https://github.com/doyoubi), [leshow](https://github.com/leshow), [spebern](https://github.com/spebern), and [wngr](https://github.com/wngr) for their contributions! 43 | -------------------------------------------------------------------------------- /benches/futures_batch_benchmark.rs: -------------------------------------------------------------------------------- 1 | use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput}; 2 | use futures::stream::{self, Stream}; 3 | use futures_batch::ChunksTimeoutStreamExt; 4 | use std::time::Duration; 5 | use tokio::runtime::Runtime; 6 | 7 | async fn batch(stream: impl Stream + Unpin) { 8 | let _ = stream.chunks_timeout(5, Duration::new(10, 0)); 9 | } 10 | 11 | fn criterion_benchmark(c: &mut Criterion) { 12 | let rt = Runtime::new().unwrap(); 13 | 14 | let mut group = c.benchmark_group("futures_batch"); 15 | for &size in &[1000, 10_000, 100_000, 1_000_000, 10_000_000] { 16 | group.throughput(Throughput::Bytes(size as u64)); 17 | group.bench_with_input(BenchmarkId::from_parameter(size), &size, |b, &size| { 18 | b.to_async(&rt).iter(|| batch(stream::iter(0..size))); 19 | }); 20 | } 21 | group.finish(); 22 | } 23 | 24 | criterion_group!(benches, criterion_benchmark); 25 | criterion_main!(benches); 26 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! An adaptor that chunks up completed futures in a stream and flushes them after a timeout or when the buffer is full. 2 | //! It is based on the `Chunks` adaptor of [futures-util](https://github.com/rust-lang-nursery/futures-rs/blob/4613193023dd4071bbd32b666e3b85efede3a725/futures-util/src/stream/chunks.rs), to which we added a timeout. 3 | //! 4 | //! ## Usage 5 | //! 6 | //! Either as a standalone stream operator or directly as a combinator: 7 | //! 8 | //! ```rust 9 | //! use std::time::Duration; 10 | //! use futures::{stream, StreamExt}; 11 | //! use futures_batch::ChunksTimeoutStreamExt; 12 | //! 13 | //! #[tokio::main] 14 | //! async fn main() { 15 | //! let results = stream::iter(0..10) 16 | //! .chunks_timeout(5, Duration::new(10, 0)) 17 | //! .collect::>(); 18 | //! 19 | //! assert_eq!(vec![vec![0, 1, 2, 3, 4], vec![5, 6, 7, 8, 9]], results.await); 20 | //! } 21 | //! ``` 22 | //! 23 | //! The above code iterates over a stream and creates chunks of size 5 with a timeout of 10 seconds. 24 | 25 | #[cfg(test)] 26 | #[macro_use] 27 | extern crate doc_comment; 28 | 29 | #[cfg(test)] 30 | doctest!("../README.md"); 31 | 32 | use core::mem; 33 | use core::pin::Pin; 34 | use futures::stream::{Fuse, FusedStream, Stream}; 35 | use futures::task::{Context, Poll}; 36 | use futures::Future; 37 | use futures::StreamExt; 38 | #[cfg(feature = "sink")] 39 | use futures_sink::Sink; 40 | use pin_utils::{unsafe_pinned, unsafe_unpinned}; 41 | 42 | use futures_timer::Delay; 43 | use std::time::Duration; 44 | 45 | /// A Stream extension trait allowing you to call `chunks_timeout` on anything 46 | /// which implements `Stream`. 47 | pub trait ChunksTimeoutStreamExt: Stream { 48 | fn chunks_timeout(self, capacity: usize, duration: Duration) -> ChunksTimeout 49 | where 50 | Self: Sized, 51 | { 52 | ChunksTimeout::new(self, capacity, duration) 53 | } 54 | } 55 | impl ChunksTimeoutStreamExt for T where T: Stream {} 56 | 57 | /// A Stream of chunks. 58 | #[derive(Debug)] 59 | #[must_use = "streams do nothing unless polled"] 60 | pub struct ChunksTimeout { 61 | stream: Fuse, 62 | items: Vec, 63 | cap: usize, 64 | // https://github.com/rust-lang-nursery/futures-rs/issues/1475 65 | clock: Option, 66 | duration: Duration, 67 | } 68 | 69 | impl Unpin for ChunksTimeout {} 70 | 71 | impl ChunksTimeout 72 | where 73 | St: Stream, 74 | { 75 | unsafe_unpinned!(items: Vec); 76 | unsafe_pinned!(clock: Option); 77 | unsafe_pinned!(stream: Fuse); 78 | 79 | pub fn new(stream: St, capacity: usize, duration: Duration) -> ChunksTimeout { 80 | assert!(capacity > 0); 81 | 82 | ChunksTimeout { 83 | stream: stream.fuse(), 84 | items: Vec::with_capacity(capacity), 85 | cap: capacity, 86 | clock: None, 87 | duration, 88 | } 89 | } 90 | 91 | fn take(mut self: Pin<&mut Self>) -> Vec { 92 | let cap = self.cap; 93 | mem::replace(self.as_mut().items(), Vec::with_capacity(cap)) 94 | } 95 | 96 | /// Acquires a reference to the underlying stream that this combinator is 97 | /// pulling from. 98 | pub fn get_ref(&self) -> &St { 99 | self.stream.get_ref() 100 | } 101 | 102 | /// Acquires a mutable reference to the underlying stream that this 103 | /// combinator is pulling from. 104 | /// 105 | /// Note that care must be taken to avoid tampering with the state of the 106 | /// stream which may otherwise confuse this combinator. 107 | pub fn get_mut(&mut self) -> &mut St { 108 | self.stream.get_mut() 109 | } 110 | 111 | /// Acquires a pinned mutable reference to the underlying stream that this 112 | /// combinator is pulling from. 113 | /// 114 | /// Note that care must be taken to avoid tampering with the state of the 115 | /// stream which may otherwise confuse this combinator. 116 | pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut St> { 117 | self.stream().get_pin_mut() 118 | } 119 | 120 | /// Consumes this combinator, returning the underlying stream. 121 | /// 122 | /// Note that this may discard intermediate state of this combinator, so 123 | /// care should be taken to avoid losing resources when this is called. 124 | pub fn into_inner(self) -> St { 125 | self.stream.into_inner() 126 | } 127 | } 128 | 129 | impl Stream for ChunksTimeout { 130 | type Item = Vec; 131 | 132 | fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 133 | loop { 134 | match self.as_mut().stream().poll_next(cx) { 135 | Poll::Ready(item) => match item { 136 | // Push the item into the buffer and check whether it is full. 137 | // If so, replace our buffer with a new and empty one and return 138 | // the full one. 139 | Some(item) => { 140 | if self.items.is_empty() { 141 | *self.as_mut().clock() = Some(Delay::new(self.duration)); 142 | } 143 | self.as_mut().items().push(item); 144 | if self.items.len() >= self.cap { 145 | *self.as_mut().clock() = None; 146 | return Poll::Ready(Some(self.as_mut().take())); 147 | } else { 148 | // Continue the loop 149 | continue; 150 | } 151 | } 152 | 153 | // Since the underlying stream ran out of values, return what we 154 | // have buffered, if we have anything. 155 | None => { 156 | let last = if self.items.is_empty() { 157 | None 158 | } else { 159 | let full_buf = mem::take(self.as_mut().items()); 160 | Some(full_buf) 161 | }; 162 | 163 | return Poll::Ready(last); 164 | } 165 | }, 166 | // Don't return here, as we need to need check the clock. 167 | Poll::Pending => {} 168 | } 169 | 170 | match self 171 | .as_mut() 172 | .clock() 173 | .as_pin_mut() 174 | .map(|clock| clock.poll(cx)) 175 | { 176 | Some(Poll::Ready(())) => { 177 | *self.as_mut().clock() = None; 178 | return Poll::Ready(Some(self.as_mut().take())); 179 | } 180 | Some(Poll::Pending) => {} 181 | None => { 182 | debug_assert!( 183 | self.items().is_empty(), 184 | "Inner buffer is empty, but clock is available." 185 | ); 186 | } 187 | } 188 | 189 | return Poll::Pending; 190 | } 191 | } 192 | 193 | fn size_hint(&self) -> (usize, Option) { 194 | let chunk_len = if self.items.is_empty() { 0 } else { 1 }; 195 | let (lower, upper) = self.stream.size_hint(); 196 | let lower = lower.saturating_add(chunk_len); 197 | let upper = match upper { 198 | Some(x) => x.checked_add(chunk_len), 199 | None => None, 200 | }; 201 | (lower, upper) 202 | } 203 | } 204 | 205 | impl FusedStream for ChunksTimeout { 206 | fn is_terminated(&self) -> bool { 207 | self.stream.is_terminated() & self.items.is_empty() 208 | } 209 | } 210 | 211 | // Forwarding impl of Sink from the underlying stream 212 | #[cfg(feature = "sink")] 213 | impl Sink for ChunksTimeout 214 | where 215 | S: Stream + Sink, 216 | { 217 | type Error = S::Error; 218 | 219 | delegate_sink!(stream, Item); 220 | } 221 | 222 | #[cfg(test)] 223 | mod tests { 224 | use super::*; 225 | use futures::{stream, FutureExt, StreamExt}; 226 | use std::iter; 227 | use std::time::{Duration, Instant}; 228 | 229 | #[tokio::test] 230 | async fn messages_pass_through() { 231 | let results = stream::iter(iter::once(5)) 232 | .chunks_timeout(5, Duration::new(1, 0)) 233 | .collect::>(); 234 | assert_eq!(vec![vec![5]], results.await); 235 | } 236 | 237 | #[tokio::test] 238 | async fn message_chunks() { 239 | let stream = stream::iter(0..10); 240 | 241 | let chunk_stream = ChunksTimeout::new(stream, 5, Duration::new(1, 0)); 242 | assert_eq!( 243 | vec![vec![0, 1, 2, 3, 4], vec![5, 6, 7, 8, 9]], 244 | chunk_stream.collect::>().await 245 | ); 246 | } 247 | 248 | #[tokio::test] 249 | async fn message_early_exit() { 250 | let iter = vec![1, 2, 3, 4].into_iter(); 251 | let stream = stream::iter(iter); 252 | 253 | let chunk_stream = ChunksTimeout::new(stream, 5, Duration::new(1, 0)); 254 | assert_eq!( 255 | vec![vec![1, 2, 3, 4]], 256 | chunk_stream.collect::>().await 257 | ); 258 | } 259 | 260 | #[tokio::test] 261 | async fn message_timeout() { 262 | let iter = vec![1, 2, 3, 4].into_iter(); 263 | let stream0 = stream::iter(iter); 264 | 265 | let iter = vec![5].into_iter(); 266 | let stream1 = stream::iter(iter) 267 | .then(move |n| Delay::new(Duration::from_millis(300)).map(move |_| n)); 268 | 269 | let iter = vec![6, 7, 8].into_iter(); 270 | let stream2 = stream::iter(iter); 271 | 272 | let stream = stream0.chain(stream1).chain(stream2); 273 | let chunk_stream = ChunksTimeout::new(stream, 5, Duration::from_millis(100)); 274 | 275 | let now = Instant::now(); 276 | let min_times = [Duration::from_millis(80), Duration::from_millis(150)]; 277 | let max_times = [Duration::from_millis(350), Duration::from_millis(500)]; 278 | let expected = vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]]; 279 | let mut i = 0; 280 | 281 | let results = chunk_stream 282 | .map(move |s| { 283 | let now2 = Instant::now(); 284 | println!("{}: {:?} {:?}", i, now2 - now, s); 285 | assert!((now2 - now) < max_times[i]); 286 | assert!((now2 - now) > min_times[i]); 287 | i += 1; 288 | s 289 | }) 290 | .collect::>(); 291 | 292 | assert_eq!(results.await, expected); 293 | } 294 | } 295 | --------------------------------------------------------------------------------