From d1b2d29528b7794b41e66fc2136e395a02f8529b Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Thu, 30 May 2024 05:59:35 +0200 Subject: Merging upstream version 1.73.0+dfsg1. Signed-off-by: Daniel Baumann --- vendor/fallible-iterator/src/lib.rs | 488 +++++++++++++++++++++++++---------- vendor/fallible-iterator/src/test.rs | 52 ++-- 2 files changed, 382 insertions(+), 158 deletions(-) (limited to 'vendor/fallible-iterator/src') diff --git a/vendor/fallible-iterator/src/lib.rs b/vendor/fallible-iterator/src/lib.rs index f5f77b257..88e8d557a 100644 --- a/vendor/fallible-iterator/src/lib.rs +++ b/vendor/fallible-iterator/src/lib.rs @@ -65,40 +65,20 @@ //! ``` #![doc(html_root_url = "https://docs.rs/fallible-iterator/0.2")] #![warn(missing_docs)] -#![cfg_attr(feature = "alloc", feature(alloc))] #![no_std] use core::cmp::{self, Ordering}; +use core::convert::Infallible; use core::iter; +use core::marker::PhantomData; -#[cfg(all(feature = "alloc", not(feature = "std")))] -#[cfg_attr(test, macro_use)] +#[cfg(feature = "alloc")] extern crate alloc; -#[cfg(all(feature = "alloc", not(feature = "std")))] -mod imports { - pub use alloc::boxed::Box; - pub use alloc::collections::btree_map::BTreeMap; - pub use alloc::collections::btree_set::BTreeSet; - pub use alloc::vec::Vec; -} - -#[cfg(feature = "std")] -#[cfg_attr(test, macro_use)] -extern crate std; - -#[cfg(feature = "std")] -mod imports { - pub use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; - pub use std::hash::{BuildHasher, Hash}; - pub use std::prelude::v1::*; -} +#[cfg(feature = "alloc")] +use alloc::boxed::Box; -#[cfg(any(feature = "std", feature = "alloc"))] -use crate::imports::*; - -#[cfg(any(feature = "std", feature = "alloc"))] -#[cfg(test)] +#[cfg(all(test, feature = "alloc"))] mod test; enum FoldStop { @@ -141,7 +121,7 @@ pub trait FallibleIterator { /// Returns `Ok(None)` when iteration is finished. /// /// The behavior of calling this method after a previous call has returned - /// `Ok(None)` or `Err` is implemenetation defined. + /// `Ok(None)` or `Err` is implementation defined. fn next(&mut self) -> Result, Self::Error>; /// Returns bounds on the remaining length of the iterator. @@ -245,7 +225,7 @@ pub trait FallibleIterator { Self: Sized, F: FnMut(Self::Item) -> Result, { - Map { it: self, f: f } + Map { it: self, f } } /// Calls a fallible closure on each element of an iterator. @@ -267,7 +247,7 @@ pub trait FallibleIterator { Self: Sized, F: FnMut(&Self::Item) -> Result, { - Filter { it: self, f: f } + Filter { it: self, f } } /// Returns an iterator which both filters and maps. The closure may fail; @@ -278,7 +258,7 @@ pub trait FallibleIterator { Self: Sized, F: FnMut(Self::Item) -> Result, Self::Error>, { - FilterMap { it: self, f: f } + FilterMap { it: self, f } } /// Returns an iterator which yields the current iteration count as well @@ -441,10 +421,10 @@ pub trait FallibleIterator { #[inline] fn collect(self) -> Result where - T: FromFallibleIterator, + T: iter::FromIterator, Self: Sized, { - T::from_fallible_iter(self) + self.iterator().collect() } /// Transforms the iterator into two collections, partitioning elements by a closure. @@ -731,7 +711,7 @@ pub trait FallibleIterator { Cloned(self) } - /// Returns an iterator which repeas this iterator endlessly. + /// Returns an iterator which repeats this iterator endlessly. #[inline] fn cycle(self) -> Cycle where @@ -960,7 +940,17 @@ pub trait FallibleIterator { F: FnMut(Self::Error) -> B, Self: Sized, { - MapErr { it: self, f: f } + MapErr { it: self, f } + } + + /// Returns an iterator which unwraps all of its elements. + #[inline] + fn unwrap(self) -> Unwrap + where + Self: Sized + FallibleIterator, + Self::Error: core::fmt::Debug, + { + Unwrap(self) } } @@ -991,7 +981,7 @@ impl DoubleEndedFallibleIterator for &m } } -#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg(feature = "alloc")] impl FallibleIterator for Box { type Item = I::Item; type Error = I::Error; @@ -1012,7 +1002,7 @@ impl FallibleIterator for Box { } } -#[cfg(any(feature = "std", feature = "alloc"))] +#[cfg(feature = "alloc")] impl DoubleEndedFallibleIterator for Box { #[inline] fn next_back(&mut self) -> Result, I::Error> { @@ -1052,112 +1042,6 @@ pub trait DoubleEndedFallibleIterator: FallibleIterator { } } -/// Conversion from a fallible iterator. -pub trait FromFallibleIterator: Sized { - /// Creates a value from a fallible iterator. - fn from_fallible_iter(it: I) -> Result - where - I: IntoFallibleIterator; -} - -#[cfg(any(feature = "std", feature = "alloc"))] -impl FromFallibleIterator for Vec { - #[inline] - fn from_fallible_iter(it: I) -> Result, I::Error> - where - I: IntoFallibleIterator, - { - let it = it.into_fallible_iter(); - let mut vec = Vec::with_capacity(it.size_hint().0); - it.for_each(|v| Ok(vec.push(v)))?; - Ok(vec) - } -} - -#[cfg(feature = "std")] -impl FromFallibleIterator for HashSet -where - T: Hash + Eq, - S: BuildHasher + Default, -{ - #[inline] - fn from_fallible_iter(it: I) -> Result, I::Error> - where - I: IntoFallibleIterator, - { - let it = it.into_fallible_iter(); - let mut set = HashSet::default(); - set.reserve(it.size_hint().0); - it.for_each(|v| { - set.insert(v); - Ok(()) - })?; - Ok(set) - } -} - -#[cfg(feature = "std")] -impl FromFallibleIterator<(K, V)> for HashMap -where - K: Hash + Eq, - S: BuildHasher + Default, -{ - #[inline] - fn from_fallible_iter(it: I) -> Result, I::Error> - where - I: IntoFallibleIterator, - { - let it = it.into_fallible_iter(); - let mut map = HashMap::default(); - map.reserve(it.size_hint().0); - it.for_each(|(k, v)| { - map.insert(k, v); - Ok(()) - })?; - Ok(map) - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -impl FromFallibleIterator for BTreeSet -where - T: Ord, -{ - #[inline] - fn from_fallible_iter(it: I) -> Result, I::Error> - where - I: IntoFallibleIterator, - { - let it = it.into_fallible_iter(); - let mut set = BTreeSet::new(); - it.for_each(|v| { - set.insert(v); - Ok(()) - })?; - Ok(set) - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -impl FromFallibleIterator<(K, V)> for BTreeMap -where - K: Ord, -{ - #[inline] - fn from_fallible_iter(it: I) -> Result, I::Error> - where - I: IntoFallibleIterator, - { - let it = it.into_fallible_iter(); - let mut map = BTreeMap::new(); - it.for_each(|(k, v)| { - map.insert(k, v); - Ok(()) - })?; - Ok(map) - } -} - /// Conversion into a `FallibleIterator`. pub trait IntoFallibleIterator { /// The elements of the iterator. @@ -1189,12 +1073,18 @@ where /// An iterator which applies a fallible transform to the elements of the /// underlying iterator. -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct Map { it: T, f: F, } +impl core::fmt::Debug for Map { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Map").field("iter", &self.it).finish() + } +} + impl FallibleIterator for Map where T: FallibleIterator, @@ -1519,6 +1409,62 @@ where } } +/// A fallible iterator that wraps a normal iterator over `Result`s. +#[derive(Clone, Debug)] +pub struct IntoFallible(I); + +impl FallibleIterator for IntoFallible +where + I: iter::Iterator, +{ + type Item = T; + type Error = Infallible; + + #[inline] + fn next(&mut self) -> Result, Self::Error> { + Ok(self.0.next()) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + self.0.size_hint() + } + + #[inline] + fn try_fold(&mut self, init: B, f: F) -> Result + where + E2: From, + F: FnMut(B, T) -> Result, + { + self.0.try_fold(init, f) + } +} + +impl> From for IntoFallible { + fn from(value: I) -> Self { + Self(value) + } +} + +impl DoubleEndedFallibleIterator for IntoFallible +where + I: DoubleEndedIterator, +{ + #[inline] + fn next_back(&mut self) -> Result, Infallible> { + Ok(self.0.next_back()) + } + + #[inline] + fn try_rfold(&mut self, init: B, f: F) -> Result + where + E2: From, + F: FnMut(B, T) -> Result, + { + self.0.try_rfold(init, f) + } +} + /// An iterator that yields the iteration count as well as the values of the /// underlying iterator. #[derive(Clone, Debug)] @@ -1888,6 +1834,52 @@ where } } +/// Creates an iterator from a fallible function generating values. +/// +/// ``` +/// # use fallible_iterator::{from_fn, FallibleIterator}; +/// let mut count = 0; +/// let counter = from_fn(move || { +/// // Increment our count. This is why we started at zero. +/// count += 1; +/// +/// // Check to see if we've finished counting or not. +/// if count < 6 { +/// Ok(Some(count)) +/// } else if count < 7 { +/// Ok(None) +/// } else { +/// Err(()) +/// } +/// }); +/// assert_eq!(&counter.collect::>().unwrap(), &[1, 2, 3, 4, 5]); +/// ``` +#[inline] +pub fn from_fn(fun: F) -> FromFn +where + F: FnMut() -> Result, E>, +{ + FromFn { fun } +} + +/// An iterator using a function to generate new values. +#[derive(Clone, Debug)] +pub struct FromFn { + fun: F, +} + +impl FallibleIterator for FromFn +where + F: FnMut() -> Result, E>, +{ + type Item = I; + type Error = E; + + fn next(&mut self) -> Result, E> { + (self.fun)() + } +} + /// An iterator that yields `Ok(None)` forever after the underlying iterator /// yields `Ok(None)` once. #[derive(Clone, Debug)] @@ -2199,6 +2191,27 @@ where Ok(self.next.as_ref()) } + + /// Consume and return the next value of this iterator if a condition is true. + /// + /// If func returns true for the next value of this iterator, consume and return it. Otherwise, return None. + #[inline] + pub fn next_if(&mut self, f: impl Fn(&I::Item) -> bool) -> Result, I::Error> { + match self.peek()? { + Some(item) if f(item) => self.next(), + _ => Ok(None), + } + } + + /// Consume and return the next item if it is equal to `expected`. + #[inline] + pub fn next_if_eq(&mut self, expected: &T) -> Result, I::Error> + where + T: ?Sized, + I::Item: PartialEq, + { + self.next_if(|found| found == expected) + } } impl FallibleIterator for Peekable @@ -2603,4 +2616,193 @@ where } } +/// An iterator that unwraps every element yielded by the underlying +/// FallibleIterator +#[derive(Clone, Debug)] +pub struct Unwrap(T); + +impl iter::Iterator for Unwrap +where + T: FallibleIterator, + T::Error: core::fmt::Debug, +{ + type Item = T::Item; + + #[inline] + fn next(&mut self) -> Option { + self.0.next().unwrap() + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + let (_, max) = self.0.size_hint(); + (0, max) + } +} + fn _is_object_safe(_: &dyn DoubleEndedFallibleIterator) {} + +/// An extnsion-trait with set of useful methods to convert [`core::iter::Iterator`] +/// into [`FallibleIterator`] +pub trait IteratorExt { + /// Convert an iterator of `Result`s into `FallibleIterator` by transposition + fn transpose_into_fallible(self) -> Convert + where + Self: iter::Iterator> + Sized; + + /// Convert an iterator of anything into `FallibleIterator` by wrapping + /// into `Result` where `Infallible` is an error that can never actually + /// happen. + fn into_fallible(self) -> IntoFallible + where + Self: iter::Iterator + Sized; +} + +impl IteratorExt for I +where + I: iter::Iterator, +{ + /// Convert an iterator of `Result`s into `FallibleIterator` by transposition + fn transpose_into_fallible(self) -> Convert + where + Self: iter::Iterator> + Sized, + { + Convert(self) + } + + /// Convert an iterator of anything into `FallibleIterator` by wrapping + /// into `Result` where `Infallible` is an error that can never actually + /// happen. + fn into_fallible(self) -> IntoFallible + where + Self: iter::Iterator + Sized, + { + IntoFallible(self) + } +} + +/// An iterator that yields nothing. +#[derive(Clone, Debug)] +pub struct Empty(PhantomData, PhantomData); + +impl FallibleIterator for Empty { + type Item = T; + type Error = E; + + #[inline] + fn next(&mut self) -> Result, E> { + Ok(None) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + (0, Some(0)) + } +} + +/// Creates an iterator that yields nothing. +pub fn empty() -> Empty { + Empty(PhantomData, PhantomData) +} + +/// An iterator that yields something exactly once. +#[derive(Clone, Debug)] +pub struct Once(Option, PhantomData); + +/// Creates an iterator that yields an element exactly once. +pub fn once(value: T) -> Once { + Once(Some(value), PhantomData) +} + +impl FallibleIterator for Once { + type Item = T; + type Error = E; + + #[inline] + fn next(&mut self) -> Result, Self::Error> { + Ok(self.0.take()) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + match self.0 { + Some(_) => (1, Some(1)), + None => (0, Some(0)), + } + } +} + +/// An iterator that fails with a predetermined error exactly once. +#[derive(Clone, Debug)] +pub struct OnceErr(PhantomData, Option); + +/// Creates an iterator that fails with a predetermined error exactly once. +pub fn once_err(value: E) -> OnceErr { + OnceErr(PhantomData, Some(value)) +} + +impl FallibleIterator for OnceErr { + type Item = T; + type Error = E; + + #[inline] + fn next(&mut self) -> Result, Self::Error> { + match self.1.take() { + Some(value) => Err(value), + None => Ok(None), + } + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + (0, Some(0)) + } +} + +/// An iterator that endlessly repeats a single element. +#[derive(Clone, Debug)] +pub struct Repeat(T, PhantomData); + +/// Creates an iterator that endlessly repeats a single element. +pub fn repeat(value: T) -> Repeat { + Repeat(value, PhantomData) +} + +impl FallibleIterator for Repeat { + type Item = T; + type Error = E; + + #[inline] + fn next(&mut self) -> Result, Self::Error> { + Ok(Some(self.0.clone())) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + (usize::max_value(), None) + } +} + +/// An iterator that endlessly repeats a single error. +#[derive(Clone, Debug)] +pub struct RepeatErr(PhantomData, E); + +/// Creates an iterator that endlessly repeats a single error. +pub fn repeat_err(value: E) -> RepeatErr { + RepeatErr(PhantomData, value) +} + +impl FallibleIterator for RepeatErr { + type Item = T; + type Error = E; + + #[inline] + fn next(&mut self) -> Result, Self::Error> { + Err(self.1.clone()) + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + (0, Some(0)) + } +} diff --git a/vendor/fallible-iterator/src/test.rs b/vendor/fallible-iterator/src/test.rs index f7627c4a3..218c6929f 100644 --- a/vendor/fallible-iterator/src/test.rs +++ b/vendor/fallible-iterator/src/test.rs @@ -1,7 +1,7 @@ -use core::iter; -use core::ops::Range; +use alloc::{vec, vec::Vec}; +use core::{iter, ops::Range}; -use super::{convert, FallibleIterator, Vec}; +use super::{convert, FallibleIterator, IntoFallible}; #[test] fn all() { @@ -190,6 +190,8 @@ fn last() { #[test] fn map() { let it = convert(vec![0, 1, 2, 3, 4].into_iter().map(Ok::)).map(|n| Ok(n * 2)); + fn assert_debug(_: &impl core::fmt::Debug) {} + assert_debug(&it); assert_eq!(it.clone().collect::>().unwrap(), [0, 2, 4, 6, 8]); assert_eq!(it.rev().collect::>().unwrap(), [8, 6, 4, 2, 0]); @@ -241,8 +243,7 @@ fn max_by_key() { // Exercise failure both on the first item, and later. assert_eq!(it.clone().max_by_key(|&i| Err::(i)), Err(0)); assert_eq!( - it.clone() - .max_by_key(|&i| if i > 0 { Err(i) } else { Ok(-i) }), + it.max_by_key(|&i| if i > 0 { Err(i) } else { Ok(-i) }), Err(3) ); } @@ -266,8 +267,7 @@ fn min_by_key() { // Exercise failure both on the first item, and later. assert_eq!(it.clone().min_by_key(|&i| Err::(i)), Err(0)); assert_eq!( - it.clone() - .min_by_key(|&i| if i > 0 { Err(i) } else { Ok(-i) }), + it.min_by_key(|&i| if i > 0 { Err(i) } else { Ok(-i) }), Err(3) ); } @@ -304,15 +304,14 @@ fn position() { assert_eq!(it.position(|n| Ok(n == 3)).unwrap(), Some(0)); assert_eq!(it.position(|n| Ok(n == 5)).unwrap(), None); - let it = convert(vec![1, 2, 3, 4].into_iter().map(Ok::)); + let mut it = convert(vec![1, 2, 3, 4].into_iter().map(Ok::)); assert_eq!( it.clone() .position(|n| if n == 3 { Err(42) } else { Ok(n == 2) }), Ok(Some(1)) ); assert_eq!( - it.clone() - .position(|n| if n == 3 { Err(42) } else { Ok(n == 4) }), + it.position(|n| if n == 3 { Err(42) } else { Ok(n == 4) }), Err(42) ); } @@ -335,7 +334,7 @@ fn skip() { let it = convert(vec![1, 2, 3, 4].into_iter().map(Ok::)); assert_eq!(it.clone().skip(0).collect::>(), Ok(vec![1, 2, 3, 4])); assert_eq!(it.clone().skip(2).collect::>(), Ok(vec![3, 4])); - assert_eq!(it.clone().skip(4).collect::>(), Ok(vec![])); + assert_eq!(it.skip(4).collect::>(), Ok(vec![])); } #[test] @@ -350,7 +349,7 @@ fn skip_while() { Ok(vec![3, 4, 1]) ); assert_eq!( - it.clone().skip_while(|x| Ok(*x < 5)).collect::>(), + it.skip_while(|x| Ok(*x < 5)).collect::>(), Ok(vec![]) ); } @@ -384,7 +383,7 @@ fn take_while() { Ok(vec![0, 1]) ); assert_eq!( - it.clone().take_while(|x| Ok(*x < 4)).collect::>(), + it.take_while(|x| Ok(*x < 4)).collect::>(), Ok(vec![0, 1, 2, 3, 0]) ); } @@ -411,7 +410,10 @@ fn flatten() { #[test] fn inspect() { let mut buf = vec![]; - let it = convert(vec![0, 1, 2, 3].into_iter().map(Ok::)).inspect(|v| Ok(buf.push(*v))); + let it = convert(vec![0, 1, 2, 3].into_iter().map(Ok::)).inspect(|&v| { + buf.push(v); + Ok(()) + }); it.count().unwrap(); assert_eq!(buf, vec![0, 1, 2, 3]); } @@ -451,5 +453,25 @@ fn unzip() { #[test] fn cycle() { let it = convert(vec![0, 1, 2, 3].into_iter().map(Ok::)).cycle(); - assert_eq!(it.take(6).clone().collect::>(), Ok(vec![0, 1, 2, 3, 0, 1])); + assert_eq!(it.take(6).collect::>(), Ok(vec![0, 1, 2, 3, 0, 1])); +} + +#[test] +fn unwrap() { + let it = convert(vec![0, 1, 2, 3].into_iter().map(Ok::)).unwrap(); + assert_eq!(it.collect::>(), vec![0, 1, 2, 3]); +} + +#[test] +#[should_panic] +fn unwrap_panic() { + let _ = convert(vec![Ok(0), Err(())].into_iter()) + .unwrap() + .collect::>(); +} + +#[test] +fn wrap_std_iter_into_fallible() { + let it = IntoFallible::from(vec![0, 1, 2, 3].into_iter()); + assert_eq!(it.collect::>().unwrap(), vec![0, 1, 2, 3]); } -- cgit v1.2.3