├── .circleci └── config.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── lib.rs ├── slice.rs └── sources.rs /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | restore_registry: &RESTORE_REGISTRY 2 | restore_cache: 3 | key: registry 4 | save_registry: &SAVE_REGISTRY 5 | save_cache: 6 | key: registry-{{ .BuildNum }} 7 | paths: 8 | - /usr/local/cargo/registry/index 9 | deps_key: &DEPS_KEY 10 | key: deps-{{ checksum "~/rust-version" }}-{{ checksum "Cargo.lock" }} 11 | restore_deps: &RESTORE_DEPS 12 | restore_cache: 13 | <<: *DEPS_KEY 14 | save_deps: &SAVE_DEPS 15 | save_cache: 16 | <<: *DEPS_KEY 17 | paths: 18 | - target 19 | - /usr/local/cargo/registry/cache 20 | 21 | version: 2 22 | jobs: 23 | build: 24 | docker: 25 | - image: rust:1.56.0 26 | working_directory: ~/build 27 | environment: 28 | RUSTFLAGS: -D warnings 29 | steps: 30 | - checkout 31 | - *RESTORE_REGISTRY 32 | - run: cargo generate-lockfile 33 | - *SAVE_REGISTRY 34 | - run: rustc --version > ~/rust-version 35 | - *RESTORE_DEPS 36 | - run: cargo test 37 | - run: cargo test --features alloc 38 | - run: cargo test --features std 39 | - *SAVE_DEPS 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | .idea 4 | *.iml 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "streaming-iterator" 3 | version = "0.1.9" 4 | authors = ["Steven Fackler "] 5 | license = "MIT OR Apache-2.0" 6 | description = "Streaming iterators" 7 | repository = "https://github.com/sfackler/streaming-iterator" 8 | readme = "README.md" 9 | edition = "2021" 10 | rust-version = "1.56" 11 | 12 | [package.metadata.docs.rs] 13 | features = ["std"] 14 | 15 | [features] 16 | alloc = [] 17 | std = ["alloc"] 18 | 19 | [dependencies] 20 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Steven Fackler 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # streaming-iterator 2 | 3 | [![CircleCI](https://circleci.com/gh/sfackler/streaming-iterator.svg?style=badge)](https://circleci.com/gh/sfackler/streaming-iterator) 4 | 5 | [Documentation](https://docs.rs/streaming-iterator) 6 | 7 | Streaming iterators for Rust. 8 | 9 | ## License 10 | 11 | Licensed under either of 12 | 13 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 14 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 15 | 16 | at your option. 17 | 18 | ### Contribution 19 | 20 | Unless you explicitly state otherwise, any contribution intentionally 21 | submitted for inclusion in the work by you, as defined in the Apache-2.0 22 | license, shall be dual licensed as above, without any additional terms or 23 | conditions. 24 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Streaming iterators. 2 | //! 3 | //! The iterator APIs in the Rust standard library do not allow elements to be yielded which borrow 4 | //! from the iterator itself. That means, for example, that the `std::io::Lines` iterator must 5 | //! allocate a new `String` for each line rather than reusing an internal buffer. The 6 | //! `StreamingIterator` trait instead provides access to elements being iterated over only by 7 | //! reference rather than by value. 8 | //! 9 | //! `StreamingIterator`s cannot be used in Rust `for` loops, but `while let` loops offer a similar 10 | //! level of ergonomics: 11 | //! 12 | //! ```ignore 13 | //! while let Some(item) = iter.next() { 14 | //! // work with item 15 | //! } 16 | //! ``` 17 | //! 18 | //! However, **make sure to only use the above form with a mutable reference to an existing iterator**, 19 | //! not with an expression that creates an iterator. 20 | //! For example, the following code will loop forever over the first element of the array: 21 | //! 22 | //! ```no_run 23 | //! use streaming_iterator::{convert, StreamingIterator}; 24 | //! let array = [0, 1, 2, 3]; 25 | //! 26 | //! while let Some(item) = convert(array.iter()).next() { 27 | //! // This is an infinite loop! 28 | //! } 29 | //! ``` 30 | //! 31 | //! While the standard `Iterator` trait's functionality is based off of the `next` method, 32 | //! `StreamingIterator`'s functionality is based off of a pair of methods: `advance` and `get`. This 33 | //! essentially splits the logic of `next` in half (in fact, `StreamingIterator`'s `next` method 34 | //! does nothing but call `advance` followed by `get`). 35 | //! 36 | //! This is required because of Rust's lexical handling of borrows (more specifically a lack of 37 | //! single entry, multiple exit borrows). If `StreamingIterator` was defined like `Iterator` with 38 | //! just a required `next` method, operations like `filter` would be impossible to define. 39 | #![doc(html_root_url = "https://docs.rs/streaming-iterator/0.1")] 40 | #![warn(missing_docs)] 41 | #![no_std] 42 | 43 | #[cfg(feature = "alloc")] 44 | extern crate alloc; 45 | 46 | use core::cmp; 47 | 48 | #[cfg(feature = "alloc")] 49 | use alloc::{borrow::ToOwned, boxed::Box}; 50 | 51 | mod slice; 52 | pub use crate::slice::{windows_mut, WindowsMut}; 53 | 54 | mod sources; 55 | pub use crate::sources::{convert, Convert}; 56 | pub use crate::sources::{convert_mut, ConvertMut}; 57 | pub use crate::sources::{convert_ref, ConvertRef}; 58 | pub use crate::sources::{empty, Empty}; 59 | pub use crate::sources::{from_fn, FromFn}; 60 | pub use crate::sources::{once, Once}; 61 | pub use crate::sources::{once_with, OnceWith}; 62 | pub use crate::sources::{repeat, Repeat}; 63 | pub use crate::sources::{repeat_with, RepeatWith}; 64 | pub use crate::sources::{successors, Successors}; 65 | 66 | /// An interface for dealing with streaming iterators. 67 | pub trait StreamingIterator { 68 | /// The type of the elements being iterated over. 69 | type Item: ?Sized; 70 | 71 | /// Advances the iterator to the next element. 72 | /// 73 | /// Iterators start just before the first element, so this should be called before `get`. 74 | /// 75 | /// The behavior of calling this method after the end of the iterator has been reached is 76 | /// unspecified. 77 | fn advance(&mut self); 78 | 79 | /// Returns a reference to the current element of the iterator. 80 | /// 81 | /// The behavior of calling this method before `advance` has been called is unspecified. 82 | fn get(&self) -> Option<&Self::Item>; 83 | 84 | /// Advances the iterator and returns the next value. 85 | /// 86 | /// The behavior of calling this method after the end of the iterator has been reached is 87 | /// unspecified. 88 | /// 89 | /// The default implementation simply calls `advance` followed by `get`. 90 | #[inline] 91 | fn next(&mut self) -> Option<&Self::Item> { 92 | self.advance(); 93 | (*self).get() 94 | } 95 | 96 | /// Returns the bounds on the remaining length of the iterator. 97 | #[inline] 98 | fn size_hint(&self) -> (usize, Option) { 99 | (0, None) 100 | } 101 | 102 | /// Checks if `get()` will return `None`. 103 | fn is_done(&self) -> bool { 104 | self.get().is_none() 105 | } 106 | 107 | /// Determines if all elements of the iterator satisfy a predicate. 108 | #[inline] 109 | fn all(&mut self, mut f: F) -> bool 110 | where 111 | Self: Sized, 112 | F: FnMut(&Self::Item) -> bool, 113 | { 114 | while let Some(i) = self.next() { 115 | if !f(i) { 116 | return false; 117 | } 118 | } 119 | 120 | true 121 | } 122 | 123 | /// Determines if any elements of the iterator satisfy a predicate. 124 | #[inline] 125 | fn any(&mut self, mut f: F) -> bool 126 | where 127 | Self: Sized, 128 | F: FnMut(&Self::Item) -> bool, 129 | { 130 | !self.all(|i| !f(i)) 131 | } 132 | 133 | /// Borrows an iterator, rather than consuming it. 134 | /// 135 | /// This is useful to allow the application of iterator adaptors while still retaining ownership 136 | /// of the original adaptor. 137 | #[inline] 138 | fn by_ref(&mut self) -> &mut Self 139 | where 140 | Self: Sized, 141 | { 142 | self 143 | } 144 | 145 | /// Consumes two iterators and returns a new iterator that iterates over both in sequence. 146 | #[inline] 147 | fn chain(self, other: I) -> Chain 148 | where 149 | Self: Sized, 150 | I: StreamingIterator + Sized, 151 | { 152 | Chain { 153 | a: self, 154 | b: other, 155 | state: ChainState::BothForward, 156 | } 157 | } 158 | 159 | /// Produces a normal, non-streaming, iterator by cloning the elements of this iterator. 160 | #[inline] 161 | fn cloned(self) -> Cloned 162 | where 163 | Self: Sized, 164 | Self::Item: Clone, 165 | { 166 | Cloned(self) 167 | } 168 | 169 | /// Produces a normal, non-streaming, iterator by copying the elements of this iterator. 170 | #[inline] 171 | fn copied(self) -> Copied 172 | where 173 | Self: Sized, 174 | Self::Item: Copy, 175 | { 176 | Copied(self) 177 | } 178 | 179 | /// Consumes the iterator, counting the number of remaining elements and returning it. 180 | #[inline] 181 | fn count(self) -> usize 182 | where 183 | Self: Sized, 184 | { 185 | self.fold(0, |count, _| count + 1) 186 | } 187 | 188 | /// Creates an iterator which uses a closure to determine if an element should be yielded. 189 | #[inline] 190 | fn filter(self, f: F) -> Filter 191 | where 192 | Self: Sized, 193 | F: FnMut(&Self::Item) -> bool, 194 | { 195 | Filter { it: self, f } 196 | } 197 | 198 | /// Creates an iterator which both filters and maps by applying a closure to elements. 199 | #[inline] 200 | fn filter_map(self, f: F) -> FilterMap 201 | where 202 | Self: Sized, 203 | F: FnMut(&Self::Item) -> Option, 204 | { 205 | FilterMap { 206 | it: self, 207 | f, 208 | item: None, 209 | } 210 | } 211 | 212 | /// Creates an iterator which flattens iterators obtained by applying a closure to elements. 213 | /// Note that the returned iterators must be streaming iterators. 214 | #[inline] 215 | fn flat_map(self, f: F) -> FlatMap 216 | where 217 | Self: Sized, 218 | J: StreamingIterator, 219 | F: FnMut(&Self::Item) -> J, 220 | { 221 | FlatMap { 222 | it: self, 223 | f, 224 | sub_iter: None, 225 | } 226 | } 227 | 228 | /// Creates a regular, non-streaming iterator which both filters and maps by applying a closure to elements. 229 | #[inline] 230 | fn filter_map_deref(self, f: F) -> FilterMapDeref 231 | where 232 | Self: Sized, 233 | F: FnMut(&Self::Item) -> Option, 234 | { 235 | FilterMapDeref { it: self, f } 236 | } 237 | 238 | /// Returns the first element of the iterator that satisfies the predicate. 239 | #[inline] 240 | fn find(&mut self, mut f: F) -> Option<&Self::Item> 241 | where 242 | Self: Sized, 243 | F: FnMut(&Self::Item) -> bool, 244 | { 245 | loop { 246 | self.advance(); 247 | match self.get() { 248 | Some(i) => { 249 | if f(i) { 250 | break; 251 | } 252 | } 253 | None => break, 254 | } 255 | } 256 | 257 | (*self).get() 258 | } 259 | 260 | /// Creates an iterator which is "well behaved" at the beginning and end of iteration. 261 | /// 262 | /// The behavior of calling `get` before iteration has been started, and of continuing to call 263 | /// `advance` after `get` has returned `None` is normally unspecified, but this guarantees that 264 | /// `get` will return `None` in both cases. 265 | #[inline] 266 | fn fuse(self) -> Fuse 267 | where 268 | Self: Sized, 269 | { 270 | Fuse { 271 | it: self, 272 | state: FuseState::Start, 273 | } 274 | } 275 | 276 | /// Call a closure on each element, passing the element on. 277 | /// The closure is called upon calls to `advance` or `advance_back`, and exactly once per element 278 | /// regardless of how many times (if any) `get` is called. 279 | #[inline] 280 | fn inspect(self, f: F) -> Inspect 281 | where 282 | F: FnMut(&Self::Item), 283 | Self: Sized, 284 | { 285 | Inspect { it: self, f } 286 | } 287 | 288 | /// Creates an iterator which transforms elements of this iterator by passing them to a closure. 289 | #[inline] 290 | fn map(self, f: F) -> Map 291 | where 292 | Self: Sized, 293 | F: FnMut(&Self::Item) -> B, 294 | { 295 | Map { 296 | it: self, 297 | f, 298 | item: None, 299 | } 300 | } 301 | 302 | /// Creates a regular, non-streaming iterator which transforms elements of this iterator by passing them to a closure. 303 | #[inline] 304 | fn map_deref(self, f: F) -> MapDeref 305 | where 306 | Self: Sized, 307 | F: FnMut(&Self::Item) -> B, 308 | { 309 | MapDeref { it: self, f } 310 | } 311 | 312 | /// Creates an iterator which transforms elements of this iterator by passing them to a closure. 313 | /// 314 | /// Unlike `map`, this method takes a closure that returns a reference into the original value. 315 | /// 316 | /// The mapping function is only guaranteed to be called at some point before an element 317 | /// is actually consumed. This allows an expensive mapping function to be ignored 318 | /// during skipping (e.g. `nth`). 319 | #[inline] 320 | fn map_ref(self, f: F) -> MapRef 321 | where 322 | Self: Sized, 323 | F: Fn(&Self::Item) -> &B, 324 | { 325 | MapRef { it: self, f } 326 | } 327 | 328 | /// Consumes the first `n` elements of the iterator, returning the next one. 329 | #[inline] 330 | fn nth(&mut self, n: usize) -> Option<&Self::Item> { 331 | for _ in 0..n { 332 | self.advance(); 333 | if self.is_done() { 334 | return None; 335 | } 336 | } 337 | self.next() 338 | } 339 | 340 | /// Creates a normal, non-streaming, iterator with elements produced by calling `to_owned` on 341 | /// the elements of this iterator. 342 | /// 343 | /// Requires the `alloc` feature. 344 | #[cfg(feature = "alloc")] 345 | #[inline] 346 | fn owned(self) -> Owned 347 | where 348 | Self: Sized, 349 | Self::Item: ToOwned, 350 | { 351 | Owned(self) 352 | } 353 | 354 | /// Returns the index of the first element of the iterator matching a predicate. 355 | #[inline] 356 | fn position(&mut self, mut f: F) -> Option 357 | where 358 | Self: Sized, 359 | F: FnMut(&Self::Item) -> bool, 360 | { 361 | let mut n = 0; 362 | 363 | while let Some(i) = self.next() { 364 | if f(i) { 365 | return Some(n); 366 | } 367 | n += 1; 368 | } 369 | 370 | None 371 | } 372 | 373 | /// Creates an iterator which skips the first `n` elements. 374 | #[inline] 375 | fn skip(self, n: usize) -> Skip 376 | where 377 | Self: Sized, 378 | { 379 | Skip { it: self, n } 380 | } 381 | 382 | /// Creates an iterator that skips initial elements matching a predicate. 383 | #[inline] 384 | fn skip_while(self, f: F) -> SkipWhile 385 | where 386 | Self: Sized, 387 | F: FnMut(&Self::Item) -> bool, 388 | { 389 | SkipWhile { 390 | it: self, 391 | f, 392 | done: false, 393 | } 394 | } 395 | 396 | /// Creates an iterator which only returns the first `n` elements. 397 | #[inline] 398 | fn take(self, n: usize) -> Take 399 | where 400 | Self: Sized, 401 | { 402 | Take { 403 | it: self, 404 | n, 405 | done: false, 406 | } 407 | } 408 | 409 | /// Creates an iterator which only returns initial elements matching a predicate. 410 | #[inline] 411 | fn take_while(self, f: F) -> TakeWhile 412 | where 413 | Self: Sized, 414 | F: FnMut(&Self::Item) -> bool, 415 | { 416 | TakeWhile { 417 | it: self, 418 | f, 419 | done: false, 420 | } 421 | } 422 | 423 | /// Creates an iterator which returns elemens in the opposite order. 424 | #[inline] 425 | fn rev(self) -> Rev 426 | where 427 | Self: Sized + DoubleEndedStreamingIterator, 428 | { 429 | Rev(self) 430 | } 431 | 432 | /// Reduces the iterator's elements to a single, final value. 433 | #[inline] 434 | fn fold(mut self, init: B, mut f: F) -> B 435 | where 436 | Self: Sized, 437 | F: FnMut(B, &Self::Item) -> B, 438 | { 439 | let mut acc = init; 440 | while let Some(item) = self.next() { 441 | acc = f(acc, item); 442 | } 443 | acc 444 | } 445 | 446 | /// Calls a closure on each element of an iterator. 447 | #[inline] 448 | fn for_each(self, mut f: F) 449 | where 450 | Self: Sized, 451 | F: FnMut(&Self::Item), 452 | { 453 | self.fold((), move |(), item| f(item)); 454 | } 455 | } 456 | 457 | impl<'a, I: ?Sized> StreamingIterator for &'a mut I 458 | where 459 | I: StreamingIterator, 460 | { 461 | type Item = I::Item; 462 | 463 | #[inline] 464 | fn advance(&mut self) { 465 | (**self).advance() 466 | } 467 | 468 | #[inline] 469 | fn is_done(&self) -> bool { 470 | (**self).is_done() 471 | } 472 | 473 | #[inline] 474 | fn get(&self) -> Option<&Self::Item> { 475 | (**self).get() 476 | } 477 | 478 | #[inline] 479 | fn size_hint(&self) -> (usize, Option) { 480 | (**self).size_hint() 481 | } 482 | 483 | #[inline] 484 | fn next(&mut self) -> Option<&Self::Item> { 485 | (**self).next() 486 | } 487 | } 488 | 489 | #[cfg(feature = "alloc")] 490 | impl StreamingIterator for Box 491 | where 492 | I: StreamingIterator, 493 | { 494 | type Item = I::Item; 495 | 496 | #[inline] 497 | fn advance(&mut self) { 498 | (**self).advance() 499 | } 500 | 501 | #[inline] 502 | fn is_done(&self) -> bool { 503 | (**self).is_done() 504 | } 505 | 506 | #[inline] 507 | fn get(&self) -> Option<&Self::Item> { 508 | (**self).get() 509 | } 510 | 511 | #[inline] 512 | fn size_hint(&self) -> (usize, Option) { 513 | (**self).size_hint() 514 | } 515 | 516 | #[inline] 517 | fn next(&mut self) -> Option<&Self::Item> { 518 | (**self).next() 519 | } 520 | } 521 | 522 | /// A streaming iterator able to yield elements from both ends. 523 | pub trait DoubleEndedStreamingIterator: StreamingIterator { 524 | /// Advances the iterator to the next element from the back of the iterator. 525 | /// 526 | /// Double ended iterators just after the last element, so this should be called before `get` 527 | /// when iterating in reverse. 528 | /// 529 | /// The behavior of calling this method after the iterator has been exhausted is unspecified. 530 | fn advance_back(&mut self); 531 | 532 | /// Advances the iterator and returns the next value from the back. 533 | /// 534 | /// The behavior of calling this method after the iterator has been exhausted is unspecified. 535 | /// 536 | /// The default implementation simply calls `advance_back` followed by `get`. 537 | #[inline] 538 | fn next_back(&mut self) -> Option<&Self::Item> { 539 | self.advance_back(); 540 | (*self).get() 541 | } 542 | 543 | /// Reduces the iterator's elements to a single, final value, starting from the back. 544 | #[inline] 545 | fn rfold(mut self, init: B, mut f: F) -> B 546 | where 547 | Self: Sized, 548 | F: FnMut(B, &Self::Item) -> B, 549 | { 550 | let mut acc = init; 551 | while let Some(item) = self.next_back() { 552 | acc = f(acc, item); 553 | } 554 | acc 555 | } 556 | } 557 | 558 | /// An interface for dealing with mutable streaming iterators. 559 | pub trait StreamingIteratorMut: StreamingIterator { 560 | /// Returns a mutable reference to the current element of the iterator. 561 | /// 562 | /// The behavior of calling this method before `advance` has been called is unspecified. 563 | /// 564 | /// Modifications through this reference may also have an unspecified effect on further 565 | /// iterator advancement, but implementations are encouraged to document this. 566 | fn get_mut(&mut self) -> Option<&mut Self::Item>; 567 | 568 | /// Advances the iterator and returns the next mutable value. 569 | /// 570 | /// The behavior of calling this method after the end of the iterator has been reached is 571 | /// unspecified. 572 | /// 573 | /// The default implementation simply calls `advance` followed by `get_mut`. 574 | #[inline] 575 | fn next_mut(&mut self) -> Option<&mut Self::Item> { 576 | self.advance(); 577 | (*self).get_mut() 578 | } 579 | 580 | /// Reduces the iterator's mutable elements to a single, final value. 581 | #[inline] 582 | fn fold_mut(mut self, init: B, mut f: F) -> B 583 | where 584 | Self: Sized, 585 | F: FnMut(B, &mut Self::Item) -> B, 586 | { 587 | let mut acc = init; 588 | while let Some(item) = self.next_mut() { 589 | acc = f(acc, item); 590 | } 591 | acc 592 | } 593 | 594 | /// Calls a closure on each mutable element of an iterator. 595 | #[inline] 596 | fn for_each_mut(self, mut f: F) 597 | where 598 | Self: Sized, 599 | F: FnMut(&mut Self::Item), 600 | { 601 | self.fold_mut((), move |(), item| f(item)); 602 | } 603 | 604 | /// Creates a regular, non-streaming iterator which transforms mutable elements 605 | /// of this iterator by passing them to a closure. 606 | #[inline] 607 | fn map_deref_mut(self, f: F) -> MapDerefMut 608 | where 609 | Self: Sized, 610 | F: FnMut(&mut Self::Item) -> B, 611 | { 612 | MapDerefMut { it: self, f } 613 | } 614 | 615 | /// Creates an iterator which flattens nested streaming iterators. 616 | #[inline] 617 | fn flatten(self) -> Flatten 618 | where 619 | Self: Sized, 620 | Self::Item: StreamingIterator, 621 | { 622 | Flatten { 623 | iter: self, 624 | first: true, 625 | } 626 | } 627 | } 628 | 629 | impl<'a, I: ?Sized> StreamingIteratorMut for &'a mut I 630 | where 631 | I: StreamingIteratorMut, 632 | { 633 | #[inline] 634 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 635 | (**self).get_mut() 636 | } 637 | 638 | #[inline] 639 | fn next_mut(&mut self) -> Option<&mut Self::Item> { 640 | (**self).next_mut() 641 | } 642 | } 643 | 644 | #[cfg(feature = "alloc")] 645 | impl StreamingIteratorMut for Box 646 | where 647 | I: StreamingIteratorMut, 648 | { 649 | #[inline] 650 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 651 | (**self).get_mut() 652 | } 653 | 654 | #[inline] 655 | fn next_mut(&mut self) -> Option<&mut Self::Item> { 656 | (**self).next_mut() 657 | } 658 | } 659 | 660 | /// A mutable streaming iterator able to yield elements from both ends. 661 | pub trait DoubleEndedStreamingIteratorMut: 662 | DoubleEndedStreamingIterator + StreamingIteratorMut 663 | { 664 | /// Advances the iterator and returns the next mutable value from the back. 665 | /// 666 | /// The behavior of calling this method after the end of the iterator has been reached is 667 | /// unspecified. 668 | /// 669 | /// The default implementation simply calls `advance_back` followed by `get_mut`. 670 | #[inline] 671 | fn next_back_mut(&mut self) -> Option<&mut Self::Item> { 672 | self.advance_back(); 673 | (*self).get_mut() 674 | } 675 | 676 | /// Reduces the iterator's mutable elements to a single, final value, starting from the back. 677 | #[inline] 678 | fn rfold_mut(mut self, init: B, mut f: F) -> B 679 | where 680 | Self: Sized, 681 | F: FnMut(B, &mut Self::Item) -> B, 682 | { 683 | let mut acc = init; 684 | while let Some(item) = self.next_back_mut() { 685 | acc = f(acc, item); 686 | } 687 | acc 688 | } 689 | } 690 | // Note, in theory we could blanket-impl `DoubleEndedStreamingIteratorMut`, but that 691 | // wouldn't allow custom folding until we can do it with Rust specialization. 692 | 693 | /// A streaming iterator that concatenates two streaming iterators 694 | #[derive(Debug)] 695 | pub struct Chain { 696 | a: A, 697 | b: B, 698 | state: ChainState, 699 | } 700 | 701 | #[derive(Debug)] 702 | enum ChainState { 703 | // Both iterators have items remaining and we are iterating forward 704 | BothForward, 705 | // Both iterators have items remaining and we are iterating backward 706 | BothBackward, 707 | // Only the front iterator has items 708 | Front, 709 | // Only the back iterator has items 710 | Back, 711 | } 712 | 713 | impl StreamingIterator for Chain 714 | where 715 | A: StreamingIterator, 716 | B: StreamingIterator, 717 | { 718 | type Item = A::Item; 719 | 720 | #[inline] 721 | fn advance(&mut self) { 722 | use crate::ChainState::*; 723 | 724 | match self.state { 725 | BothForward | BothBackward => { 726 | self.a.advance(); 727 | self.state = if self.a.is_done() { 728 | self.b.advance(); 729 | Back 730 | } else { 731 | BothForward 732 | }; 733 | } 734 | Front => self.a.advance(), 735 | Back => self.b.advance(), 736 | } 737 | } 738 | 739 | #[inline] 740 | fn is_done(&self) -> bool { 741 | use crate::ChainState::*; 742 | 743 | match self.state { 744 | BothForward | Front => self.a.is_done(), 745 | BothBackward | Back => self.b.is_done(), 746 | } 747 | } 748 | 749 | #[inline] 750 | fn get(&self) -> Option<&Self::Item> { 751 | use crate::ChainState::*; 752 | 753 | match self.state { 754 | BothForward | Front => self.a.get(), 755 | BothBackward | Back => self.b.get(), 756 | } 757 | } 758 | 759 | #[inline] 760 | fn fold(self, init: Acc, mut f: F) -> Acc 761 | where 762 | Self: Sized, 763 | F: FnMut(Acc, &Self::Item) -> Acc, 764 | { 765 | let mut accum = init; 766 | match self.state { 767 | ChainState::Back => {} 768 | _ => accum = self.a.fold(accum, &mut f), 769 | } 770 | match self.state { 771 | ChainState::Front => {} 772 | _ => accum = self.b.fold(accum, &mut f), 773 | } 774 | accum 775 | } 776 | } 777 | 778 | impl DoubleEndedStreamingIterator for Chain 779 | where 780 | A: DoubleEndedStreamingIterator, 781 | B: DoubleEndedStreamingIterator, 782 | { 783 | #[inline] 784 | fn advance_back(&mut self) { 785 | use crate::ChainState::*; 786 | 787 | match self.state { 788 | BothForward | BothBackward => { 789 | self.b.advance_back(); 790 | self.state = if self.b.is_done() { 791 | self.a.advance_back(); 792 | Front 793 | } else { 794 | BothBackward 795 | }; 796 | } 797 | Front => self.a.advance_back(), 798 | Back => self.b.advance_back(), 799 | } 800 | } 801 | 802 | #[inline] 803 | fn rfold(self, init: Acc, mut f: F) -> Acc 804 | where 805 | Self: Sized, 806 | F: FnMut(Acc, &Self::Item) -> Acc, 807 | { 808 | let mut accum = init; 809 | match self.state { 810 | ChainState::Front => {} 811 | _ => accum = self.b.rfold(accum, &mut f), 812 | } 813 | match self.state { 814 | ChainState::Back => {} 815 | _ => accum = self.a.rfold(accum, &mut f), 816 | } 817 | accum 818 | } 819 | } 820 | 821 | impl StreamingIteratorMut for Chain 822 | where 823 | A: StreamingIteratorMut, 824 | B: StreamingIteratorMut, 825 | { 826 | #[inline] 827 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 828 | use crate::ChainState::*; 829 | 830 | match self.state { 831 | BothForward | Front => self.a.get_mut(), 832 | BothBackward | Back => self.b.get_mut(), 833 | } 834 | } 835 | 836 | #[inline] 837 | fn fold_mut(self, init: Acc, mut f: F) -> Acc 838 | where 839 | Self: Sized, 840 | F: FnMut(Acc, &mut Self::Item) -> Acc, 841 | { 842 | let mut accum = init; 843 | match self.state { 844 | ChainState::Back => {} 845 | _ => accum = self.a.fold_mut(accum, &mut f), 846 | } 847 | match self.state { 848 | ChainState::Front => {} 849 | _ => accum = self.b.fold_mut(accum, &mut f), 850 | } 851 | accum 852 | } 853 | } 854 | 855 | impl DoubleEndedStreamingIteratorMut for Chain 856 | where 857 | A: DoubleEndedStreamingIteratorMut, 858 | B: DoubleEndedStreamingIteratorMut, 859 | { 860 | fn rfold_mut(self, init: Acc, mut f: F) -> Acc 861 | where 862 | Self: Sized, 863 | F: FnMut(Acc, &mut Self::Item) -> Acc, 864 | { 865 | let mut accum = init; 866 | match self.state { 867 | ChainState::Front => {} 868 | _ => accum = self.b.rfold_mut(accum, &mut f), 869 | } 870 | match self.state { 871 | ChainState::Back => {} 872 | _ => accum = self.a.rfold_mut(accum, &mut f), 873 | } 874 | accum 875 | } 876 | } 877 | 878 | /// A normal, non-streaming, iterator which converts the elements of a streaming iterator into owned 879 | /// values by cloning them. 880 | #[derive(Clone, Debug)] 881 | pub struct Cloned(I); 882 | 883 | impl Iterator for Cloned 884 | where 885 | I: StreamingIterator, 886 | I::Item: Clone, 887 | { 888 | type Item = I::Item; 889 | 890 | #[inline] 891 | fn next(&mut self) -> Option { 892 | self.0.next().cloned() 893 | } 894 | 895 | #[inline] 896 | fn size_hint(&self) -> (usize, Option) { 897 | self.0.size_hint() 898 | } 899 | 900 | #[inline] 901 | fn fold(self, init: Acc, mut f: Fold) -> Acc 902 | where 903 | Self: Sized, 904 | Fold: FnMut(Acc, Self::Item) -> Acc, 905 | { 906 | self.0.fold(init, move |acc, item| f(acc, item.clone())) 907 | } 908 | } 909 | 910 | impl DoubleEndedIterator for Cloned 911 | where 912 | I: DoubleEndedStreamingIterator, 913 | I::Item: Clone, 914 | { 915 | #[inline] 916 | fn next_back(&mut self) -> Option { 917 | self.0.next_back().cloned() 918 | } 919 | 920 | #[inline] 921 | fn rfold(self, init: Acc, mut f: Fold) -> Acc 922 | where 923 | Self: Sized, 924 | Fold: FnMut(Acc, Self::Item) -> Acc, 925 | { 926 | self.0.rfold(init, move |acc, item| f(acc, item.clone())) 927 | } 928 | } 929 | 930 | /// A normal, non-streaming, iterator which converts the elements of a streaming iterator into owned 931 | /// values by copying them. 932 | #[derive(Clone, Debug)] 933 | pub struct Copied(I); 934 | 935 | impl Iterator for Copied 936 | where 937 | I: StreamingIterator, 938 | I::Item: Copy, 939 | { 940 | type Item = I::Item; 941 | 942 | #[inline] 943 | fn next(&mut self) -> Option { 944 | self.0.next().copied() 945 | } 946 | 947 | #[inline] 948 | fn size_hint(&self) -> (usize, Option) { 949 | self.0.size_hint() 950 | } 951 | 952 | #[inline] 953 | fn fold(self, init: Acc, mut f: Fold) -> Acc 954 | where 955 | Self: Sized, 956 | Fold: FnMut(Acc, Self::Item) -> Acc, 957 | { 958 | self.0.fold(init, move |acc, &item| f(acc, item)) 959 | } 960 | } 961 | 962 | impl DoubleEndedIterator for Copied 963 | where 964 | I: DoubleEndedStreamingIterator, 965 | I::Item: Copy, 966 | { 967 | #[inline] 968 | fn next_back(&mut self) -> Option { 969 | self.0.next_back().copied() 970 | } 971 | 972 | #[inline] 973 | fn rfold(self, init: Acc, mut f: Fold) -> Acc 974 | where 975 | Self: Sized, 976 | Fold: FnMut(Acc, Self::Item) -> Acc, 977 | { 978 | self.0.rfold(init, move |acc, &item| f(acc, item)) 979 | } 980 | } 981 | 982 | /// A streaming iterator which filters the elements of a streaming iterator with a predicate. 983 | #[derive(Debug)] 984 | pub struct Filter { 985 | it: I, 986 | f: F, 987 | } 988 | 989 | impl StreamingIterator for Filter 990 | where 991 | I: StreamingIterator, 992 | F: FnMut(&I::Item) -> bool, 993 | { 994 | type Item = I::Item; 995 | 996 | #[inline] 997 | fn advance(&mut self) { 998 | while let Some(i) = self.it.next() { 999 | if (self.f)(i) { 1000 | break; 1001 | } 1002 | } 1003 | } 1004 | 1005 | #[inline] 1006 | fn is_done(&self) -> bool { 1007 | self.it.is_done() 1008 | } 1009 | 1010 | #[inline] 1011 | fn get(&self) -> Option<&I::Item> { 1012 | self.it.get() 1013 | } 1014 | 1015 | #[inline] 1016 | fn size_hint(&self) -> (usize, Option) { 1017 | (0, self.it.size_hint().1) 1018 | } 1019 | 1020 | #[inline] 1021 | fn fold(self, init: Acc, mut fold: Fold) -> Acc 1022 | where 1023 | Self: Sized, 1024 | Fold: FnMut(Acc, &Self::Item) -> Acc, 1025 | { 1026 | let mut f = self.f; 1027 | self.it.fold( 1028 | init, 1029 | move |acc, item| { 1030 | if f(item) { 1031 | fold(acc, item) 1032 | } else { 1033 | acc 1034 | } 1035 | }, 1036 | ) 1037 | } 1038 | } 1039 | 1040 | impl DoubleEndedStreamingIterator for Filter 1041 | where 1042 | I: DoubleEndedStreamingIterator, 1043 | F: FnMut(&I::Item) -> bool, 1044 | { 1045 | #[inline] 1046 | fn advance_back(&mut self) { 1047 | while let Some(i) = self.it.next_back() { 1048 | if (self.f)(i) { 1049 | break; 1050 | } 1051 | } 1052 | } 1053 | 1054 | #[inline] 1055 | fn rfold(self, init: Acc, mut fold: Fold) -> Acc 1056 | where 1057 | Self: Sized, 1058 | Fold: FnMut(Acc, &Self::Item) -> Acc, 1059 | { 1060 | let mut f = self.f; 1061 | self.it.rfold( 1062 | init, 1063 | move |acc, item| { 1064 | if f(item) { 1065 | fold(acc, item) 1066 | } else { 1067 | acc 1068 | } 1069 | }, 1070 | ) 1071 | } 1072 | } 1073 | 1074 | impl StreamingIteratorMut for Filter 1075 | where 1076 | I: StreamingIteratorMut, 1077 | F: FnMut(&I::Item) -> bool, 1078 | { 1079 | #[inline] 1080 | fn get_mut(&mut self) -> Option<&mut I::Item> { 1081 | self.it.get_mut() 1082 | } 1083 | 1084 | #[inline] 1085 | fn fold_mut(self, init: Acc, mut fold: Fold) -> Acc 1086 | where 1087 | Self: Sized, 1088 | Fold: FnMut(Acc, &mut Self::Item) -> Acc, 1089 | { 1090 | let mut f = self.f; 1091 | self.it.fold_mut( 1092 | init, 1093 | move |acc, item| { 1094 | if f(&*item) { 1095 | fold(acc, item) 1096 | } else { 1097 | acc 1098 | } 1099 | }, 1100 | ) 1101 | } 1102 | } 1103 | 1104 | impl DoubleEndedStreamingIteratorMut for Filter 1105 | where 1106 | I: DoubleEndedStreamingIteratorMut, 1107 | F: FnMut(&I::Item) -> bool, 1108 | { 1109 | #[inline] 1110 | fn rfold_mut(self, init: Acc, mut fold: Fold) -> Acc 1111 | where 1112 | Self: Sized, 1113 | Fold: FnMut(Acc, &mut Self::Item) -> Acc, 1114 | { 1115 | let mut f = self.f; 1116 | self.it.rfold_mut( 1117 | init, 1118 | move |acc, item| { 1119 | if f(&*item) { 1120 | fold(acc, item) 1121 | } else { 1122 | acc 1123 | } 1124 | }, 1125 | ) 1126 | } 1127 | } 1128 | 1129 | /// An iterator which both filters and maps elements of a streaming iterator with a closure. 1130 | #[derive(Debug)] 1131 | pub struct FilterMap { 1132 | it: I, 1133 | f: F, 1134 | item: Option, 1135 | } 1136 | 1137 | impl StreamingIterator for FilterMap 1138 | where 1139 | I: StreamingIterator, 1140 | F: FnMut(&I::Item) -> Option, 1141 | { 1142 | type Item = B; 1143 | 1144 | #[inline] 1145 | fn advance(&mut self) { 1146 | loop { 1147 | match self.it.next() { 1148 | Some(i) => { 1149 | if let Some(i) = (self.f)(i) { 1150 | self.item = Some(i); 1151 | break; 1152 | } 1153 | } 1154 | None => { 1155 | self.item = None; 1156 | break; 1157 | } 1158 | } 1159 | } 1160 | } 1161 | 1162 | #[inline] 1163 | fn get(&self) -> Option<&B> { 1164 | self.item.as_ref() 1165 | } 1166 | 1167 | #[inline] 1168 | fn size_hint(&self) -> (usize, Option) { 1169 | (0, self.it.size_hint().1) 1170 | } 1171 | 1172 | #[inline] 1173 | fn fold(self, init: Acc, mut fold: Fold) -> Acc 1174 | where 1175 | Self: Sized, 1176 | Fold: FnMut(Acc, &Self::Item) -> Acc, 1177 | { 1178 | let mut f = self.f; 1179 | self.it.fold(init, move |acc, item| match f(item) { 1180 | Some(item) => fold(acc, &item), 1181 | None => acc, 1182 | }) 1183 | } 1184 | } 1185 | 1186 | impl DoubleEndedStreamingIterator for FilterMap 1187 | where 1188 | I: DoubleEndedStreamingIterator, 1189 | F: FnMut(&I::Item) -> Option, 1190 | { 1191 | #[inline] 1192 | fn advance_back(&mut self) { 1193 | loop { 1194 | match self.it.next_back() { 1195 | Some(i) => { 1196 | if let Some(i) = (self.f)(i) { 1197 | self.item = Some(i); 1198 | break; 1199 | } 1200 | } 1201 | None => { 1202 | self.item = None; 1203 | break; 1204 | } 1205 | } 1206 | } 1207 | } 1208 | 1209 | #[inline] 1210 | fn rfold(self, init: Acc, mut fold: Fold) -> Acc 1211 | where 1212 | Self: Sized, 1213 | Fold: FnMut(Acc, &Self::Item) -> Acc, 1214 | { 1215 | let mut f = self.f; 1216 | self.it.rfold(init, move |acc, item| match f(item) { 1217 | Some(item) => fold(acc, &item), 1218 | None => acc, 1219 | }) 1220 | } 1221 | } 1222 | 1223 | impl StreamingIteratorMut for FilterMap 1224 | where 1225 | I: StreamingIterator, 1226 | F: FnMut(&I::Item) -> Option, 1227 | { 1228 | #[inline] 1229 | fn get_mut(&mut self) -> Option<&mut B> { 1230 | self.item.as_mut() 1231 | } 1232 | 1233 | #[inline] 1234 | fn fold_mut(self, init: Acc, mut fold: Fold) -> Acc 1235 | where 1236 | Self: Sized, 1237 | Fold: FnMut(Acc, &mut Self::Item) -> Acc, 1238 | { 1239 | let mut f = self.f; 1240 | self.it.fold(init, move |acc, item| match f(item) { 1241 | Some(mut item) => fold(acc, &mut item), 1242 | None => acc, 1243 | }) 1244 | } 1245 | } 1246 | 1247 | impl DoubleEndedStreamingIteratorMut for FilterMap 1248 | where 1249 | I: DoubleEndedStreamingIterator, 1250 | F: FnMut(&I::Item) -> Option, 1251 | { 1252 | #[inline] 1253 | fn rfold_mut(self, init: Acc, mut fold: Fold) -> Acc 1254 | where 1255 | Self: Sized, 1256 | Fold: FnMut(Acc, &mut Self::Item) -> Acc, 1257 | { 1258 | let mut f = self.f; 1259 | self.it.rfold(init, move |acc, item| match f(item) { 1260 | Some(mut item) => fold(acc, &mut item), 1261 | None => acc, 1262 | }) 1263 | } 1264 | } 1265 | 1266 | /// A streaming iterator that maps elements to iterators with a closure and then yields the 1267 | /// concatenation of the obtained iterators 1268 | #[derive(Debug)] 1269 | pub struct FlatMap { 1270 | it: I, 1271 | f: F, 1272 | sub_iter: Option, 1273 | } 1274 | 1275 | impl StreamingIterator for FlatMap 1276 | where 1277 | I: StreamingIterator, 1278 | F: FnMut(&I::Item) -> J, 1279 | J: StreamingIterator, 1280 | { 1281 | type Item = J::Item; 1282 | 1283 | #[inline] 1284 | fn advance(&mut self) { 1285 | loop { 1286 | if let Some(ref mut iter) = self.sub_iter { 1287 | iter.advance(); 1288 | if !iter.is_done() { 1289 | break; 1290 | } 1291 | } 1292 | if let Some(item) = self.it.next() { 1293 | self.sub_iter = Some((self.f)(item)); 1294 | } else { 1295 | break; 1296 | } 1297 | } 1298 | } 1299 | 1300 | #[inline] 1301 | fn is_done(&self) -> bool { 1302 | match self.sub_iter { 1303 | Some(ref iter) => iter.is_done(), 1304 | None => true, 1305 | } 1306 | } 1307 | 1308 | #[inline] 1309 | fn get(&self) -> Option<&Self::Item> { 1310 | self.sub_iter.as_ref().and_then(J::get) 1311 | } 1312 | 1313 | #[inline] 1314 | fn fold(self, init: Acc, mut fold: Fold) -> Acc 1315 | where 1316 | Self: Sized, 1317 | Fold: FnMut(Acc, &Self::Item) -> Acc, 1318 | { 1319 | let mut acc = init; 1320 | if let Some(iter) = self.sub_iter { 1321 | acc = iter.fold(acc, &mut fold); 1322 | } 1323 | let mut f = self.f; 1324 | self.it.fold(acc, |acc, item| f(item).fold(acc, &mut fold)) 1325 | } 1326 | } 1327 | 1328 | impl StreamingIteratorMut for FlatMap 1329 | where 1330 | I: StreamingIterator, 1331 | F: FnMut(&I::Item) -> J, 1332 | J: StreamingIteratorMut, 1333 | { 1334 | #[inline] 1335 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 1336 | self.sub_iter.as_mut().and_then(J::get_mut) 1337 | } 1338 | 1339 | #[inline] 1340 | fn fold_mut(self, init: Acc, mut fold: Fold) -> Acc 1341 | where 1342 | Self: Sized, 1343 | Fold: FnMut(Acc, &mut Self::Item) -> Acc, 1344 | { 1345 | let mut acc = init; 1346 | if let Some(iter) = self.sub_iter { 1347 | acc = iter.fold_mut(acc, &mut fold); 1348 | } 1349 | let mut f = self.f; 1350 | self.it 1351 | .fold(acc, |acc, item| f(item).fold_mut(acc, &mut fold)) 1352 | } 1353 | } 1354 | 1355 | /// A streaming iterator that flattens nested streaming iterators. 1356 | #[derive(Debug)] 1357 | pub struct Flatten { 1358 | iter: I, 1359 | first: bool, 1360 | } 1361 | 1362 | impl StreamingIterator for Flatten 1363 | where 1364 | I: StreamingIteratorMut, 1365 | I::Item: StreamingIterator, 1366 | { 1367 | type Item = ::Item; 1368 | 1369 | #[inline] 1370 | fn advance(&mut self) { 1371 | if self.first { 1372 | self.first = false; 1373 | self.iter.advance(); 1374 | } 1375 | while let Some(iter) = self.iter.get_mut() { 1376 | iter.advance(); 1377 | if !iter.is_done() { 1378 | break; 1379 | } 1380 | self.iter.advance(); // since we got Some, self.iter is not done and can be advanced 1381 | } 1382 | } 1383 | 1384 | #[inline] 1385 | fn is_done(&self) -> bool { 1386 | match self.iter.get() { 1387 | Some(iter) => iter.is_done(), 1388 | None => true, 1389 | } 1390 | } 1391 | 1392 | #[inline] 1393 | fn get(&self) -> Option<&Self::Item> { 1394 | self.iter.get().and_then(I::Item::get) 1395 | } 1396 | 1397 | #[inline] 1398 | fn fold(self, init: Acc, mut fold: Fold) -> Acc 1399 | where 1400 | Self: Sized, 1401 | Fold: FnMut(Acc, &Self::Item) -> Acc, 1402 | { 1403 | self.iter 1404 | .fold_mut(init, |acc, item| item.fold(acc, &mut fold)) 1405 | } 1406 | } 1407 | 1408 | impl StreamingIteratorMut for Flatten 1409 | where 1410 | I: StreamingIteratorMut, 1411 | I::Item: StreamingIteratorMut, 1412 | { 1413 | #[inline] 1414 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 1415 | self.iter.get_mut().and_then(I::Item::get_mut) 1416 | } 1417 | 1418 | #[inline] 1419 | fn fold_mut(self, init: Acc, mut fold: Fold) -> Acc 1420 | where 1421 | Self: Sized, 1422 | Fold: FnMut(Acc, &mut Self::Item) -> Acc, 1423 | { 1424 | self.iter 1425 | .fold_mut(init, |acc, item| item.fold_mut(acc, &mut fold)) 1426 | } 1427 | } 1428 | 1429 | /// A regular, non-streaming iterator which both filters and maps elements of a streaming iterator with a closure. 1430 | #[derive(Debug)] 1431 | pub struct FilterMapDeref { 1432 | it: I, 1433 | f: F, 1434 | } 1435 | 1436 | impl Iterator for FilterMapDeref 1437 | where 1438 | I: StreamingIterator, 1439 | F: FnMut(&I::Item) -> Option, 1440 | { 1441 | type Item = B; 1442 | 1443 | #[inline] 1444 | fn next(&mut self) -> Option { 1445 | while let Some(item) = self.it.next() { 1446 | if let Some(mapped) = (self.f)(item) { 1447 | return Some(mapped); 1448 | } 1449 | } 1450 | 1451 | None 1452 | } 1453 | 1454 | #[inline] 1455 | fn fold(self, init: Acc, mut f: Fold) -> Acc 1456 | where 1457 | Self: Sized, 1458 | Fold: FnMut(Acc, Self::Item) -> Acc, 1459 | { 1460 | let mut map = self.f; 1461 | self.it.fold(init, move |acc, item| match map(item) { 1462 | Some(mapped) => f(acc, mapped), 1463 | None => acc, 1464 | }) 1465 | } 1466 | } 1467 | 1468 | impl DoubleEndedIterator for FilterMapDeref 1469 | where 1470 | I: DoubleEndedStreamingIterator, 1471 | F: FnMut(&I::Item) -> Option, 1472 | { 1473 | #[inline] 1474 | fn next_back(&mut self) -> Option { 1475 | while let Some(item) = self.it.next_back() { 1476 | if let Some(mapped) = (self.f)(item) { 1477 | return Some(mapped); 1478 | } 1479 | } 1480 | 1481 | None 1482 | } 1483 | 1484 | #[inline] 1485 | fn rfold(self, init: Acc, mut f: Fold) -> Acc 1486 | where 1487 | Self: Sized, 1488 | Fold: FnMut(Acc, Self::Item) -> Acc, 1489 | { 1490 | let mut map = self.f; 1491 | self.it.rfold(init, move |acc, item| match map(item) { 1492 | Some(mapped) => f(acc, mapped), 1493 | None => acc, 1494 | }) 1495 | } 1496 | } 1497 | 1498 | #[derive(Copy, Clone, Debug)] 1499 | enum FuseState { 1500 | Start, 1501 | Middle, 1502 | End, 1503 | } 1504 | 1505 | /// A streaming iterator which is well-defined before and after iteration. 1506 | #[derive(Clone, Debug)] 1507 | pub struct Fuse { 1508 | it: I, 1509 | state: FuseState, 1510 | } 1511 | 1512 | impl StreamingIterator for Fuse 1513 | where 1514 | I: StreamingIterator, 1515 | { 1516 | type Item = I::Item; 1517 | 1518 | #[inline] 1519 | fn advance(&mut self) { 1520 | match self.state { 1521 | FuseState::Start => { 1522 | self.it.advance(); 1523 | self.state = if self.it.is_done() { 1524 | FuseState::End 1525 | } else { 1526 | FuseState::Middle 1527 | }; 1528 | } 1529 | FuseState::Middle => { 1530 | self.it.advance(); 1531 | if self.it.is_done() { 1532 | self.state = FuseState::End; 1533 | } 1534 | } 1535 | FuseState::End => {} 1536 | } 1537 | } 1538 | 1539 | #[inline] 1540 | fn is_done(&self) -> bool { 1541 | match self.state { 1542 | FuseState::Start | FuseState::End => true, 1543 | FuseState::Middle => false, 1544 | } 1545 | } 1546 | 1547 | #[inline] 1548 | fn get(&self) -> Option<&I::Item> { 1549 | match self.state { 1550 | FuseState::Start | FuseState::End => None, 1551 | FuseState::Middle => self.it.get(), 1552 | } 1553 | } 1554 | 1555 | #[inline] 1556 | fn size_hint(&self) -> (usize, Option) { 1557 | self.it.size_hint() 1558 | } 1559 | 1560 | #[inline] 1561 | fn next(&mut self) -> Option<&I::Item> { 1562 | match self.state { 1563 | FuseState::Start => match self.it.next() { 1564 | Some(i) => { 1565 | self.state = FuseState::Middle; 1566 | Some(i) 1567 | } 1568 | None => { 1569 | self.state = FuseState::End; 1570 | None 1571 | } 1572 | }, 1573 | FuseState::Middle => match self.it.next() { 1574 | Some(i) => Some(i), 1575 | None => { 1576 | self.state = FuseState::End; 1577 | None 1578 | } 1579 | }, 1580 | FuseState::End => None, 1581 | } 1582 | } 1583 | 1584 | #[inline] 1585 | fn count(self) -> usize { 1586 | match self.state { 1587 | FuseState::Start | FuseState::Middle => self.it.count(), 1588 | FuseState::End => 0, 1589 | } 1590 | } 1591 | 1592 | #[inline] 1593 | fn fold(self, init: Acc, fold: Fold) -> Acc 1594 | where 1595 | Self: Sized, 1596 | Fold: FnMut(Acc, &Self::Item) -> Acc, 1597 | { 1598 | match self.state { 1599 | FuseState::Start | FuseState::Middle => self.it.fold(init, fold), 1600 | FuseState::End => init, 1601 | } 1602 | } 1603 | } 1604 | 1605 | impl StreamingIteratorMut for Fuse 1606 | where 1607 | I: StreamingIteratorMut, 1608 | { 1609 | #[inline] 1610 | fn get_mut(&mut self) -> Option<&mut I::Item> { 1611 | match self.state { 1612 | FuseState::Start | FuseState::End => None, 1613 | FuseState::Middle => self.it.get_mut(), 1614 | } 1615 | } 1616 | 1617 | #[inline] 1618 | fn fold_mut(self, init: Acc, fold: Fold) -> Acc 1619 | where 1620 | Self: Sized, 1621 | Fold: FnMut(Acc, &mut Self::Item) -> Acc, 1622 | { 1623 | match self.state { 1624 | FuseState::Start | FuseState::Middle => self.it.fold_mut(init, fold), 1625 | FuseState::End => init, 1626 | } 1627 | } 1628 | } 1629 | 1630 | /// A streaming iterator that calls a function with element before yielding it. 1631 | #[derive(Debug)] 1632 | pub struct Inspect { 1633 | it: I, 1634 | f: F, 1635 | } 1636 | 1637 | impl StreamingIterator for Inspect 1638 | where 1639 | I: StreamingIterator, 1640 | F: FnMut(&I::Item), 1641 | { 1642 | type Item = I::Item; 1643 | 1644 | fn advance(&mut self) { 1645 | if let Some(item) = self.it.next() { 1646 | (self.f)(item); 1647 | } 1648 | } 1649 | 1650 | #[inline] 1651 | fn is_done(&self) -> bool { 1652 | self.it.is_done() 1653 | } 1654 | 1655 | fn get(&self) -> Option<&Self::Item> { 1656 | self.it.get() 1657 | } 1658 | 1659 | fn size_hint(&self) -> (usize, Option) { 1660 | self.it.size_hint() 1661 | } 1662 | 1663 | #[inline] 1664 | fn fold(self, init: Acc, mut fold: Fold) -> Acc 1665 | where 1666 | Self: Sized, 1667 | Fold: FnMut(Acc, &Self::Item) -> Acc, 1668 | { 1669 | let mut f = self.f; 1670 | self.it.fold(init, |acc, item| { 1671 | f(item); 1672 | fold(acc, item) 1673 | }) 1674 | } 1675 | } 1676 | 1677 | impl DoubleEndedStreamingIterator for Inspect 1678 | where 1679 | I: DoubleEndedStreamingIterator, 1680 | F: FnMut(&I::Item), 1681 | { 1682 | fn advance_back(&mut self) { 1683 | if let Some(item) = self.it.next_back() { 1684 | (self.f)(item); 1685 | } 1686 | } 1687 | 1688 | #[inline] 1689 | fn rfold(self, init: Acc, mut fold: Fold) -> Acc 1690 | where 1691 | Self: Sized, 1692 | Fold: FnMut(Acc, &Self::Item) -> Acc, 1693 | { 1694 | let mut f = self.f; 1695 | self.it.rfold(init, |acc, item| { 1696 | f(item); 1697 | fold(acc, item) 1698 | }) 1699 | } 1700 | } 1701 | 1702 | impl StreamingIteratorMut for Inspect 1703 | where 1704 | I: StreamingIteratorMut, 1705 | F: FnMut(&I::Item), 1706 | { 1707 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 1708 | self.it.get_mut() 1709 | } 1710 | 1711 | #[inline] 1712 | fn fold_mut(self, init: Acc, mut fold: Fold) -> Acc 1713 | where 1714 | Self: Sized, 1715 | Fold: FnMut(Acc, &mut Self::Item) -> Acc, 1716 | { 1717 | let mut f = self.f; 1718 | self.it.fold_mut(init, |acc, item| { 1719 | f(&*item); 1720 | fold(acc, item) 1721 | }) 1722 | } 1723 | } 1724 | 1725 | impl DoubleEndedStreamingIteratorMut for Inspect 1726 | where 1727 | I: DoubleEndedStreamingIteratorMut, 1728 | F: FnMut(&I::Item), 1729 | { 1730 | #[inline] 1731 | fn rfold_mut(self, init: Acc, mut fold: Fold) -> Acc 1732 | where 1733 | Self: Sized, 1734 | Fold: FnMut(Acc, &mut Self::Item) -> Acc, 1735 | { 1736 | let mut f = self.f; 1737 | self.it.rfold_mut(init, |acc, item| { 1738 | f(&*item); 1739 | fold(acc, item) 1740 | }) 1741 | } 1742 | } 1743 | 1744 | /// A streaming iterator which transforms the elements of a streaming iterator. 1745 | #[derive(Debug)] 1746 | pub struct Map { 1747 | it: I, 1748 | f: F, 1749 | item: Option, 1750 | } 1751 | 1752 | impl StreamingIterator for Map 1753 | where 1754 | I: StreamingIterator, 1755 | F: FnMut(&I::Item) -> B, 1756 | { 1757 | type Item = B; 1758 | 1759 | #[inline] 1760 | fn advance(&mut self) { 1761 | self.item = self.it.next().map(&mut self.f); 1762 | } 1763 | 1764 | #[inline] 1765 | fn get(&self) -> Option<&B> { 1766 | self.item.as_ref() 1767 | } 1768 | 1769 | #[inline] 1770 | fn size_hint(&self) -> (usize, Option) { 1771 | self.it.size_hint() 1772 | } 1773 | 1774 | #[inline] 1775 | fn fold(self, init: Acc, mut fold: Fold) -> Acc 1776 | where 1777 | Self: Sized, 1778 | Fold: FnMut(Acc, &Self::Item) -> Acc, 1779 | { 1780 | let mut f = self.f; 1781 | self.it.fold(init, move |acc, item| fold(acc, &f(item))) 1782 | } 1783 | } 1784 | 1785 | impl DoubleEndedStreamingIterator for Map 1786 | where 1787 | I: DoubleEndedStreamingIterator, 1788 | F: FnMut(&I::Item) -> B, 1789 | { 1790 | #[inline] 1791 | fn advance_back(&mut self) { 1792 | self.item = self.it.next_back().map(&mut self.f); 1793 | } 1794 | 1795 | #[inline] 1796 | fn rfold(self, init: Acc, mut fold: Fold) -> Acc 1797 | where 1798 | Self: Sized, 1799 | Fold: FnMut(Acc, &Self::Item) -> Acc, 1800 | { 1801 | let mut f = self.f; 1802 | self.it.rfold(init, move |acc, item| fold(acc, &f(item))) 1803 | } 1804 | } 1805 | 1806 | impl StreamingIteratorMut for Map 1807 | where 1808 | I: StreamingIterator, 1809 | F: FnMut(&I::Item) -> B, 1810 | { 1811 | #[inline] 1812 | fn get_mut(&mut self) -> Option<&mut B> { 1813 | self.item.as_mut() 1814 | } 1815 | 1816 | #[inline] 1817 | fn fold_mut(self, init: Acc, mut fold: Fold) -> Acc 1818 | where 1819 | Self: Sized, 1820 | Fold: FnMut(Acc, &mut Self::Item) -> Acc, 1821 | { 1822 | let mut f = self.f; 1823 | self.it.fold(init, move |acc, item| fold(acc, &mut f(item))) 1824 | } 1825 | } 1826 | 1827 | impl DoubleEndedStreamingIteratorMut for Map 1828 | where 1829 | I: DoubleEndedStreamingIterator, 1830 | F: FnMut(&I::Item) -> B, 1831 | { 1832 | #[inline] 1833 | fn rfold_mut(self, init: Acc, mut fold: Fold) -> Acc 1834 | where 1835 | Self: Sized, 1836 | Fold: FnMut(Acc, &mut Self::Item) -> Acc, 1837 | { 1838 | let mut f = self.f; 1839 | self.it 1840 | .rfold(init, move |acc, item| fold(acc, &mut f(item))) 1841 | } 1842 | } 1843 | 1844 | /// A regular, non-streaming iterator which transforms the elements of a streaming iterator. 1845 | #[derive(Debug)] 1846 | pub struct MapDeref { 1847 | it: I, 1848 | f: F, 1849 | } 1850 | 1851 | impl Iterator for MapDeref 1852 | where 1853 | I: StreamingIterator, 1854 | F: FnMut(&I::Item) -> B, 1855 | { 1856 | type Item = B; 1857 | 1858 | #[inline] 1859 | fn next(&mut self) -> Option { 1860 | self.it.next().map(&mut self.f) 1861 | } 1862 | 1863 | #[inline] 1864 | fn size_hint(&self) -> (usize, Option) { 1865 | self.it.size_hint() 1866 | } 1867 | 1868 | #[inline] 1869 | fn fold(self, init: Acc, mut f: Fold) -> Acc 1870 | where 1871 | Self: Sized, 1872 | Fold: FnMut(Acc, Self::Item) -> Acc, 1873 | { 1874 | let mut map = self.f; 1875 | self.it.fold(init, move |acc, item| f(acc, map(item))) 1876 | } 1877 | } 1878 | 1879 | impl DoubleEndedIterator for MapDeref 1880 | where 1881 | I: DoubleEndedStreamingIterator, 1882 | F: FnMut(&I::Item) -> B, 1883 | { 1884 | #[inline] 1885 | fn next_back(&mut self) -> Option { 1886 | self.it.next_back().map(&mut self.f) 1887 | } 1888 | 1889 | #[inline] 1890 | fn rfold(self, init: Acc, mut f: Fold) -> Acc 1891 | where 1892 | Self: Sized, 1893 | Fold: FnMut(Acc, Self::Item) -> Acc, 1894 | { 1895 | let mut map = self.f; 1896 | self.it.rfold(init, move |acc, item| f(acc, map(item))) 1897 | } 1898 | } 1899 | 1900 | /// A regular, non-streaming iterator which transforms the elements of a mutable streaming iterator. 1901 | #[derive(Debug)] 1902 | pub struct MapDerefMut { 1903 | it: I, 1904 | f: F, 1905 | } 1906 | 1907 | impl Iterator for MapDerefMut 1908 | where 1909 | I: StreamingIteratorMut, 1910 | F: FnMut(&mut I::Item) -> B, 1911 | { 1912 | type Item = B; 1913 | 1914 | #[inline] 1915 | fn next(&mut self) -> Option { 1916 | self.it.next_mut().map(&mut self.f) 1917 | } 1918 | 1919 | #[inline] 1920 | fn size_hint(&self) -> (usize, Option) { 1921 | self.it.size_hint() 1922 | } 1923 | 1924 | #[inline] 1925 | fn fold(self, init: Acc, mut f: Fold) -> Acc 1926 | where 1927 | Self: Sized, 1928 | Fold: FnMut(Acc, Self::Item) -> Acc, 1929 | { 1930 | let mut map = self.f; 1931 | self.it.fold_mut(init, move |acc, item| f(acc, map(item))) 1932 | } 1933 | } 1934 | 1935 | impl DoubleEndedIterator for MapDerefMut 1936 | where 1937 | I: DoubleEndedStreamingIteratorMut, 1938 | F: FnMut(&mut I::Item) -> B, 1939 | { 1940 | #[inline] 1941 | fn next_back(&mut self) -> Option { 1942 | self.it.next_back_mut().map(&mut self.f) 1943 | } 1944 | 1945 | #[inline] 1946 | fn rfold(self, init: Acc, mut f: Fold) -> Acc 1947 | where 1948 | Self: Sized, 1949 | Fold: FnMut(Acc, Self::Item) -> Acc, 1950 | { 1951 | let mut map = self.f; 1952 | self.it.rfold_mut(init, move |acc, item| f(acc, map(item))) 1953 | } 1954 | } 1955 | 1956 | /// A streaming iterator which transforms the elements of a streaming iterator. 1957 | #[derive(Debug)] 1958 | pub struct MapRef { 1959 | it: I, 1960 | f: F, 1961 | } 1962 | 1963 | impl StreamingIterator for MapRef 1964 | where 1965 | I: StreamingIterator, 1966 | F: Fn(&I::Item) -> &B, 1967 | { 1968 | type Item = B; 1969 | 1970 | #[inline] 1971 | fn advance(&mut self) { 1972 | self.it.advance(); 1973 | } 1974 | 1975 | #[inline] 1976 | fn is_done(&self) -> bool { 1977 | self.it.is_done() 1978 | } 1979 | 1980 | #[inline] 1981 | fn get(&self) -> Option<&B> { 1982 | self.it.get().map(&self.f) 1983 | } 1984 | 1985 | #[inline] 1986 | fn size_hint(&self) -> (usize, Option) { 1987 | self.it.size_hint() 1988 | } 1989 | 1990 | #[inline] 1991 | fn next(&mut self) -> Option<&B> { 1992 | self.it.next().map(&self.f) 1993 | } 1994 | 1995 | #[inline] 1996 | fn fold(self, init: Acc, mut fold: Fold) -> Acc 1997 | where 1998 | Self: Sized, 1999 | Fold: FnMut(Acc, &Self::Item) -> Acc, 2000 | { 2001 | let f = self.f; 2002 | self.it.fold(init, move |acc, item| fold(acc, f(item))) 2003 | } 2004 | } 2005 | 2006 | /// A normal, non-streaming, iterator which converts the elements of a streaming iterator into owned 2007 | /// versions. 2008 | /// 2009 | /// Requires the `alloc` feature. 2010 | #[cfg(feature = "alloc")] 2011 | #[derive(Clone, Debug)] 2012 | pub struct Owned(I); 2013 | 2014 | #[cfg(feature = "alloc")] 2015 | impl Iterator for Owned 2016 | where 2017 | I: StreamingIterator, 2018 | I::Item: ToOwned, 2019 | { 2020 | type Item = ::Owned; 2021 | 2022 | #[inline] 2023 | fn next(&mut self) -> Option<::Owned> { 2024 | self.0.next().map(ToOwned::to_owned) 2025 | } 2026 | 2027 | #[inline] 2028 | fn size_hint(&self) -> (usize, Option) { 2029 | self.0.size_hint() 2030 | } 2031 | 2032 | #[inline] 2033 | fn fold(self, init: Acc, mut f: Fold) -> Acc 2034 | where 2035 | Self: Sized, 2036 | Fold: FnMut(Acc, Self::Item) -> Acc, 2037 | { 2038 | self.0.fold(init, move |acc, item| f(acc, item.to_owned())) 2039 | } 2040 | } 2041 | 2042 | #[cfg(feature = "alloc")] 2043 | impl DoubleEndedIterator for Owned 2044 | where 2045 | I: DoubleEndedStreamingIterator, 2046 | I::Item: Sized + ToOwned, 2047 | { 2048 | #[inline] 2049 | fn next_back(&mut self) -> Option<::Owned> { 2050 | self.0.next_back().map(ToOwned::to_owned) 2051 | } 2052 | 2053 | #[inline] 2054 | fn rfold(self, init: Acc, mut f: Fold) -> Acc 2055 | where 2056 | Self: Sized, 2057 | Fold: FnMut(Acc, Self::Item) -> Acc, 2058 | { 2059 | self.0.rfold(init, move |acc, item| f(acc, item.to_owned())) 2060 | } 2061 | } 2062 | 2063 | /// A streaming iterator which skips a number of elements in a streaming iterator. 2064 | #[derive(Clone, Debug)] 2065 | pub struct Skip { 2066 | it: I, 2067 | n: usize, 2068 | } 2069 | 2070 | impl StreamingIterator for Skip 2071 | where 2072 | I: StreamingIterator, 2073 | { 2074 | type Item = I::Item; 2075 | 2076 | #[inline] 2077 | fn advance(&mut self) { 2078 | self.it.nth(self.n); 2079 | self.n = 0; 2080 | } 2081 | 2082 | #[inline] 2083 | fn is_done(&self) -> bool { 2084 | self.it.is_done() 2085 | } 2086 | 2087 | #[inline] 2088 | fn get(&self) -> Option<&I::Item> { 2089 | self.it.get() 2090 | } 2091 | 2092 | #[inline] 2093 | fn size_hint(&self) -> (usize, Option) { 2094 | let hint = self.it.size_hint(); 2095 | ( 2096 | hint.0.saturating_sub(self.n), 2097 | hint.1.map(|n| n.saturating_sub(self.n)), 2098 | ) 2099 | } 2100 | 2101 | #[inline] 2102 | fn fold(mut self, init: Acc, fold: Fold) -> Acc 2103 | where 2104 | Self: Sized, 2105 | Fold: FnMut(Acc, &Self::Item) -> Acc, 2106 | { 2107 | if self.n > 0 { 2108 | // nth(n) skips n+1 2109 | if self.it.nth(self.n - 1).is_none() { 2110 | return init; 2111 | } 2112 | } 2113 | self.it.fold(init, fold) 2114 | } 2115 | } 2116 | 2117 | impl StreamingIteratorMut for Skip 2118 | where 2119 | I: StreamingIteratorMut, 2120 | { 2121 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 2122 | self.it.get_mut() 2123 | } 2124 | 2125 | #[inline] 2126 | fn fold_mut(mut self, init: Acc, fold: Fold) -> Acc 2127 | where 2128 | Self: Sized, 2129 | Fold: FnMut(Acc, &mut Self::Item) -> Acc, 2130 | { 2131 | if self.n > 0 { 2132 | // nth(n) skips n+1 2133 | if self.it.nth(self.n - 1).is_none() { 2134 | return init; 2135 | } 2136 | } 2137 | self.it.fold_mut(init, fold) 2138 | } 2139 | } 2140 | 2141 | /// A streaming iterator which skips initial elements that match a predicate 2142 | #[derive(Clone, Debug)] 2143 | pub struct SkipWhile { 2144 | it: I, 2145 | f: F, 2146 | done: bool, 2147 | } 2148 | 2149 | impl StreamingIterator for SkipWhile 2150 | where 2151 | I: StreamingIterator, 2152 | F: FnMut(&I::Item) -> bool, 2153 | { 2154 | type Item = I::Item; 2155 | 2156 | #[inline] 2157 | fn advance(&mut self) { 2158 | if !self.done { 2159 | let f = &mut self.f; 2160 | self.it.find(|i| !f(i)); 2161 | self.done = true; 2162 | } else { 2163 | self.it.advance(); 2164 | } 2165 | } 2166 | 2167 | #[inline] 2168 | fn is_done(&self) -> bool { 2169 | self.it.is_done() 2170 | } 2171 | 2172 | #[inline] 2173 | fn get(&self) -> Option<&I::Item> { 2174 | self.it.get() 2175 | } 2176 | 2177 | #[inline] 2178 | fn size_hint(&self) -> (usize, Option) { 2179 | let hint = self.it.size_hint(); 2180 | (0, hint.1) 2181 | } 2182 | 2183 | #[inline] 2184 | fn fold(mut self, mut init: Acc, mut fold: Fold) -> Acc 2185 | where 2186 | Self: Sized, 2187 | Fold: FnMut(Acc, &Self::Item) -> Acc, 2188 | { 2189 | if !self.done { 2190 | match self.next() { 2191 | Some(item) => init = fold(init, item), 2192 | None => return init, 2193 | } 2194 | } 2195 | self.it.fold(init, fold) 2196 | } 2197 | } 2198 | 2199 | impl StreamingIteratorMut for SkipWhile 2200 | where 2201 | I: StreamingIteratorMut, 2202 | F: FnMut(&I::Item) -> bool, 2203 | { 2204 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 2205 | self.it.get_mut() 2206 | } 2207 | 2208 | #[inline] 2209 | fn fold_mut(mut self, mut init: Acc, mut fold: Fold) -> Acc 2210 | where 2211 | Self: Sized, 2212 | Fold: FnMut(Acc, &mut Self::Item) -> Acc, 2213 | { 2214 | if !self.done { 2215 | match self.next_mut() { 2216 | Some(item) => init = fold(init, item), 2217 | None => return init, 2218 | } 2219 | } 2220 | self.it.fold_mut(init, fold) 2221 | } 2222 | } 2223 | 2224 | /// A streaming iterator which only yields a limited number of elements in a streaming iterator. 2225 | #[derive(Clone, Debug)] 2226 | pub struct Take { 2227 | it: I, 2228 | n: usize, 2229 | done: bool, 2230 | } 2231 | 2232 | impl StreamingIterator for Take 2233 | where 2234 | I: StreamingIterator, 2235 | { 2236 | type Item = I::Item; 2237 | 2238 | #[inline] 2239 | fn advance(&mut self) { 2240 | if self.n != 0 { 2241 | self.it.advance(); 2242 | self.n -= 1; 2243 | } else { 2244 | self.done = true; 2245 | } 2246 | } 2247 | 2248 | #[inline] 2249 | fn is_done(&self) -> bool { 2250 | self.done || self.it.is_done() 2251 | } 2252 | 2253 | #[inline] 2254 | fn get(&self) -> Option<&I::Item> { 2255 | if self.done { 2256 | None 2257 | } else { 2258 | self.it.get() 2259 | } 2260 | } 2261 | 2262 | #[inline] 2263 | fn size_hint(&self) -> (usize, Option) { 2264 | let hint = self.it.size_hint(); 2265 | (cmp::min(hint.0, self.n), Some(self.n)) 2266 | } 2267 | } 2268 | 2269 | impl StreamingIteratorMut for Take 2270 | where 2271 | I: StreamingIteratorMut, 2272 | { 2273 | #[inline] 2274 | fn get_mut(&mut self) -> Option<&mut I::Item> { 2275 | if self.done { 2276 | None 2277 | } else { 2278 | self.it.get_mut() 2279 | } 2280 | } 2281 | } 2282 | 2283 | /// A streaming iterator which only returns initial elements matching a predicate. 2284 | #[derive(Debug)] 2285 | pub struct TakeWhile { 2286 | it: I, 2287 | f: F, 2288 | done: bool, 2289 | } 2290 | 2291 | impl StreamingIterator for TakeWhile 2292 | where 2293 | I: StreamingIterator, 2294 | F: FnMut(&I::Item) -> bool, 2295 | { 2296 | type Item = I::Item; 2297 | 2298 | #[inline] 2299 | fn advance(&mut self) { 2300 | if !self.done { 2301 | self.it.advance(); 2302 | if let Some(i) = self.it.get() { 2303 | if !(self.f)(i) { 2304 | self.done = true; 2305 | } 2306 | } 2307 | } 2308 | } 2309 | 2310 | #[inline] 2311 | fn is_done(&self) -> bool { 2312 | self.done || self.it.is_done() 2313 | } 2314 | 2315 | #[inline] 2316 | fn get(&self) -> Option<&I::Item> { 2317 | if self.done { 2318 | None 2319 | } else { 2320 | self.it.get() 2321 | } 2322 | } 2323 | 2324 | #[inline] 2325 | fn next(&mut self) -> Option<&I::Item> { 2326 | if self.done { 2327 | None 2328 | } else { 2329 | match self.it.next() { 2330 | Some(i) => { 2331 | if (self.f)(i) { 2332 | Some(i) 2333 | } else { 2334 | self.done = true; 2335 | None 2336 | } 2337 | } 2338 | None => None, 2339 | } 2340 | } 2341 | } 2342 | 2343 | #[inline] 2344 | fn size_hint(&self) -> (usize, Option) { 2345 | let upper = if self.done { 2346 | Some(0) 2347 | } else { 2348 | self.it.size_hint().1 2349 | }; 2350 | (0, upper) 2351 | } 2352 | } 2353 | 2354 | impl StreamingIteratorMut for TakeWhile 2355 | where 2356 | I: StreamingIteratorMut, 2357 | F: FnMut(&I::Item) -> bool, 2358 | { 2359 | #[inline] 2360 | fn get_mut(&mut self) -> Option<&mut I::Item> { 2361 | if self.done { 2362 | None 2363 | } else { 2364 | self.it.get_mut() 2365 | } 2366 | } 2367 | } 2368 | 2369 | /// A streaming iterator which returns elements in the opposite order. 2370 | pub struct Rev(I); 2371 | 2372 | impl StreamingIterator for Rev 2373 | where 2374 | I: DoubleEndedStreamingIterator, 2375 | { 2376 | type Item = I::Item; 2377 | 2378 | #[inline] 2379 | fn advance(&mut self) { 2380 | self.0.advance_back(); 2381 | } 2382 | 2383 | #[inline] 2384 | fn is_done(&self) -> bool { 2385 | self.0.is_done() 2386 | } 2387 | 2388 | #[inline] 2389 | fn get(&self) -> Option<&I::Item> { 2390 | self.0.get() 2391 | } 2392 | 2393 | #[inline] 2394 | fn next(&mut self) -> Option<&I::Item> { 2395 | self.0.next_back() 2396 | } 2397 | 2398 | #[inline] 2399 | fn size_hint(&self) -> (usize, Option) { 2400 | self.0.size_hint() 2401 | } 2402 | 2403 | #[inline] 2404 | fn fold(self, init: Acc, f: Fold) -> Acc 2405 | where 2406 | Self: Sized, 2407 | Fold: FnMut(Acc, &Self::Item) -> Acc, 2408 | { 2409 | self.0.rfold(init, f) 2410 | } 2411 | } 2412 | 2413 | impl DoubleEndedStreamingIterator for Rev 2414 | where 2415 | I: DoubleEndedStreamingIterator, 2416 | { 2417 | #[inline] 2418 | fn advance_back(&mut self) { 2419 | self.0.advance(); 2420 | } 2421 | 2422 | #[inline] 2423 | fn next_back(&mut self) -> Option<&I::Item> { 2424 | self.0.next() 2425 | } 2426 | 2427 | #[inline] 2428 | fn rfold(self, init: Acc, f: Fold) -> Acc 2429 | where 2430 | Self: Sized, 2431 | Fold: FnMut(Acc, &Self::Item) -> Acc, 2432 | { 2433 | self.0.fold(init, f) 2434 | } 2435 | } 2436 | 2437 | impl StreamingIteratorMut for Rev 2438 | where 2439 | I: DoubleEndedStreamingIteratorMut, 2440 | { 2441 | #[inline] 2442 | fn get_mut(&mut self) -> Option<&mut I::Item> { 2443 | self.0.get_mut() 2444 | } 2445 | 2446 | #[inline] 2447 | fn fold_mut(self, init: B, f: F) -> B 2448 | where 2449 | Self: Sized, 2450 | F: FnMut(B, &mut Self::Item) -> B, 2451 | { 2452 | self.0.rfold_mut(init, f) 2453 | } 2454 | } 2455 | 2456 | impl DoubleEndedStreamingIteratorMut for Rev 2457 | where 2458 | I: DoubleEndedStreamingIteratorMut, 2459 | { 2460 | #[inline] 2461 | fn rfold_mut(self, init: B, f: F) -> B 2462 | where 2463 | Self: Sized, 2464 | F: FnMut(B, &mut Self::Item) -> B, 2465 | { 2466 | self.0.fold_mut(init, f) 2467 | } 2468 | } 2469 | 2470 | /// Conversion from [`IntoIterator`] to [`StreamingIterator`]. 2471 | pub trait IntoStreamingIterator: IntoIterator 2472 | where 2473 | Self: Sized, 2474 | { 2475 | /// Turns an [`IntoIterator`] into a [`StreamingIterator`]. 2476 | /// 2477 | /// Calling this method on an [`IntoIterator`] is equivalent to using [`convert`]. 2478 | #[inline] 2479 | fn into_streaming_iter(self) -> Convert { 2480 | convert(self) 2481 | } 2482 | 2483 | /// Turns an [`IntoIterator`] of references into a [`StreamingIterator`]. 2484 | /// 2485 | /// Calling this method on an [`IntoIterator`] is equivalent to using [`convert_ref`]. 2486 | #[inline] 2487 | fn into_streaming_iter_ref<'a, T: ?Sized>(self) -> ConvertRef<'a, Self::IntoIter, T> 2488 | where 2489 | Self: IntoIterator, 2490 | { 2491 | convert_ref(self) 2492 | } 2493 | 2494 | /// Turns an [`IntoIterator`] of mutable references into a [`StreamingIteratorMut`]. 2495 | /// 2496 | /// Calling this method on an [`IntoIterator`] is equivalent to using [`convert_mut`]. 2497 | #[inline] 2498 | fn into_streaming_iter_mut<'a, T: ?Sized>(self) -> ConvertMut<'a, Self::IntoIter, T> 2499 | where 2500 | Self: IntoIterator, 2501 | { 2502 | convert_mut(self) 2503 | } 2504 | } 2505 | 2506 | impl IntoStreamingIterator for I where I: IntoIterator {} 2507 | 2508 | #[cfg(test)] 2509 | mod test { 2510 | use core::fmt::Debug; 2511 | 2512 | #[cfg(feature = "alloc")] 2513 | use alloc::vec::Vec; 2514 | 2515 | use super::*; 2516 | 2517 | fn test(mut it: I, expected: &[I::Item]) 2518 | where 2519 | I: StreamingIterator, 2520 | I::Item: Sized + PartialEq + Debug, 2521 | { 2522 | for item in expected { 2523 | it.advance(); 2524 | assert_eq!(it.get(), Some(item)); 2525 | assert_eq!(it.get(), Some(item)); 2526 | } 2527 | it.advance(); 2528 | assert_eq!(it.get(), None); 2529 | assert_eq!(it.get(), None); 2530 | } 2531 | 2532 | fn test_back(mut it: I, expected: &[I::Item]) 2533 | where 2534 | I: DoubleEndedStreamingIterator, 2535 | I::Item: Sized + PartialEq + Debug, 2536 | { 2537 | for item in expected { 2538 | it.advance_back(); 2539 | assert_eq!(it.get(), Some(item)); 2540 | assert_eq!(it.get(), Some(item)); 2541 | } 2542 | it.advance_back(); 2543 | assert_eq!(it.get(), None); 2544 | assert_eq!(it.get(), None); 2545 | } 2546 | 2547 | fn test_deref(mut it: I, expected: &[I::Item]) 2548 | where 2549 | I: Iterator, 2550 | I::Item: Sized + PartialEq + Debug, 2551 | { 2552 | for item in expected { 2553 | assert_eq!(it.next().as_ref(), Some(item)); 2554 | } 2555 | assert_eq!(it.next(), None) 2556 | } 2557 | 2558 | #[test] 2559 | fn all() { 2560 | let items = [0, 1, 2]; 2561 | let mut it = convert(items); 2562 | assert!(it.clone().all(|&i| i < 3)); 2563 | assert!(!it.all(|&i| i % 2 == 0)); 2564 | } 2565 | 2566 | #[test] 2567 | fn any() { 2568 | let items = [0, 1, 2]; 2569 | let mut it = convert(items); 2570 | assert!(it.clone().any(|&i| i > 1)); 2571 | assert!(!it.any(|&i| i > 2)); 2572 | } 2573 | 2574 | #[test] 2575 | fn test_chain() { 2576 | let items_a = [0, 1, 2, 3]; 2577 | let items_b = [10, 20, 30]; 2578 | let expected = [0, 1, 2, 3, 10, 20, 30]; 2579 | 2580 | let it = convert(items_a).chain(convert(items_b)); 2581 | test(it, &expected); 2582 | } 2583 | 2584 | #[test] 2585 | fn test_chain_back() { 2586 | let items_a = [0, 1, 2, 3]; 2587 | let items_b = [10, 20, 30]; 2588 | let expected = [30, 20, 10, 3, 2, 1, 0]; 2589 | 2590 | let it = convert(items_a).chain(convert(items_b)); 2591 | test_back(it, &expected); 2592 | } 2593 | 2594 | #[test] 2595 | fn test_chain_mixed() { 2596 | let items_a = [0, 1, 2, 3]; 2597 | let items_b = [10, 20, 30]; 2598 | 2599 | let mut it = convert(items_a).chain(convert(items_b)); 2600 | 2601 | assert_eq!(it.get(), None); 2602 | it.advance(); 2603 | assert_eq!(it.get().copied(), Some(0)); 2604 | it.advance_back(); 2605 | assert_eq!(it.get().copied(), Some(30)); 2606 | it.advance(); 2607 | assert_eq!(it.get().copied(), Some(1)); 2608 | it.advance_back(); 2609 | assert_eq!(it.get().copied(), Some(20)); 2610 | it.advance(); 2611 | assert_eq!(it.get().copied(), Some(2)); 2612 | it.advance_back(); 2613 | assert_eq!(it.get().copied(), Some(10)); 2614 | it.advance_back(); 2615 | assert_eq!(it.get().copied(), Some(3)); 2616 | } 2617 | 2618 | #[test] 2619 | fn cloned() { 2620 | let items = [0, 1]; 2621 | let mut it = convert(items).cloned(); 2622 | assert_eq!(it.next(), Some(0)); 2623 | assert_eq!(it.next(), Some(1)); 2624 | assert_eq!(it.next(), None); 2625 | } 2626 | 2627 | #[test] 2628 | fn copied() { 2629 | let items = [0, 1]; 2630 | let mut it = convert(items).copied(); 2631 | assert_eq!(it.next(), Some(0)); 2632 | assert_eq!(it.next(), Some(1)); 2633 | assert_eq!(it.next(), None); 2634 | } 2635 | 2636 | #[test] 2637 | fn test_convert() { 2638 | let items = [0, 1]; 2639 | let it = convert(items); 2640 | test(it, &items); 2641 | } 2642 | 2643 | #[test] 2644 | fn test_convert_ref() { 2645 | let items = [&0, &1]; 2646 | let it = convert_ref(items.iter()); 2647 | test(it, &items); 2648 | } 2649 | 2650 | #[test] 2651 | fn count() { 2652 | let items = [0, 1, 2, 3]; 2653 | let it = convert(items); 2654 | assert_eq!(it.count(), 4); 2655 | } 2656 | 2657 | #[test] 2658 | fn filter() { 2659 | let items = [0, 1, 2, 3]; 2660 | let it = convert(items).filter(|x| x % 2 == 0); 2661 | test(it, &[0, 2]); 2662 | } 2663 | 2664 | #[test] 2665 | fn fuse() { 2666 | struct Flicker(i32); 2667 | 2668 | impl StreamingIterator for Flicker { 2669 | type Item = i32; 2670 | 2671 | fn advance(&mut self) { 2672 | self.0 += 1; 2673 | } 2674 | 2675 | fn get(&self) -> Option<&i32> { 2676 | if self.0 % 4 == 3 { 2677 | None 2678 | } else { 2679 | Some(&self.0) 2680 | } 2681 | } 2682 | } 2683 | 2684 | let mut it = Flicker(0).fuse(); 2685 | assert_eq!(it.get(), None); 2686 | it.advance(); 2687 | assert_eq!(it.get(), Some(&1)); 2688 | assert_eq!(it.get(), Some(&1)); 2689 | it.advance(); 2690 | assert_eq!(it.get(), Some(&2)); 2691 | assert_eq!(it.get(), Some(&2)); 2692 | it.advance(); 2693 | assert_eq!(it.get(), None); 2694 | assert_eq!(it.get(), None); 2695 | it.advance(); 2696 | assert_eq!(it.get(), None); 2697 | assert_eq!(it.get(), None); 2698 | } 2699 | 2700 | #[test] 2701 | fn inspect() { 2702 | let items = [0, 1, 2, 3]; 2703 | let mut idx = 0; 2704 | let mut items_inspected = [-1, -1, -1, -1]; 2705 | 2706 | { 2707 | let it = convert(items).inspect(|&i| { 2708 | items_inspected[idx] = i; 2709 | idx += 1; 2710 | }); 2711 | 2712 | test(it, &items); 2713 | } 2714 | 2715 | assert_eq!(&items_inspected, &items); 2716 | } 2717 | 2718 | #[test] 2719 | fn map() { 2720 | let items = [0, 1]; 2721 | let it = convert(items.iter().map(|&i| i as usize)).map(|&i| i as i32); 2722 | test(it, &items); 2723 | } 2724 | 2725 | #[test] 2726 | fn map_deref() { 2727 | let items = [0, 1]; 2728 | let it = convert(items.iter().map(|&i| i as usize)).map_deref(|&i| i as i32); 2729 | test_deref(it, &items); 2730 | } 2731 | 2732 | #[test] 2733 | fn map_deref_mut() { 2734 | let mut items = [1, 2, 3]; 2735 | { 2736 | let it = convert_mut(&mut items).map_deref_mut(|i| -core::mem::replace(i, 0)); 2737 | test_deref(it, &[-1, -2, -3]); 2738 | } 2739 | assert_eq!(items, [0, 0, 0]); 2740 | } 2741 | 2742 | #[test] 2743 | fn map_ref() { 2744 | #[derive(Clone)] 2745 | struct Foo(i32); 2746 | 2747 | let items = [Foo(0), Foo(1)]; 2748 | let it = convert(items).map_ref(|f| &f.0); 2749 | test(it, &[0, 1]); 2750 | } 2751 | 2752 | #[test] 2753 | fn flat_map() { 2754 | let items = [[0, 1, 2], [3, 4, 5]]; 2755 | let it = convert(items).flat_map(|&i| convert(i)); 2756 | 2757 | test(it, &[0, 1, 2, 3, 4, 5]); 2758 | } 2759 | 2760 | #[test] 2761 | fn flatten() { 2762 | let mut items = [ 2763 | convert_ref([].as_ref()), 2764 | convert_ref([1].as_ref()), 2765 | convert_ref([].as_ref()), 2766 | convert_ref([2, 3].as_ref()), 2767 | convert_ref([].as_ref()), 2768 | ]; 2769 | let it = convert_mut(&mut items).flatten(); 2770 | 2771 | test(it, &[1, 2, 3]); 2772 | } 2773 | 2774 | #[test] 2775 | fn flatten_unsized() { 2776 | type DynI32 = dyn StreamingIterator; 2777 | let mut items = [ 2778 | &mut once(1) as &mut DynI32, 2779 | &mut empty(), 2780 | &mut convert(2..=3), 2781 | ]; 2782 | let iters = items.iter_mut().map(|iter| &mut **iter); 2783 | let it = convert_mut(iters).flatten(); 2784 | 2785 | test(it, &[1, 2, 3]); 2786 | } 2787 | 2788 | #[test] 2789 | fn nth() { 2790 | let items = [0, 1]; 2791 | let mut it = convert(items); 2792 | assert_eq!(it.clone().nth(0), Some(&0)); 2793 | assert_eq!(it.clone().nth(1), Some(&1)); 2794 | assert_eq!(it.nth(2), None); 2795 | } 2796 | 2797 | #[test] 2798 | fn filter_map() { 2799 | let items = [0u8, 1, 1, 2, 4]; 2800 | let it = convert(items).filter_map(|&i| if i % 2 == 0 { Some(i) } else { None }); 2801 | test(it, &[0, 2, 4]) 2802 | } 2803 | 2804 | #[test] 2805 | fn filter_map_deref() { 2806 | let items = [0u8, 1, 1, 2, 4]; 2807 | let it = convert(items).filter_map_deref(|&i| if i % 2 == 0 { Some(i) } else { None }); 2808 | test_deref(it, &[0, 2, 4]) 2809 | } 2810 | 2811 | #[test] 2812 | fn find() { 2813 | let items = [0, 1]; 2814 | let mut it = convert(items); 2815 | assert_eq!(it.clone().find(|&x| x % 2 == 1), Some(&1)); 2816 | assert_eq!(it.find(|&x| x % 3 == 2), None); 2817 | } 2818 | 2819 | #[test] 2820 | #[cfg(feature = "alloc")] 2821 | fn owned() { 2822 | let items = [0, 1]; 2823 | let it = convert(items).owned(); 2824 | assert_eq!(it.collect::>(), items); 2825 | } 2826 | 2827 | #[test] 2828 | #[cfg(feature = "alloc")] 2829 | fn owned_str() { 2830 | let s = "The quick brown fox jumps over the lazy dog"; 2831 | let words = s.split_whitespace().map(str::to_owned).collect::>(); 2832 | let it = convert_ref(s.split_whitespace()).owned(); 2833 | assert_eq!(it.collect::>(), words); 2834 | } 2835 | 2836 | #[test] 2837 | fn position() { 2838 | let items = [0, 1]; 2839 | let mut it = convert(items); 2840 | assert_eq!(it.clone().position(|&x| x % 2 == 1), Some(1)); 2841 | assert_eq!(it.position(|&x| x % 3 == 2), None); 2842 | } 2843 | 2844 | #[test] 2845 | fn skip() { 2846 | let items = [0, 1, 2, 3]; 2847 | let it = convert(items); 2848 | test(it.clone().skip(0), &[0, 1, 2, 3]); 2849 | test(it.clone().skip(2), &[2, 3]); 2850 | test(it.skip(5), &[]); 2851 | } 2852 | 2853 | #[test] 2854 | fn skip_while() { 2855 | let items = [0, 1, 2, 3]; 2856 | let it = convert(items); 2857 | test(it.clone().skip_while(|&i| i < 0), &[0, 1, 2, 3]); 2858 | test(it.clone().skip_while(|&i| i < 2), &[2, 3]); 2859 | test(it.skip_while(|&i| i < 5), &[]); 2860 | } 2861 | 2862 | #[test] 2863 | fn take() { 2864 | let items = [0, 1, 2, 3]; 2865 | let it = convert(items); 2866 | test(it.clone().take(0), &[]); 2867 | test(it.clone().take(2), &[0, 1]); 2868 | test(it.take(5), &[0, 1, 2, 3]); 2869 | } 2870 | 2871 | #[test] 2872 | fn take_while() { 2873 | let items = [0, 1, 2, 3]; 2874 | let it = convert(items); 2875 | test(it.clone().take_while(|&i| i < 0), &[]); 2876 | test(it.clone().take_while(|&i| i < 2), &[0, 1]); 2877 | test(it.take_while(|&i| i < 5), &[0, 1, 2, 3]); 2878 | } 2879 | 2880 | fn _is_object_safe(_: &dyn StreamingIterator) {} 2881 | 2882 | fn _is_object_safe_mut(_: &dyn StreamingIteratorMut) {} 2883 | 2884 | #[test] 2885 | fn empty_iterator() { 2886 | let mut it: Empty = empty(); 2887 | 2888 | assert_eq!(it.next(), None); 2889 | } 2890 | 2891 | #[test] 2892 | fn is_done_empty() { 2893 | let mut empty = empty::(); 2894 | empty.advance(); 2895 | assert!(empty.is_done()); 2896 | } 2897 | 2898 | #[test] 2899 | fn is_done_map() { 2900 | let items = [1]; 2901 | let mut it = convert(items).map_ref::(|_| panic!("only called during get()")); 2902 | it.advance(); 2903 | assert!(!it.is_done()); 2904 | it.advance(); 2905 | assert!(it.is_done()); 2906 | } 2907 | 2908 | #[test] 2909 | fn rev() { 2910 | let items = [0, 1, 2, 3]; 2911 | let it = convert(items); 2912 | test(it.rev(), &[3, 2, 1, 0]); 2913 | } 2914 | 2915 | #[test] 2916 | fn fold() { 2917 | let items = [0, 1, 2, 3]; 2918 | let it = convert(items); 2919 | assert_eq!(it.fold(0, |acc, i| acc * 10 + i), 123); 2920 | } 2921 | 2922 | #[test] 2923 | fn for_each() { 2924 | let items = [0, 1, 2, 3]; 2925 | let it = convert(items); 2926 | let mut acc = 0; 2927 | it.for_each(|i| acc = acc * 10 + i); 2928 | assert_eq!(acc, 123); 2929 | } 2930 | 2931 | #[test] 2932 | fn rfold() { 2933 | let items = [0, 1, 2, 3]; 2934 | let it = convert(items); 2935 | assert_eq!(it.rfold(0, |acc, i| acc * 10 + i), 3210); 2936 | } 2937 | 2938 | #[test] 2939 | fn for_each_rev() { 2940 | let items = [0, 1, 2, 3]; 2941 | let it = convert(items); 2942 | let mut acc = 0; 2943 | it.rev().for_each(|i| acc = acc * 10 + i); 2944 | assert_eq!(acc, 3210); 2945 | } 2946 | 2947 | #[test] 2948 | fn for_each_mut() { 2949 | let mut items = [0, 1, 2, 3]; 2950 | 2951 | convert_mut(&mut items).for_each_mut(|i: &mut i32| *i += 10); 2952 | assert_eq!(items, [10, 11, 12, 13]); 2953 | 2954 | // Note that filter sees a direct `&T` reference, 2955 | // rather than `&&mut T` like `Iterator` would. 2956 | convert_mut(&mut items) 2957 | .filter(|&i: &i32| i & 1 == 0) 2958 | .for_each_mut(|i: &mut i32| *i /= 2); 2959 | assert_eq!(items, [5, 11, 6, 13]); 2960 | } 2961 | 2962 | #[test] 2963 | fn into_streaming_iter() { 2964 | let items = [0, 1, 2, 3]; 2965 | let iter = items.into_streaming_iter(); 2966 | test(iter, &items); 2967 | let iter = (&items).into_streaming_iter_ref(); 2968 | test(iter, &items); 2969 | let mut mut_items = items; 2970 | let iter = (&mut mut_items).into_streaming_iter_mut(); 2971 | test(iter, &items); 2972 | } 2973 | } 2974 | -------------------------------------------------------------------------------- /src/slice.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | DoubleEndedStreamingIterator, DoubleEndedStreamingIteratorMut, StreamingIterator, 3 | StreamingIteratorMut, 4 | }; 5 | 6 | use core::mem; 7 | use core::num::NonZeroUsize; 8 | 9 | /// Creates an iterator over all contiguous windows of length `size` in a mutable `slice`. 10 | /// 11 | /// The windows overlap and may be mutated via `StreamingIteratorMut`. 12 | /// If the `slice` is shorter than `size`, the iterator returns no values. 13 | /// 14 | /// # Panics 15 | /// 16 | /// Panics if `size` is 0. 17 | pub fn windows_mut(slice: &mut [T], size: usize) -> WindowsMut<'_, T> { 18 | WindowsMut { 19 | slice, 20 | size: NonZeroUsize::new(size).expect("size is zero"), 21 | position: Position::Init, 22 | } 23 | } 24 | 25 | /// A streaming iterator which returns overlapping mutable subslices of length `size`. 26 | /// 27 | /// This struct is created by the [`windows_mut`] function. 28 | pub struct WindowsMut<'a, T> { 29 | slice: &'a mut [T], 30 | size: NonZeroUsize, 31 | position: Position, 32 | } 33 | 34 | enum Position { 35 | Init, 36 | Front, 37 | Back, 38 | } 39 | 40 | impl WindowsMut<'_, T> { 41 | fn consume(&mut self) { 42 | match self.position { 43 | Position::Init => {} 44 | Position::Front => { 45 | let slice = mem::take(&mut self.slice); 46 | if let Some((_, tail)) = slice.split_first_mut() { 47 | self.slice = tail; 48 | } 49 | } 50 | Position::Back => { 51 | let slice = mem::take(&mut self.slice); 52 | if let Some((_, head)) = slice.split_last_mut() { 53 | self.slice = head; 54 | } 55 | } 56 | } 57 | } 58 | 59 | fn get_front(&self) -> Option<&[T]> { 60 | self.slice.get(..self.size.get()) 61 | } 62 | 63 | fn get_front_mut(&mut self) -> Option<&mut [T]> { 64 | self.slice.get_mut(..self.size.get()) 65 | } 66 | 67 | fn get_back(&self) -> Option<&[T]> { 68 | let start = self.slice.len().checked_sub(self.size.get())?; 69 | self.slice.get(start..) 70 | } 71 | 72 | fn get_back_mut(&mut self) -> Option<&mut [T]> { 73 | let start = self.slice.len().checked_sub(self.size.get())?; 74 | self.slice.get_mut(start..) 75 | } 76 | 77 | fn len(&self) -> usize { 78 | let len = match self.position { 79 | Position::Init => self.slice.len(), 80 | _ => self.slice.len().saturating_sub(1), 81 | }; 82 | len.saturating_sub(self.size.get() - 1) 83 | } 84 | } 85 | 86 | impl StreamingIterator for WindowsMut<'_, T> { 87 | type Item = [T]; 88 | 89 | fn advance(&mut self) { 90 | self.consume(); 91 | self.position = Position::Front; 92 | } 93 | 94 | fn get(&self) -> Option<&Self::Item> { 95 | match self.position { 96 | Position::Init => None, 97 | Position::Front => self.get_front(), 98 | Position::Back => self.get_back(), 99 | } 100 | } 101 | 102 | fn next(&mut self) -> Option<&Self::Item> { 103 | self.advance(); 104 | self.get_front() 105 | } 106 | 107 | fn size_hint(&self) -> (usize, Option) { 108 | let len = self.len(); 109 | (len, Some(len)) 110 | } 111 | 112 | fn is_done(&self) -> bool { 113 | self.slice.len() < self.size.get() 114 | } 115 | 116 | fn count(self) -> usize { 117 | self.len() 118 | } 119 | } 120 | 121 | impl StreamingIteratorMut for WindowsMut<'_, T> { 122 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 123 | match self.position { 124 | Position::Init => None, 125 | Position::Front => self.get_front_mut(), 126 | Position::Back => self.get_back_mut(), 127 | } 128 | } 129 | 130 | fn next_mut(&mut self) -> Option<&mut Self::Item> { 131 | self.advance(); 132 | self.get_front_mut() 133 | } 134 | } 135 | 136 | impl DoubleEndedStreamingIterator for WindowsMut<'_, T> { 137 | fn advance_back(&mut self) { 138 | self.consume(); 139 | self.position = Position::Back; 140 | } 141 | 142 | fn next_back(&mut self) -> Option<&Self::Item> { 143 | self.advance_back(); 144 | self.get_back() 145 | } 146 | } 147 | 148 | impl DoubleEndedStreamingIteratorMut for WindowsMut<'_, T> { 149 | fn next_back_mut(&mut self) -> Option<&mut Self::Item> { 150 | self.advance_back(); 151 | self.get_back_mut() 152 | } 153 | } 154 | 155 | #[test] 156 | fn test_windows_mut() { 157 | let slice: &mut [_] = &mut [0; 6]; 158 | 159 | windows_mut(slice, 3).fold_mut(0, |i, win| { 160 | win.copy_from_slice(&[i; 3]); 161 | i + 1 162 | }); 163 | assert_eq!(slice, &[0, 1, 2, 3, 3, 3]); 164 | 165 | windows_mut(slice, 2).rfold_mut(0, |i, win| { 166 | win.copy_from_slice(&[i; 2]); 167 | i + 1 168 | }); 169 | assert_eq!(slice, &[4, 4, 3, 2, 1, 0]); 170 | 171 | let mut i = 0; 172 | let mut iter = windows_mut(slice, 1); 173 | while let Some(win) = iter.next_mut() { 174 | win.copy_from_slice(&[i]); 175 | i += 1; 176 | 177 | if let Some(win) = iter.next_back_mut() { 178 | win.copy_from_slice(&[i]); 179 | i += 1; 180 | } 181 | } 182 | assert_eq!(slice, &[0, 2, 4, 5, 3, 1]); 183 | } 184 | 185 | #[test] 186 | fn test_windows_mut_count() { 187 | let slice: &mut [_] = &mut [0; 6]; 188 | 189 | assert_eq!(windows_mut(slice, 3).count(), 4); 190 | assert_eq!(windows_mut(slice, 6).count(), 1); 191 | assert_eq!(windows_mut(slice, 9).count(), 0); 192 | 193 | let mut iter = windows_mut(slice, 3); 194 | assert_eq!(iter.size_hint(), (4, Some(4))); 195 | iter.advance(); 196 | assert_eq!(iter.count(), 3); 197 | } 198 | 199 | #[test] 200 | #[should_panic] 201 | fn test_windows_mut_0() { 202 | let _: WindowsMut<'_, i32> = windows_mut(&mut [], 0); 203 | } 204 | -------------------------------------------------------------------------------- /src/sources.rs: -------------------------------------------------------------------------------- 1 | use super::{DoubleEndedStreamingIterator, StreamingIterator}; 2 | use super::{DoubleEndedStreamingIteratorMut, StreamingIteratorMut}; 3 | use core::marker::PhantomData; 4 | use core::usize; 5 | 6 | /// Turns a normal, non-streaming iterator into a streaming iterator. 7 | /// 8 | /// ``` 9 | /// # use streaming_iterator::{StreamingIterator, convert}; 10 | /// let scores = vec![100, 50, 80]; 11 | /// let mut streaming_iter = convert(scores); 12 | /// while let Some(score) = streaming_iter.next() { 13 | /// println!("The score is: {}", score); 14 | /// } 15 | /// ``` 16 | #[inline] 17 | pub fn convert(it: I) -> Convert 18 | where 19 | I: IntoIterator, 20 | { 21 | Convert { 22 | it: it.into_iter(), 23 | item: None, 24 | } 25 | } 26 | 27 | /// Turns an iterator of references into a streaming iterator. 28 | /// 29 | /// ``` 30 | /// # use streaming_iterator::{StreamingIterator, convert_ref}; 31 | /// let scores = vec![100, 50, 80]; 32 | /// let mut streaming_iter = convert_ref(&scores); 33 | /// while let Some(score) = streaming_iter.next() { 34 | /// println!("The score is: {}", score); 35 | /// } 36 | /// ``` 37 | #[inline] 38 | pub fn convert_ref<'a, I, T: ?Sized>(iterator: I) -> ConvertRef<'a, I::IntoIter, T> 39 | where 40 | I: IntoIterator, 41 | { 42 | ConvertRef { 43 | it: iterator.into_iter(), 44 | item: None, 45 | } 46 | } 47 | 48 | /// Turns an iterator of mutable references into a streaming iterator. 49 | /// 50 | /// ``` 51 | /// # use streaming_iterator::{StreamingIteratorMut, convert_mut}; 52 | /// let mut scores = vec![Some(100), None, Some(80)]; 53 | /// { 54 | /// let mut streaming_iter = convert_mut(&mut scores); 55 | /// while let Some(opt_score) = streaming_iter.next_mut() { 56 | /// if let Some(score) = opt_score.take() { 57 | /// println!("The score is: {}", score); 58 | /// } 59 | /// // else already reported 60 | /// } 61 | /// } 62 | /// assert_eq!(scores, [None, None, None]); 63 | /// ``` 64 | #[inline] 65 | pub fn convert_mut<'a, I, T: ?Sized>(iterator: I) -> ConvertMut<'a, I::IntoIter, T> 66 | where 67 | I: IntoIterator, 68 | { 69 | ConvertMut { 70 | it: iterator.into_iter(), 71 | item: None, 72 | } 73 | } 74 | 75 | /// Creates an empty iterator. 76 | /// 77 | /// ``` 78 | /// # use streaming_iterator::StreamingIterator; 79 | /// let mut streaming_iter = streaming_iterator::empty::(); 80 | /// assert_eq!(streaming_iter.next(), None); 81 | /// ``` 82 | #[inline] 83 | pub fn empty() -> Empty { 84 | Empty { 85 | phantom: PhantomData, 86 | } 87 | } 88 | 89 | /// Creates an iterator that returns items from a function call. 90 | /// 91 | /// ``` 92 | /// # use streaming_iterator::StreamingIterator; 93 | /// let mut count = 0; 94 | /// let mut streaming_iter = streaming_iterator::from_fn(|| { 95 | /// count += 1; 96 | /// if count < 4 { Some(count) } else { None } 97 | /// }); 98 | /// assert_eq!(streaming_iter.next(), Some(&1)); 99 | /// assert_eq!(streaming_iter.next(), Some(&2)); 100 | /// assert_eq!(streaming_iter.next(), Some(&3)); 101 | /// assert_eq!(streaming_iter.next(), None); 102 | /// ``` 103 | #[inline] 104 | pub fn from_fn Option>(gen: F) -> FromFn { 105 | FromFn { gen, item: None } 106 | } 107 | 108 | /// Creates an iterator that returns exactly one item. 109 | /// 110 | /// ``` 111 | /// # use streaming_iterator::StreamingIterator; 112 | /// let mut streaming_iter = streaming_iterator::once(1); 113 | /// assert_eq!(streaming_iter.next(), Some(&1)); 114 | /// assert_eq!(streaming_iter.next(), None); 115 | /// ``` 116 | #[inline] 117 | pub fn once(item: T) -> Once { 118 | Once { 119 | first: true, 120 | item: Some(item), 121 | } 122 | } 123 | 124 | /// Creates an iterator that returns exactly one item from a function call. 125 | /// 126 | /// ``` 127 | /// # use streaming_iterator::StreamingIterator; 128 | /// #[derive(Debug, PartialEq)] 129 | /// struct Expensive(i32); 130 | /// let mut streaming_iter = streaming_iterator::once_with(|| Expensive(1)); 131 | /// assert_eq!(streaming_iter.next(), Some(&Expensive(1))); 132 | /// assert_eq!(streaming_iter.next(), None); 133 | /// ``` 134 | #[inline] 135 | pub fn once_with T>(gen: F) -> OnceWith { 136 | OnceWith { 137 | gen: Some(gen), 138 | item: None, 139 | } 140 | } 141 | 142 | /// Creates an iterator that returns an item endlessly. 143 | /// 144 | /// ``` 145 | /// # use streaming_iterator::StreamingIterator; 146 | /// let mut streaming_iter = streaming_iterator::repeat(1); 147 | /// assert_eq!(streaming_iter.next(), Some(&1)); 148 | /// assert_eq!(streaming_iter.next(), Some(&1)); 149 | /// assert_eq!(streaming_iter.next(), Some(&1)); 150 | /// assert_eq!(streaming_iter.next(), Some(&1)); 151 | /// assert_eq!(streaming_iter.next(), Some(&1)); 152 | /// // ... 153 | /// ``` 154 | #[inline] 155 | pub fn repeat(item: T) -> Repeat { 156 | Repeat { item } 157 | } 158 | 159 | /// Creates an iterator that endlessly returns items from a function call. 160 | /// 161 | /// ``` 162 | /// # use streaming_iterator::StreamingIterator; 163 | /// let mut count = 0; 164 | /// let mut streaming_iter = streaming_iterator::repeat_with(|| { 165 | /// count += 1; 166 | /// count 167 | /// }); 168 | /// assert_eq!(streaming_iter.next(), Some(&1)); 169 | /// assert_eq!(streaming_iter.next(), Some(&2)); 170 | /// assert_eq!(streaming_iter.next(), Some(&3)); 171 | /// assert_eq!(streaming_iter.next(), Some(&4)); 172 | /// assert_eq!(streaming_iter.next(), Some(&5)); 173 | /// // ... 174 | /// ``` 175 | #[inline] 176 | pub fn repeat_with T>(gen: F) -> RepeatWith { 177 | RepeatWith { gen, item: None } 178 | } 179 | 180 | /// Creates an iterator where each successive item is computed from the preceding one. 181 | /// 182 | /// ``` 183 | /// # use streaming_iterator::StreamingIterator; 184 | /// let mut streaming_iter = streaming_iterator::successors( 185 | /// Some(1), 186 | /// |count| if count < 3 { Some(count + 1) } else { None }, 187 | /// ); 188 | /// assert_eq!(streaming_iter.next(), Some(&1)); 189 | /// assert_eq!(streaming_iter.next(), Some(&2)); 190 | /// assert_eq!(streaming_iter.next(), Some(&3)); 191 | /// assert_eq!(streaming_iter.next(), None); 192 | /// ``` 193 | #[inline] 194 | pub fn successors Option>(first: Option, succ: F) -> Successors { 195 | Successors { 196 | first: true, 197 | item: first, 198 | succ, 199 | } 200 | } 201 | 202 | /// A streaming iterator which yields elements from a normal, non-streaming, iterator. 203 | #[derive(Clone, Debug)] 204 | pub struct Convert 205 | where 206 | I: Iterator, 207 | { 208 | it: I, 209 | item: Option, 210 | } 211 | 212 | impl StreamingIterator for Convert 213 | where 214 | I: Iterator, 215 | { 216 | type Item = I::Item; 217 | 218 | #[inline] 219 | fn advance(&mut self) { 220 | self.item = self.it.next(); 221 | } 222 | 223 | #[inline] 224 | fn get(&self) -> Option<&I::Item> { 225 | self.item.as_ref() 226 | } 227 | 228 | #[inline] 229 | fn size_hint(&self) -> (usize, Option) { 230 | self.it.size_hint() 231 | } 232 | 233 | #[inline] 234 | fn count(self) -> usize { 235 | self.it.count() 236 | } 237 | 238 | #[inline] 239 | fn fold(self, init: Acc, mut f: Fold) -> Acc 240 | where 241 | Self: Sized, 242 | Fold: FnMut(Acc, &Self::Item) -> Acc, 243 | { 244 | self.it.fold(init, move |acc, item| f(acc, &item)) 245 | } 246 | } 247 | 248 | impl DoubleEndedStreamingIterator for Convert 249 | where 250 | I: DoubleEndedIterator, 251 | { 252 | #[inline] 253 | fn advance_back(&mut self) { 254 | self.item = self.it.next_back(); 255 | } 256 | 257 | #[inline] 258 | fn rfold(self, init: Acc, mut f: Fold) -> Acc 259 | where 260 | Self: Sized, 261 | Fold: FnMut(Acc, &Self::Item) -> Acc, 262 | { 263 | self.it.rfold(init, move |acc, item| f(acc, &item)) 264 | } 265 | } 266 | 267 | impl StreamingIteratorMut for Convert 268 | where 269 | I: Iterator, 270 | { 271 | #[inline] 272 | fn get_mut(&mut self) -> Option<&mut I::Item> { 273 | self.item.as_mut() 274 | } 275 | 276 | #[inline] 277 | fn fold_mut(self, init: B, mut f: F) -> B 278 | where 279 | Self: Sized, 280 | F: FnMut(B, &mut Self::Item) -> B, 281 | { 282 | self.it.fold(init, move |acc, mut item| f(acc, &mut item)) 283 | } 284 | } 285 | 286 | impl DoubleEndedStreamingIteratorMut for Convert 287 | where 288 | I: DoubleEndedIterator, 289 | { 290 | #[inline] 291 | fn rfold_mut(self, init: B, mut f: F) -> B 292 | where 293 | Self: Sized, 294 | F: FnMut(B, &mut Self::Item) -> B, 295 | { 296 | self.it.rfold(init, move |acc, mut item| f(acc, &mut item)) 297 | } 298 | } 299 | 300 | /// A streaming iterator which yields elements from an iterator of references. 301 | #[derive(Clone, Debug)] 302 | pub struct ConvertRef<'a, I, T: ?Sized> 303 | where 304 | I: Iterator, 305 | { 306 | it: I, 307 | item: Option<&'a T>, 308 | } 309 | 310 | impl<'a, I, T: ?Sized> StreamingIterator for ConvertRef<'a, I, T> 311 | where 312 | I: Iterator, 313 | { 314 | type Item = T; 315 | 316 | #[inline] 317 | fn advance(&mut self) { 318 | self.item = self.it.next(); 319 | } 320 | 321 | #[inline] 322 | fn get(&self) -> Option<&T> { 323 | self.item 324 | } 325 | 326 | #[inline] 327 | fn size_hint(&self) -> (usize, Option) { 328 | self.it.size_hint() 329 | } 330 | 331 | #[inline] 332 | fn count(self) -> usize { 333 | self.it.count() 334 | } 335 | 336 | #[inline] 337 | fn fold(self, init: Acc, f: Fold) -> Acc 338 | where 339 | Self: Sized, 340 | Fold: FnMut(Acc, &Self::Item) -> Acc, 341 | { 342 | self.it.fold(init, f) 343 | } 344 | } 345 | 346 | impl<'a, I, T: ?Sized> DoubleEndedStreamingIterator for ConvertRef<'a, I, T> 347 | where 348 | I: DoubleEndedIterator, 349 | { 350 | #[inline] 351 | fn advance_back(&mut self) { 352 | self.item = self.it.next_back(); 353 | } 354 | 355 | #[inline] 356 | fn rfold(self, init: Acc, f: Fold) -> Acc 357 | where 358 | Self: Sized, 359 | Fold: FnMut(Acc, &Self::Item) -> Acc, 360 | { 361 | self.it.rfold(init, f) 362 | } 363 | } 364 | 365 | /// A streaming iterator which yields elements from an iterator of mutable references. 366 | #[derive(Debug)] 367 | pub struct ConvertMut<'a, I, T: ?Sized> 368 | where 369 | I: Iterator, 370 | { 371 | it: I, 372 | item: Option<&'a mut T>, 373 | } 374 | 375 | impl<'a, I, T: ?Sized> StreamingIterator for ConvertMut<'a, I, T> 376 | where 377 | I: Iterator, 378 | { 379 | type Item = T; 380 | 381 | #[inline] 382 | fn advance(&mut self) { 383 | self.item = self.it.next(); 384 | } 385 | 386 | #[inline] 387 | fn get(&self) -> Option<&T> { 388 | match self.item { 389 | Some(&mut ref item) => Some(item), 390 | None => None, 391 | } 392 | } 393 | 394 | #[inline] 395 | fn size_hint(&self) -> (usize, Option) { 396 | self.it.size_hint() 397 | } 398 | 399 | #[inline] 400 | fn count(self) -> usize { 401 | self.it.count() 402 | } 403 | 404 | #[inline] 405 | fn fold(self, init: Acc, mut f: Fold) -> Acc 406 | where 407 | Self: Sized, 408 | Fold: FnMut(Acc, &Self::Item) -> Acc, 409 | { 410 | self.it.fold(init, move |acc, item| f(acc, item)) 411 | } 412 | } 413 | 414 | impl<'a, I, T: ?Sized> DoubleEndedStreamingIterator for ConvertMut<'a, I, T> 415 | where 416 | I: DoubleEndedIterator, 417 | { 418 | #[inline] 419 | fn advance_back(&mut self) { 420 | self.item = self.it.next_back(); 421 | } 422 | 423 | #[inline] 424 | fn rfold(self, init: Acc, mut f: Fold) -> Acc 425 | where 426 | Self: Sized, 427 | Fold: FnMut(Acc, &Self::Item) -> Acc, 428 | { 429 | self.it.rfold(init, move |acc, item| f(acc, item)) 430 | } 431 | } 432 | 433 | impl<'a, I, T: ?Sized> StreamingIteratorMut for ConvertMut<'a, I, T> 434 | where 435 | I: Iterator, 436 | { 437 | #[inline] 438 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 439 | match self.item { 440 | Some(&mut ref mut item) => Some(item), 441 | None => None, 442 | } 443 | } 444 | 445 | #[inline] 446 | fn fold_mut(self, init: B, f: F) -> B 447 | where 448 | Self: Sized, 449 | F: FnMut(B, &mut Self::Item) -> B, 450 | { 451 | self.it.fold(init, f) 452 | } 453 | } 454 | 455 | impl<'a, I, T: ?Sized> DoubleEndedStreamingIteratorMut for ConvertMut<'a, I, T> 456 | where 457 | I: DoubleEndedIterator, 458 | { 459 | #[inline] 460 | fn rfold_mut(self, init: B, f: F) -> B 461 | where 462 | Self: Sized, 463 | F: FnMut(B, &mut Self::Item) -> B, 464 | { 465 | self.it.rfold(init, f) 466 | } 467 | } 468 | 469 | /// A simple iterator that returns nothing. 470 | #[derive(Clone, Debug)] 471 | pub struct Empty { 472 | phantom: PhantomData, 473 | } 474 | 475 | impl StreamingIterator for Empty { 476 | type Item = T; 477 | 478 | #[inline] 479 | fn advance(&mut self) {} 480 | 481 | #[inline] 482 | fn get(&self) -> Option<&Self::Item> { 483 | None 484 | } 485 | 486 | #[inline] 487 | fn size_hint(&self) -> (usize, Option) { 488 | (0, Some(0)) 489 | } 490 | } 491 | 492 | impl DoubleEndedStreamingIterator for Empty { 493 | #[inline] 494 | fn advance_back(&mut self) {} 495 | } 496 | 497 | impl StreamingIteratorMut for Empty { 498 | #[inline] 499 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 500 | None 501 | } 502 | } 503 | 504 | impl DoubleEndedStreamingIteratorMut for Empty {} 505 | 506 | /// A simple iterator that returns items from a function call. 507 | #[derive(Clone, Debug)] 508 | pub struct FromFn { 509 | gen: F, 510 | item: Option, 511 | } 512 | 513 | impl Option> StreamingIterator for FromFn { 514 | type Item = T; 515 | 516 | #[inline] 517 | fn advance(&mut self) { 518 | self.item = (self.gen)(); 519 | } 520 | 521 | #[inline] 522 | fn get(&self) -> Option<&Self::Item> { 523 | self.item.as_ref() 524 | } 525 | } 526 | 527 | impl Option> StreamingIteratorMut for FromFn { 528 | #[inline] 529 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 530 | self.item.as_mut() 531 | } 532 | } 533 | 534 | /// A simple iterator that returns exactly one item. 535 | #[derive(Clone, Debug)] 536 | pub struct Once { 537 | first: bool, 538 | item: Option, 539 | } 540 | 541 | impl StreamingIterator for Once { 542 | type Item = T; 543 | 544 | #[inline] 545 | fn advance(&mut self) { 546 | if self.first { 547 | self.first = false; 548 | } else { 549 | self.item = None; 550 | } 551 | } 552 | 553 | #[inline] 554 | fn get(&self) -> Option<&Self::Item> { 555 | self.item.as_ref() 556 | } 557 | 558 | #[inline] 559 | fn size_hint(&self) -> (usize, Option) { 560 | let len = self.first as usize; 561 | (len, Some(len)) 562 | } 563 | } 564 | 565 | impl DoubleEndedStreamingIterator for Once { 566 | #[inline] 567 | fn advance_back(&mut self) { 568 | self.advance(); 569 | } 570 | } 571 | 572 | impl StreamingIteratorMut for Once { 573 | #[inline] 574 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 575 | self.item.as_mut() 576 | } 577 | } 578 | 579 | impl DoubleEndedStreamingIteratorMut for Once {} 580 | 581 | /// A simple iterator that returns exactly one item from a function call. 582 | #[derive(Clone, Debug)] 583 | pub struct OnceWith { 584 | gen: Option, 585 | item: Option, 586 | } 587 | 588 | impl T> StreamingIterator for OnceWith { 589 | type Item = T; 590 | 591 | #[inline] 592 | fn advance(&mut self) { 593 | self.item = self.gen.take().map(|gen| gen()); 594 | } 595 | 596 | #[inline] 597 | fn get(&self) -> Option<&Self::Item> { 598 | self.item.as_ref() 599 | } 600 | 601 | #[inline] 602 | fn size_hint(&self) -> (usize, Option) { 603 | let len = self.gen.is_some() as usize; 604 | (len, Some(len)) 605 | } 606 | } 607 | 608 | impl T> DoubleEndedStreamingIterator for OnceWith { 609 | #[inline] 610 | fn advance_back(&mut self) { 611 | self.advance(); 612 | } 613 | } 614 | 615 | impl T> StreamingIteratorMut for OnceWith { 616 | #[inline] 617 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 618 | self.item.as_mut() 619 | } 620 | } 621 | 622 | impl T> DoubleEndedStreamingIteratorMut for OnceWith {} 623 | 624 | /// A simple iterator that repeats an item endlessly. 625 | /// 626 | /// Note: if the item is modified through `StreamingIteratorMut`, 627 | /// this will continue be reflected in further iterations! 628 | #[derive(Clone, Debug)] 629 | pub struct Repeat { 630 | item: T, 631 | } 632 | 633 | impl StreamingIterator for Repeat { 634 | type Item = T; 635 | 636 | #[inline] 637 | fn advance(&mut self) {} 638 | 639 | #[inline] 640 | fn get(&self) -> Option<&Self::Item> { 641 | Some(&self.item) 642 | } 643 | 644 | #[inline] 645 | fn size_hint(&self) -> (usize, Option) { 646 | (usize::MAX, None) 647 | } 648 | } 649 | 650 | impl DoubleEndedStreamingIterator for Repeat { 651 | #[inline] 652 | fn advance_back(&mut self) {} 653 | } 654 | 655 | impl StreamingIteratorMut for Repeat { 656 | #[inline] 657 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 658 | Some(&mut self.item) 659 | } 660 | } 661 | 662 | impl DoubleEndedStreamingIteratorMut for Repeat {} 663 | 664 | /// A simple iterator that endlessly returns items from a function call. 665 | #[derive(Clone, Debug)] 666 | pub struct RepeatWith { 667 | gen: F, 668 | item: Option, 669 | } 670 | 671 | impl T> StreamingIterator for RepeatWith { 672 | type Item = T; 673 | 674 | #[inline] 675 | fn advance(&mut self) { 676 | self.item = Some((self.gen)()); 677 | } 678 | 679 | #[inline] 680 | fn get(&self) -> Option<&Self::Item> { 681 | self.item.as_ref() 682 | } 683 | 684 | #[inline] 685 | fn size_hint(&self) -> (usize, Option) { 686 | (usize::MAX, None) 687 | } 688 | } 689 | 690 | impl T> StreamingIteratorMut for RepeatWith { 691 | #[inline] 692 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 693 | self.item.as_mut() 694 | } 695 | } 696 | 697 | /// An iterator where each successive item is computed from the preceding one. 698 | /// 699 | /// Note: if an item is modified through `StreamingIteratorMut`, those changes 700 | /// will be visible to the successor function when the iterator is advanced. 701 | #[derive(Clone, Debug)] 702 | pub struct Successors { 703 | first: bool, 704 | item: Option, 705 | succ: F, 706 | } 707 | 708 | impl Option> StreamingIterator for Successors { 709 | type Item = T; 710 | 711 | #[inline] 712 | fn advance(&mut self) { 713 | if self.first { 714 | self.first = false; 715 | } else if let Some(item) = self.item.take() { 716 | self.item = (self.succ)(item); 717 | } 718 | } 719 | 720 | #[inline] 721 | fn get(&self) -> Option<&Self::Item> { 722 | self.item.as_ref() 723 | } 724 | 725 | #[inline] 726 | fn size_hint(&self) -> (usize, Option) { 727 | match (self.first, &self.item) { 728 | // We have a first item and unknown successors 729 | (true, &Some(_)) => (1, None), 730 | // We only have unknown successors 731 | (false, &Some(_)) => (0, None), 732 | // We have nothing. 733 | (_, &None) => (0, Some(0)), 734 | } 735 | } 736 | } 737 | 738 | impl Option> StreamingIteratorMut for Successors { 739 | #[inline] 740 | fn get_mut(&mut self) -> Option<&mut Self::Item> { 741 | self.item.as_mut() 742 | } 743 | } 744 | --------------------------------------------------------------------------------