about summary refs log tree commit diff
path: root/library/core/tests/iter/adapters
AgeCommit message (Collapse)AuthorLines
2025-01-26Put all coretests in a separate cratebjorn3-3468/+0
2024-12-24chore: fix typosoliveredget-1/+1
2024-09-22Reformat using the new identifier sorting from rustfmtMichael Goulet-5/+6
2023-01-16Implement DoubleEnded and ExactSize for Take<Repeat> and Take<RepeatWith>Michal Nazarewicz-0/+90
Repeat iterator always returns the same element and behaves the same way backwards and forwards. Take iterator can trivially implement backwards iteration over Repeat inner iterator by simply doing forwards iteration. DoubleEndedIterator is not currently implemented for Take<Repeat<T>> because Repeat doesn’t implement ExactSizeIterator which is a required bound on DEI implementation for Take. Similarly, since Repeat is an infinite iterator which never stops, Take can trivially know how many elements it’s going to return. This allows implementing ExactSizeIterator on Take<Repeat<T>>. While at it, observe that ExactSizeIterator can also be implemented for Take<RepeatWhile<F>> so add that implementation too. Since in contrast to Repeat, RepeatWhile doesn’t guarante to always return the same value, DoubleEndedIterator isn’t implemented. Those changes render core::iter::repeat_n somewhat redundant. Issue: https://github.com/rust-lang/rust/issues/104434 Issue: https://github.com/rust-lang/rust/issues/104729
2024-07-29Reformat `use` declarations.Nicholas Nethercote-8/+13
The previous commit updated `rustfmt.toml` appropriately. This commit is the outcome of running `x fmt --all` with the new formatting options.
2024-06-25regression test for leaks in the the Filter::next_chunk implementationThe 8472-0/+13
previously next_chunk would forget items rejected by the filter
2024-06-20Add blank lines after module-level `//!` comments.Nicholas Nethercote-0/+1
Most modules have such a blank line, but some don't. Inserting the blank line makes it clearer that the `//!` comments are describing the entire module, rather than the `use` declaration(s) that immediately follows.
2024-06-04Add function `core::iter::chain`Ross MacArthur-0/+8
The addition of `core::iter::zip` (#82917) set a precedent for adding plain functions for iterator adaptors. Adding `chain` makes it a little easier to `chain` two iterators. ``` for (x, y) in chain(xs, ys) {} // vs. for (x, y) in xs.into_iter().chain(ys) {} ```
2024-03-20step cfgsMark Rousskov-1/+1
2024-02-25Auto merge of #120393 - Urgau:rfc3373-non-local-defs, r=WaffleLapkinbors-0/+1
Implement RFC 3373: Avoid non-local definitions in functions This PR implements [RFC 3373: Avoid non-local definitions in functions](https://github.com/rust-lang/rust/issues/120363).
2024-02-17Allow newly added non_local_definitions in stdUrgau-0/+1
2024-02-16Specialize flattening iterators with only one inner itemJosh Stone-0/+66
For iterators like `Once` and `option::IntoIter` that only ever have a single item at most, the front and back iterator states in `FlatMap` and `Flatten` are a waste, as they're always consumed already. We can use specialization for these types to simplify the iterator methods. It's a somewhat common pattern to use `flatten()` for options and results, even recommended by [multiple][1] [clippy][2] [lints][3]. The implementation is more efficient with `filter_map`, as mentioned in [clippy#9377], but this new specialization should close some of that gap for existing code that flattens. [1]: https://rust-lang.github.io/rust-clippy/master/#filter_map_identity [2]: https://rust-lang.github.io/rust-clippy/master/#option_filter_map [3]: https://rust-lang.github.io/rust-clippy/master/#result_filter_map [clippy#9377]: https://github.com/rust-lang/rust-clippy/issues/9377
2024-02-15Replace `NonZero::<_>::new` with `NonZero::new`.Markus Reiter-28/+19
2024-02-15Use generic `NonZero` internally.Markus Reiter-24/+27
2024-01-21Auto merge of #85528 - the8472:iter-markers, r=dtolnaybors-2/+5
Implement iterator specialization traits on more adapters This adds * `TrustedLen` to `Skip` and `StepBy` * `TrustedRandomAccess` to `Skip` * `InPlaceIterable` and `SourceIter` to `Copied` and `Cloned` The first two might improve performance in the compiler itself since `skip` is used in several places. Constellations that would exercise the last point are probably rare since it would require an owning iterator that has references as Items somewhere in its iterator pipeline. Improvements for `Skip`: ``` # old test iter::bench_skip_trusted_random_access ... bench: 8,335 ns/iter (+/- 90) # new test iter::bench_skip_trusted_random_access ... bench: 2,753 ns/iter (+/- 27) ```
2024-01-11apply fmtklensy-19/+27
2024-01-10implement TrustedLen for StepByThe8472-2/+5
2023-12-10remove redundant importssurechen-2/+1
detects redundant imports that can be eliminated. for #117772 : In order to facilitate review and modification, split the checking code and removing redundant imports code into two PR.
2023-10-06optimize zipping over array iteratorsThe 8472-1/+5
2023-08-11Add Iterator::map_windowsFrank King-0/+284
This is inherited from the old PR. This method returns an iterator over mapped windows of the starting iterator. Adding the more straight-forward `Iterator::windows` is not easily possible right now as the items are stored in the iterator type, meaning the `next` call would return references to `self`. This is not allowed by the current `Iterator` trait design. This might change once GATs have landed. The idea has been brought up by @m-ou-se here: https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Iterator.3A.3A.7Bpairwise.2C.20windows.7D/near/224587771 Co-authored-by: Lukas Kalbertodt <lukas.kalbertodt@gmail.com>
2023-06-23Specialize StepBy<Range<{integer}>>The 8472-0/+55
For ranges < usize we determine the number of items StepBy would yield and then store that in the range.end instead of the actual end. This significantly simplifies calculation of the loop induction variable especially in cases where StepBy::step (an usize) could overflow the Range's item type
2023-03-27replace advance_by returning usize with Result<(), NonZeroUsize>The 8472-59/+78
2023-03-27Change advance(_back)_by to return `usize` instead of `Result<(), usize>`The 8472-60/+64
A successful advance is now signalled by returning `0` and other values now represent the remaining number of steps that couldn't be advanced as opposed to the amount of steps that have been advanced during a partial advance_by. This simplifies adapters a bit, replacing some `match`/`if` with arithmetic. Whether this is beneficial overall depends on whether `advance_by` is mostly used as a building-block for other iterator methods and adapters or whether we also see uses by users where `Result` might be more useful.
2023-03-03Match unmatched backticks in library/est31-1/+1
2022-11-24Tune RepeatWith::try_fold and Take::for_each and Vec::extend_trustedScott McMurray-0/+20
2022-11-07simplification: do not process the ArrayChunks remainder in fold()The 8472-1/+2
2022-08-24Rollup merge of #100220 - scottmcm:fix-by-ref-sized, r=joshtriplettMatthias Krüger-0/+21
Properly forward `ByRefSized::fold` to the inner iterator cc ``@timvermeulen,`` who noticed this mistake in https://github.com/rust-lang/rust/pull/100214#issuecomment-1207317625
2022-08-19Auto merge of #99541 - timvermeulen:flatten_cleanup, r=the8472bors-0/+42
Refactor iteration logic in the `Flatten` and `FlatMap` iterators The `Flatten` and `FlatMap` iterators both delegate to `FlattenCompat`: ```rust struct FlattenCompat<I, U> { iter: Fuse<I>, frontiter: Option<U>, backiter: Option<U>, } ``` Every individual iterator method that `FlattenCompat` implements needs to carefully manage this state, checking whether the `frontiter` and `backiter` are present, and storing the current iterator appropriately if iteration is aborted. This has led to methods such as `next`, `advance_by`, and `try_fold` all having similar code for managing the iterator's state. I have extracted this common logic of iterating the inner iterators with the option to exit early into a `iter_try_fold` method: ```rust impl<I, U> FlattenCompat<I, U> where I: Iterator<Item: IntoIterator<IntoIter = U>>, { fn iter_try_fold<Acc, Fold, R>(&mut self, acc: Acc, fold: Fold) -> R where Fold: FnMut(Acc, &mut U) -> R, R: Try<Output = Acc>, { ... } } ``` It passes each of the inner iterators to the given function as long as it keep succeeding. It takes care of managing `FlattenCompat`'s state, so that the actual `Iterator` methods don't need to. The resulting code that makes use of this abstraction is much more straightforward: ```rust fn next(&mut self) -> Option<U::Item> { #[inline] fn next<U: Iterator>((): (), iter: &mut U) -> ControlFlow<U::Item> { match iter.next() { None => ControlFlow::CONTINUE, Some(x) => ControlFlow::Break(x), } } self.iter_try_fold((), next).break_value() } ``` Note that despite being implemented in terms of `iter_try_fold`, `next` is still able to benefit from `U`'s `next` method. It therefore does not take the performance hit that implementing `next` directly in terms of `Self::try_fold` causes (in some benchmarks). This PR also adds `iter_try_rfold` which captures the shared logic of `try_rfold` and `advance_back_by`, as well as `iter_fold` and `iter_rfold` for folding without early exits (used by `fold`, `rfold`, `count`, and `last`). Benchmark results: ``` before after bench_flat_map_sum 423,255 ns/iter 414,338 ns/iter bench_flat_map_ref_sum 1,942,139 ns/iter 2,216,643 ns/iter bench_flat_map_chain_sum 1,616,840 ns/iter 1,246,445 ns/iter bench_flat_map_chain_ref_sum 4,348,110 ns/iter 3,574,775 ns/iter bench_flat_map_chain_option_sum 780,037 ns/iter 780,679 ns/iter bench_flat_map_chain_option_ref_sum 2,056,458 ns/iter 834,932 ns/iter ``` I added the last two benchmarks specifically to demonstrate an extreme case where `FlatMap::next` can benefit from custom internal iteration of the outer iterator, so take it with a grain of salt. We should probably do a perf run to see if the changes to `next` are worth it in practice.
2022-08-14Properly forward `ByRefSized::fold` to the inner iteratorScott McMurray-0/+21
2022-08-14fix(iter::skip): Optimize `next` and `nth` implementations of `Skip`austinabell-0/+31
2022-08-05Move `fold` logic to `iter_fold` method and reuse it in `count` and `last`Tim Vermeulen-0/+42
2022-08-01Remove incorrect impl `TrustedLen` for `ArrayChunks`Maybe Waffle-1/+1
As explained in the review of the previous attempt to add `ArrayChunks`, adapters that shrink the length can't implement `TrustedLen`.
2022-08-01Use `array::IntoIter` for the `ArrayChunks` remainderRoss MacArthur-24/+5
2022-08-01Add `Iterator::array_chunks()`Ross MacArthur-0/+221
2022-07-18Add note to test about `Unfuse`Tim Vermeulen-0/+3
2022-07-18Fix `Skip::next` for non-fused inner iteratorsTim Vermeulen-0/+8
2022-03-09Remove unexpected #[cfg(target_pointer_width = "8")] in testsLoïc BRANSTETT-2/+0
2022-01-09eplace usages of vec![].into_iter with [].into_iterLucas Kent-5/+5
2021-12-04Use IntoIterator for array impl everywhere.Mara Bos-6/+5
2021-11-19Fix Iterator::advance_by contract inconsistencyThe8472-0/+44
The `advance_by(n)` docs state that in the error case `Err(k)` that k is always less than n. It also states that `advance_by(0)` may return `Err(0)` to indicate an exhausted iterator. These statements are inconsistent. Since only one implementation (Skip) actually made use of that I changed it to return Ok(()) in that case too. While adding some tests I also found a bug in `Take::advance_back_by`.
2021-09-30implement advance_(back_)_by on more iteratorsThe8472-0/+17
2021-07-30Consistent spelling of "adapter" in the standard libraryFrank Steffahn-1/+1
Change all occurrences of "(A|a)daptor" to "(A|a)dapter".
2021-07-16implement ConstSizeIntoIterator for &[T;N] in addition to [T;N]The8472-0/+16
Due to #20400 the corresponding TrustedLen impls need a helper trait instead of directly adding `Item = &[T;N]` bounds. Since TrustedLen is a public trait this in turn means the helper trait needs to be public. Since it's just a workaround for a compiler deficit it's marked hidden, unstable and unsafe.
2021-07-15implement TrustedLen for Flatten/FlatMap if the U: IntoIterator == [T; N]The8472-0/+24
This only works if arrays are passed directly instead of array iterators because we need to be sure that they have not been advanced before Flatten does its size calculation.
2021-06-20disable test on platforms that don't support unwindingThe8472-2/+4
2021-06-19fix panic-safety in specialized Zip::next_backThe8472-0/+25
This was unsound since a panic in a.next_back() would result in the length not being updated which would then lead to the same element being revisited in the side-effect preserving code.
2021-06-02Update expressions where we can use array's IntoIterator implementationMuhammad Mominul Huque-3/+1
2021-03-14Remove Option::{unwrap_none, expect_none}.Mara Bos-6/+6
2021-03-05Add relevant testGiacomo Stevanato-0/+23
2021-03-05Rollup merge of #82289 - SkiFire13:fix-issue-82282, r=m-ou-seMara-0/+20
Fix underflow in specialized ZipImpl::size_hint Fixes #82282