diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
commit | 26a029d407be480d791972afb5975cf62c9360a6 (patch) | |
tree | f435a8308119effd964b339f76abb83a57c29483 /third_party/rust/fallible-streaming-iterator | |
parent | Initial commit. (diff) | |
download | firefox-26a029d407be480d791972afb5975cf62c9360a6.tar.xz firefox-26a029d407be480d791972afb5975cf62c9360a6.zip |
Adding upstream version 124.0.1.upstream/124.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/fallible-streaming-iterator')
6 files changed, 1168 insertions, 0 deletions
diff --git a/third_party/rust/fallible-streaming-iterator/.cargo-checksum.json b/third_party/rust/fallible-streaming-iterator/.cargo-checksum.json new file mode 100644 index 0000000000..059cf13544 --- /dev/null +++ b/third_party/rust/fallible-streaming-iterator/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"9af8cd50237f6a32a46ae7d0f3d39555dc7cdb97b247535c191582a4a299d58c","LICENSE-APACHE":"c6596eb7be8581c18be736c846fb9173b69eccf6ef94c5135893ec56bd92ba08","LICENSE-MIT":"8dcec5569a9be5b0e086c80faed6f1aefa670af0ec29cecc2f714303096887e0","README.md":"73f5daabf0443f5253c00dfc3b1d2f9cb057f12b0160de27b95da7312df8aa34","src/lib.rs":"7fb7428997bdd89c3ee0818ecee642f8d93882c9c66171c9c6194b732f337089"},"package":"7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"}
\ No newline at end of file diff --git a/third_party/rust/fallible-streaming-iterator/Cargo.toml b/third_party/rust/fallible-streaming-iterator/Cargo.toml new file mode 100644 index 0000000000..b086cdb11b --- /dev/null +++ b/third_party/rust/fallible-streaming-iterator/Cargo.toml @@ -0,0 +1,25 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "fallible-streaming-iterator" +version = "0.1.9" +authors = ["Steven Fackler <sfackler@gmail.com>"] +description = "Fallible streaming iteration" +readme = "README.md" +license = "MIT/Apache-2.0" +repository = "https://github.com/sfackler/fallible-streaming-iterator" + +[dependencies] + +[features] +std = [] diff --git a/third_party/rust/fallible-streaming-iterator/LICENSE-APACHE b/third_party/rust/fallible-streaming-iterator/LICENSE-APACHE new file mode 100644 index 0000000000..8f71f43fee --- /dev/null +++ b/third_party/rust/fallible-streaming-iterator/LICENSE-APACHE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/third_party/rust/fallible-streaming-iterator/LICENSE-MIT b/third_party/rust/fallible-streaming-iterator/LICENSE-MIT new file mode 100644 index 0000000000..41aaea31af --- /dev/null +++ b/third_party/rust/fallible-streaming-iterator/LICENSE-MIT @@ -0,0 +1,19 @@ +Copyright (c) 2016 The fallible-streaming-iterator Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third_party/rust/fallible-streaming-iterator/README.md b/third_party/rust/fallible-streaming-iterator/README.md new file mode 100644 index 0000000000..f0854028e0 --- /dev/null +++ b/third_party/rust/fallible-streaming-iterator/README.md @@ -0,0 +1,22 @@ +# fallible-streaming-iterator +[![CircleCI](https://circleci.com/gh/sfackler/fallible-streaming-iterator.svg?style=shield)](https://circleci.com/gh/sfackler/fallible-streaming-iterator) + +[Documentation](https://docs.rs/fallible-streaming-iterator) + +Fallible, streaming iteration + +## License + +Licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally +submitted for inclusion in the work by you, as defined in the Apache-2.0 +license, shall be dual licensed as above, without any additional terms or +conditions. diff --git a/third_party/rust/fallible-streaming-iterator/src/lib.rs b/third_party/rust/fallible-streaming-iterator/src/lib.rs new file mode 100644 index 0000000000..69262d6aef --- /dev/null +++ b/third_party/rust/fallible-streaming-iterator/src/lib.rs @@ -0,0 +1,899 @@ +//! Fallible, streaming iteration. +//! +//! `FallibleStreamingIterator` differs from the standard library's `Iterator` trait in two ways: +//! iteration can fail, resulting in an error, and only one element of the iteration is available at +//! any time. +//! +//! While these iterators cannot be used with Rust `for` loops, `while let` loops offer a similar +//! level of ergonomics: +//! +//! ```ignore +//! while let Some(value) = it.next()? { +//! // use value +//! } +//! ``` +#![doc(html_root_url = "https://docs.rs/fallible-streaming-iterator/0.1")] +#![warn(missing_docs)] +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg(feature = "std")] +extern crate core; + +use core::cmp; +use core::marker::PhantomData; + +/// A fallible, streaming iterator. +pub trait FallibleStreamingIterator { + /// The type being iterated over. + type Item: ?Sized; + + /// The error type of iteration. + type Error; + + /// Advances the iterator to the next position. + /// + /// Iterators start just before the first item, so this method should be called before `get` + /// when iterating. + /// + /// The behavior of calling this method after `get` has returned `None`, or after this method + /// has returned an error is unspecified. + fn advance(&mut self) -> Result<(), Self::Error>; + + /// Returns the current element. + /// + /// The behavior of calling this method before any calls to `advance` is unspecified. + fn get(&self) -> Option<&Self::Item>; + + /// Advances the iterator, returning the next element. + /// + /// The default implementation simply calls `advance` followed by `get`. + #[inline] + fn next(&mut self) -> Result<Option<&Self::Item>, Self::Error> { + self.advance()?; + Ok((*self).get()) + } + + /// Returns bounds on the number of remaining elements in the iterator. + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + (0, None) + } + + /// Determines if all elements of the iterator satisfy a predicate. + #[inline] + fn all<F>(&mut self, mut f: F) -> Result<bool, Self::Error> + where + Self: Sized, + F: FnMut(&Self::Item) -> bool, + { + while let Some(e) = self.next()? { + if !f(e) { + return Ok(false); + } + } + Ok(true) + } + + /// Determines if any elements of the iterator satisfy a predicate. + #[inline] + fn any<F>(&mut self, mut f: F) -> Result<bool, Self::Error> + where + Self: Sized, + F: FnMut(&Self::Item) -> bool, + { + self.all(|e| !f(e)).map(|r| !r) + } + + /// Borrows an iterator, rather than consuming it. + /// + /// This is useful to allow the application of iterator adaptors while still retaining ownership + /// of the original adaptor. + #[inline] + fn by_ref(&mut self) -> &mut Self + where + Self: Sized, + { + self + } + + /// Returns the number of remaining elements in the iterator. + #[inline] + fn count(mut self) -> Result<usize, Self::Error> + where + Self: Sized, + { + let mut count = 0; + while let Some(_) = self.next()? { + count += 1; + } + Ok(count) + } + + /// Returns an iterator which filters elements by a predicate. + #[inline] + fn filter<F>(self, f: F) -> Filter<Self, F> + where + Self: Sized, + F: FnMut(&Self::Item) -> bool, + { + Filter { it: self, f: f } + } + + /// Returns the first element of the iterator which satisfies a predicate. + #[inline] + fn find<F>(&mut self, mut f: F) -> Result<Option<&Self::Item>, Self::Error> + where + Self: Sized, + F: FnMut(&Self::Item) -> bool, + { + loop { + self.advance()?; + match self.get() { + Some(v) => { + if f(v) { + break; + } + } + None => break, + } + } + Ok((*self).get()) + } + + /// Calls a closure on each element of an iterator. + #[inline] + fn for_each<F>(mut self, mut f: F) -> Result<(), Self::Error> + where + Self: Sized, + F: FnMut(&Self::Item), + { + while let Some(value) = self.next()? { + f(value); + } + Ok(()) + } + + /// Returns an iterator which is well-behaved at the beginning and end of iteration. + #[inline] + fn fuse(self) -> Fuse<Self> + where + Self: Sized, + { + Fuse { + it: self, + state: FuseState::Start, + } + } + + /// Returns an iterator which applies a transform to elements. + #[inline] + fn map<F, B>(self, f: F) -> Map<Self, F, B> + where + Self: Sized, + F: FnMut(&Self::Item) -> B, + { + Map { + it: self, + f: f, + value: None, + } + } + + /// Returns an iterator which applies a transform to elements. + /// + /// Unlike `map`, the the closure provided to this method returns a reference into the original + /// value. + #[inline] + fn map_ref<F, B: ?Sized>(self, f: F) -> MapRef<Self, F> + where + Self: Sized, + F: Fn(&Self::Item) -> &B, + { + MapRef { it: self, f: f } + } + + /// Returns an iterator that applies a transform to errors. + #[inline] + fn map_err<F, B>(self, f: F) -> MapErr<Self, F> + where + Self: Sized, + F: Fn(Self::Error) -> B, + { + MapErr { it: self, f: f } + } + + /// Returns the `nth` element of the iterator. + #[inline] + fn nth(&mut self, n: usize) -> Result<Option<&Self::Item>, Self::Error> { + for _ in 0..n { + self.advance()?; + if let None = self.get() { + return Ok(None); + } + } + self.next() + } + + /// Returns the position of the first element matching a predicate. + #[inline] + fn position<F>(&mut self, mut f: F) -> Result<Option<usize>, Self::Error> + where + Self: Sized, + F: FnMut(&Self::Item) -> bool, + { + let mut pos = 0; + while let Some(v) = self.next()? { + if f(v) { + return Ok(Some(pos)); + } + pos += 1; + } + Ok(None) + } + + /// Returns an iterator which skips the first `n` elements. + #[inline] + fn skip(self, n: usize) -> Skip<Self> + where + Self: Sized, + { + Skip { it: self, n: n } + } + + /// Returns an iterator which skips the first sequence of elements matching a predicate. + #[inline] + fn skip_while<F>(self, f: F) -> SkipWhile<Self, F> + where + Self: Sized, + F: FnMut(&Self::Item) -> bool, + { + SkipWhile { + it: self, + f: f, + done: false, + } + } + + /// Returns an iterator which only returns the first `n` elements. + #[inline] + fn take(self, n: usize) -> Take<Self> + where + Self: Sized, + { + Take { + it: self, + n: n, + done: false, + } + } + + /// Returns an iterator which only returns the first sequence of elements matching a predicate. + #[inline] + fn take_while<F>(self, f: F) -> TakeWhile<Self, F> + where + Self: Sized, + F: FnMut(&Self::Item) -> bool, + { + TakeWhile { + it: self, + f: f, + done: false, + } + } +} + +/// A fallible, streaming iterator which can be advanced from either end. +pub trait DoubleEndedFallibleStreamingIterator: FallibleStreamingIterator { + /// Advances the state of the iterator to the next item from the end. + /// + /// Iterators start just after the last item, so this method should be called before `get` + /// when iterating. + /// + /// The behavior of calling this method after `get` has returned `None`, or after this method + /// or `advance` has returned an error is unspecified. + fn advance_back(&mut self) -> Result<(), Self::Error>; + + /// Advances the back of the iterator, returning the last element. + /// + /// The default implementation simply calls `advance_back` followed by `get`. + #[inline] + fn next_back(&mut self) -> Result<Option<&Self::Item>, Self::Error> { + self.advance_back()?; + Ok((*self).get()) + } +} + +impl<'a, I: ?Sized> FallibleStreamingIterator for &'a mut I +where + I: FallibleStreamingIterator, +{ + type Item = I::Item; + type Error = I::Error; + + #[inline] + fn advance(&mut self) -> Result<(), I::Error> { + (**self).advance() + } + + #[inline] + fn get(&self) -> Option<&I::Item> { + (**self).get() + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + (**self).size_hint() + } + + #[inline] + fn next(&mut self) -> Result<Option<&I::Item>, I::Error> { + (**self).next() + } +} + +#[cfg(feature = "std")] +impl<I: ?Sized> FallibleStreamingIterator for Box<I> +where + I: FallibleStreamingIterator, +{ + type Item = I::Item; + type Error = I::Error; + + #[inline] + fn advance(&mut self) -> Result<(), I::Error> { + (**self).advance() + } + + #[inline] + fn get(&self) -> Option<&I::Item> { + (**self).get() + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + (**self).size_hint() + } + + #[inline] + fn next(&mut self) -> Result<Option<&I::Item>, I::Error> { + (**self).next() + } +} + +/// Converts a normal `Iterator` over `Results` of references into a +/// `FallibleStreamingIterator`. +pub fn convert<'a, I, T, E>(it: I) -> Convert<'a, I, T> +where + I: Iterator<Item = Result<&'a T, E>>, +{ + Convert { it: it, item: None } +} + +/// An iterator which wraps a normal `Iterator`. +pub struct Convert<'a, I, T: 'a> { + it: I, + item: Option<&'a T>, +} + +impl<'a, I, T, E> FallibleStreamingIterator for Convert<'a, I, T> +where + I: Iterator<Item = Result<&'a T, E>>, +{ + type Item = T; + type Error = E; + + #[inline] + fn advance(&mut self) -> Result<(), E> { + self.item = match self.it.next() { + Some(Ok(v)) => Some(v), + Some(Err(e)) => return Err(e), + None => None, + }; + Ok(()) + } + + #[inline] + fn get(&self) -> Option<&T> { + self.item + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + self.it.size_hint() + } +} + +impl<'a, I, T, E> DoubleEndedFallibleStreamingIterator for Convert<'a, I, T> +where + I: DoubleEndedIterator<Item = Result<&'a T, E>>, +{ + #[inline] + fn advance_back(&mut self) -> Result<(), E> { + self.item = match self.it.next_back() { + Some(Ok(v)) => Some(v), + Some(Err(e)) => return Err(e), + None => None, + }; + Ok(()) + } +} + +/// Returns an iterator over no items. +pub fn empty<T, E>() -> Empty<T, E> { + Empty(PhantomData) +} + +/// An iterator over no items. +pub struct Empty<T, E>(PhantomData<(T, E)>); + +impl<T, E> FallibleStreamingIterator for Empty<T, E> { + type Item = T; + type Error = E; + + #[inline] + fn advance(&mut self) -> Result<(), E> { + Ok(()) + } + + #[inline] + fn get(&self) -> Option<&T> { + None + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + (0, Some(0)) + } +} + +impl<T, E> DoubleEndedFallibleStreamingIterator for Empty<T, E> { + #[inline] + fn advance_back(&mut self) -> Result<(), E> { + Ok(()) + } +} + +/// An iterator which filters elements with a predicate. +pub struct Filter<I, F> { + it: I, + f: F, +} + +impl<I, F> FallibleStreamingIterator for Filter<I, F> +where + I: FallibleStreamingIterator, + F: FnMut(&I::Item) -> bool, +{ + type Item = I::Item; + type Error = I::Error; + + #[inline] + fn advance(&mut self) -> Result<(), I::Error> { + while let Some(i) = self.it.next()? { + if (self.f)(i) { + break; + } + } + Ok(()) + } + + #[inline] + fn get(&self) -> Option<&I::Item> { + self.it.get() + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + (0, self.it.size_hint().1) + } +} + +#[derive(Copy, Clone)] +enum FuseState { + Start, + Middle, + End, +} + +/// An iterator which is well-behaved at the beginning and end of iteration. +pub struct Fuse<I> { + it: I, + state: FuseState, +} + +impl<I> FallibleStreamingIterator for Fuse<I> +where + I: FallibleStreamingIterator, +{ + type Item = I::Item; + type Error = I::Error; + + #[inline] + fn advance(&mut self) -> Result<(), I::Error> { + match self.state { + FuseState::Start => { + match self.it.next() { + Ok(Some(_)) => self.state = FuseState::Middle, + Ok(None) => self.state = FuseState::End, + Err(e) => { + self.state = FuseState::End; + return Err(e); + } + }; + } + FuseState::Middle => match self.it.next() { + Ok(Some(_)) => {} + Ok(None) => self.state = FuseState::End, + Err(e) => { + self.state = FuseState::End; + return Err(e); + } + }, + FuseState::End => {} + } + Ok(()) + } + + #[inline] + fn get(&self) -> Option<&I::Item> { + match self.state { + FuseState::Middle => self.it.get(), + FuseState::Start | FuseState::End => None, + } + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + self.it.size_hint() + } + + #[inline] + fn next(&mut self) -> Result<Option<&I::Item>, I::Error> { + match self.state { + FuseState::Start => match self.it.next() { + Ok(Some(v)) => { + self.state = FuseState::Middle; + Ok(Some(v)) + } + Ok(None) => { + self.state = FuseState::End; + Ok(None) + } + Err(e) => { + self.state = FuseState::End; + Err(e) + } + }, + FuseState::Middle => match self.it.next() { + Ok(Some(v)) => Ok(Some(v)), + Ok(None) => { + self.state = FuseState::End; + Ok(None) + } + Err(e) => { + self.state = FuseState::End; + Err(e) + } + }, + FuseState::End => Ok(None), + } + } +} + +/// An iterator which applies a transform to elements. +pub struct Map<I, F, B> { + it: I, + f: F, + value: Option<B>, +} + +impl<I, F, B> FallibleStreamingIterator for Map<I, F, B> +where + I: FallibleStreamingIterator, + F: FnMut(&I::Item) -> B, +{ + type Item = B; + type Error = I::Error; + + #[inline] + fn advance(&mut self) -> Result<(), I::Error> { + self.value = self.it.next()?.map(&mut self.f); + Ok(()) + } + + #[inline] + fn get(&self) -> Option<&B> { + self.value.as_ref() + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + self.it.size_hint() + } +} + +impl<I, F, B> DoubleEndedFallibleStreamingIterator for Map<I, F, B> +where + I: DoubleEndedFallibleStreamingIterator, + F: FnMut(&I::Item) -> B, +{ + #[inline] + fn advance_back(&mut self) -> Result<(), I::Error> { + self.value = self.it.next_back()?.map(&mut self.f); + Ok(()) + } +} + +/// An iterator which applies a transform to elements. +pub struct MapRef<I, F> { + it: I, + f: F, +} + +impl<I, F, B: ?Sized> FallibleStreamingIterator for MapRef<I, F> +where + I: FallibleStreamingIterator, + F: Fn(&I::Item) -> &B, +{ + type Item = B; + type Error = I::Error; + + #[inline] + fn advance(&mut self) -> Result<(), I::Error> { + self.it.advance() + } + + #[inline] + fn get(&self) -> Option<&B> { + self.it.get().map(&self.f) + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + self.it.size_hint() + } +} + +impl<I, F, B: ?Sized> DoubleEndedFallibleStreamingIterator for MapRef<I, F> +where + I: DoubleEndedFallibleStreamingIterator, + F: Fn(&I::Item) -> &B, +{ + #[inline] + fn advance_back(&mut self) -> Result<(), I::Error> { + self.it.advance_back() + } +} + +/// An iterator which applies a transform to errors. +pub struct MapErr<I, F> { + it: I, + f: F, +} + +impl<I, F, B> FallibleStreamingIterator for MapErr<I, F> +where + I: FallibleStreamingIterator, + F: Fn(I::Error) -> B, +{ + type Item = I::Item; + type Error = B; + + #[inline] + fn advance(&mut self) -> Result<(), B> { + self.it.advance().map_err(&mut self.f) + } + + #[inline] + fn get(&self) -> Option<&I::Item> { + self.it.get() + } + + #[inline] + fn next(&mut self) -> Result<Option<&I::Item>, B> { + self.it.next().map_err(&mut self.f) + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + self.it.size_hint() + } +} + +impl<I, F, B> DoubleEndedFallibleStreamingIterator for MapErr<I, F> +where + I: DoubleEndedFallibleStreamingIterator, + F: Fn(I::Error) -> B, +{ + #[inline] + fn advance_back(&mut self) -> Result<(), B> { + self.it.advance_back().map_err(&mut self.f) + } + + #[inline] + fn next_back(&mut self) -> Result<Option<&I::Item>, B> { + self.it.next_back().map_err(&mut self.f) + } +} + +/// An iterator which skips a number of initial elements. +pub struct Skip<I> { + it: I, + n: usize, +} + +impl<I> FallibleStreamingIterator for Skip<I> +where + I: FallibleStreamingIterator, +{ + type Item = I::Item; + type Error = I::Error; + + #[inline] + fn advance(&mut self) -> Result<(), I::Error> { + for _ in 0..self.n { + if let None = self.it.next()? { + return Ok(()); + } + } + self.n = 0; + self.advance() + } + + #[inline] + fn get(&self) -> Option<&I::Item> { + self.it.get() + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + let hint = self.it.size_hint(); + ( + hint.0.saturating_sub(self.n), + hint.1.map(|h| h.saturating_sub(self.n)), + ) + } +} + +/// An iterator which skips initial elements matching a predicate. +pub struct SkipWhile<I, F> { + it: I, + f: F, + done: bool, +} + +impl<I, F> FallibleStreamingIterator for SkipWhile<I, F> +where + I: FallibleStreamingIterator, + F: FnMut(&I::Item) -> bool, +{ + type Item = I::Item; + type Error = I::Error; + + #[inline] + fn advance(&mut self) -> Result<(), I::Error> { + if !self.done { + self.done = true; + let f = &mut self.f; + self.it.find(|i| !f(i)).map(|_| ()) + } else { + self.it.advance() + } + } + + #[inline] + fn get(&self) -> Option<&I::Item> { + self.it.get() + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + let hint = self.it.size_hint(); + if self.done { + hint + } else { + (0, hint.1) + } + } +} + +/// An iterator which only returns a number of initial elements. +pub struct Take<I> { + it: I, + n: usize, + done: bool, +} + +impl<I> FallibleStreamingIterator for Take<I> +where + I: FallibleStreamingIterator, +{ + type Item = I::Item; + type Error = I::Error; + + #[inline] + fn advance(&mut self) -> Result<(), I::Error> { + if self.n != 0 { + self.it.advance()?; + self.n -= 1; + } else { + self.done = true; + } + Ok(()) + } + + #[inline] + fn get(&self) -> Option<&I::Item> { + if self.done { + None + } else { + self.it.get() + } + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + let (lower, upper) = self.it.size_hint(); + + let lower = cmp::min(lower, self.n); + + let upper = match upper { + Some(x) if x < self.n => Some(x), + _ => Some(self.n) + }; + + (lower, upper) + } +} + +/// An iterator which only returns initial elements matching a predicate. +pub struct TakeWhile<I, F> { + it: I, + f: F, + done: bool, +} + +impl<I, F> FallibleStreamingIterator for TakeWhile<I, F> +where + I: FallibleStreamingIterator, + F: FnMut(&I::Item) -> bool, +{ + type Item = I::Item; + type Error = I::Error; + + #[inline] + fn advance(&mut self) -> Result<(), I::Error> { + if let Some(v) = self.it.next()? { + if !(self.f)(v) { + self.done = true; + } + } + Ok(()) + } + + #[inline] + fn get(&self) -> Option<&I::Item> { + if self.done { + None + } else { + self.it.get() + } + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + if self.done { + (0, Some(0)) + } else { + (0, self.it.size_hint().1) + } + } +} + +#[cfg(test)] +mod test { + use super::*; + + fn _is_object_safe(_: &FallibleStreamingIterator<Item = (), Error = ()>) {} + fn _is_object_safe_double(_: &DoubleEndedFallibleStreamingIterator<Item = (), Error = ()>) {} +} |