Skip to content

Conversation

@kennytm
Copy link
Member

@kennytm kennytm commented Jul 10, 2025

Implementation for #143702

@kennytm kennytm added the T-libs-api Relevant to the library API team, which will review and decide on the PR/issue. label Jul 10, 2025
@rustbot
Copy link
Collaborator

rustbot commented Jul 10, 2025

r? @scottmcm

rustbot has assigned @scottmcm.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

@rustbot rustbot added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Jul 10, 2025
@rust-log-analyzer

This comment has been minimized.

@kennytm kennytm force-pushed the peekable_next_if_map branch from a4962ee to 2261154 Compare July 10, 2025 12:45
@kennytm kennytm added T-libs Relevant to the library team, which will review and decide on the PR/issue. and removed T-libs-api Relevant to the library API team, which will review and decide on the PR/issue. labels Jul 23, 2025
@kennytm
Copy link
Member Author

kennytm commented Jul 23, 2025

r? libs

@rustbot rustbot assigned thomcc and unassigned scottmcm Jul 23, 2025
@tgross35
Copy link
Contributor

tgross35 commented Sep 3, 2025

Thom is off rotation,
r? libs

@rustbot rustbot assigned jhpratt and unassigned thomcc Sep 3, 2025
@jhpratt
Copy link
Member

jhpratt commented Sep 3, 2025

@bors r+ rollup

@bors
Copy link
Collaborator

bors commented Sep 3, 2025

📌 Commit 2261154 has been approved by jhpratt

It is now in the queue for this repository.

@bors bors added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Sep 3, 2025
tgross35 added a commit to tgross35/rust that referenced this pull request Sep 3, 2025
…pratt

core: add Peekable::next_if_map

Implementation for rust-lang#143702
bors added a commit that referenced this pull request Sep 3, 2025
Rollup of 9 pull requests

Successful merges:

 - #143725 (core: add Peekable::next_if_map)
 - #145209 (Stabilize `path_add_extension`)
 - #145750 (raw_vec.rs: Remove superfluous fn alloc_guard)
 - #145962 (Ensure we emit an allocator shim when only some crate types need one)
 - #145963 (Add LSX accelerated implementation for source file analysis)
 - #146054 (add `#[must_use]` to `array::repeat`)
 - #146090 (Derive `PartialEq` for `InvisibleOrigin`)
 - #146120 (Correct typo in `rustc_errors` comment)
 - #146131 (rustdoc-search: add test case for indexing every item type)

r? `@ghost`
`@rustbot` modify labels: rollup
jhpratt added a commit to jhpratt/rust that referenced this pull request Sep 3, 2025
…pratt

core: add Peekable::next_if_map

Implementation for rust-lang#143702
bors added a commit that referenced this pull request Sep 3, 2025
Rollup of 15 pull requests

Successful merges:

 - #143725 (core: add Peekable::next_if_map)
 - #145209 (Stabilize `path_add_extension`)
 - #145750 (raw_vec.rs: Remove superfluous fn alloc_guard)
 - #145962 (Ensure we emit an allocator shim when only some crate types need one)
 - #145963 (Add LSX accelerated implementation for source file analysis)
 - #146054 (add `#[must_use]` to `array::repeat`)
 - #146090 (Derive `PartialEq` for `InvisibleOrigin`)
 - #146120 (Correct typo in `rustc_errors` comment)
 - #146127 (Rename `ToolRustc` to `ToolRustcPrivate`)
 - #146131 (rustdoc-search: add test case for indexing every item type)
 - #146133 (Revert "Make `lto` and `linker-plugin-lto` work the same for `compiler_builtins`)
 - #146134 (llvm: nvptx: Layout update to match LLVM)
 - #146136 (docs(std): add missing closing code block fences in doc comments)
 - #146137 (Disallow frontmatter in `--cfg` and `--check-cfg` arguments)
 - #146140 (compiletest: cygwin follows windows in using PATH for dynamic libraries)

r? `@ghost`
`@rustbot` modify labels: rollup
Zalathar added a commit to Zalathar/rust that referenced this pull request Sep 3, 2025
…pratt

core: add Peekable::next_if_map

Implementation for rust-lang#143702
bors added a commit that referenced this pull request Sep 3, 2025
Rollup of 16 pull requests

Successful merges:

 - #143725 (core: add Peekable::next_if_map)
 - #145209 (Stabilize `path_add_extension`)
 - #145342 (fix drop scope for `super let` bindings within `if let`)
 - #145750 (raw_vec.rs: Remove superfluous fn alloc_guard)
 - #145962 (Ensure we emit an allocator shim when only some crate types need one)
 - #145963 (Add LSX accelerated implementation for source file analysis)
 - #146054 (add `#[must_use]` to `array::repeat`)
 - #146090 (Derive `PartialEq` for `InvisibleOrigin`)
 - #146120 (Correct typo in `rustc_errors` comment)
 - #146127 (Rename `ToolRustc` to `ToolRustcPrivate`)
 - #146133 (Revert "Make `lto` and `linker-plugin-lto` work the same for `compiler_builtins`)
 - #146134 (llvm: nvptx: Layout update to match LLVM)
 - #146136 (docs(std): add missing closing code block fences in doc comments)
 - #146137 (Disallow frontmatter in `--cfg` and `--check-cfg` arguments)
 - #146140 (compiletest: cygwin follows windows in using PATH for dynamic libraries)
 - #146156 (miri subtree update)

r? `@ghost`
`@rustbot` modify labels: rollup
Zalathar added a commit to Zalathar/rust that referenced this pull request Sep 4, 2025
…pratt

core: add Peekable::next_if_map

Implementation for rust-lang#143702
bors added a commit that referenced this pull request Sep 4, 2025
Rollup of 24 pull requests

Successful merges:

 - #140459 (Add `read_buf` equivalents for positioned reads)
 - #143725 (core: add Peekable::next_if_map)
 - #145209 (Stabilize `path_add_extension`)
 - #145342 (fix drop scope for `super let` bindings within `if let`)
 - #145750 (raw_vec.rs: Remove superfluous fn alloc_guard)
 - #145827 (On unused binding or binding not present in all patterns, suggest potential typo of unit struct/variant or const)
 - #145932 (Allow `inline(always)` with a target feature behind a unstable feature `target_feature_inline_always`.)
 - #145962 (Ensure we emit an allocator shim when only some crate types need one)
 - #145963 (Add LSX accelerated implementation for source file analysis)
 - #146054 (add `#[must_use]` to `array::repeat`)
 - #146090 (Derive `PartialEq` for `InvisibleOrigin`)
 - #146112 (don't uppercase error messages)
 - #146120 (Correct typo in `rustc_errors` comment)
 - #146124 (Test `rustc-dev` in `distcheck`)
 - #146127 (Rename `ToolRustc` to `ToolRustcPrivate`)
 - #146131 (rustdoc-search: add test case for indexing every item type)
 - #146134 (llvm: nvptx: Layout update to match LLVM)
 - #146136 (docs(std): add missing closing code block fences in doc comments)
 - #146137 (Disallow frontmatter in `--cfg` and `--check-cfg` arguments)
 - #146140 (compiletest: cygwin follows windows in using PATH for dynamic libraries)
 - #146150 (fix(rustdoc): match rustc `--emit` precedence )
 - #146155 (Make bootstrap self test parallel)
 - #146161 ([rustdoc] Uncomment code to add scraped rustdoc examples in loaded paths)
 - #146172 (triagebot: configure some pings when certain attributes are used)

r? `@ghost`
`@rustbot` modify labels: rollup
@bors bors merged commit 732802c into rust-lang:master Sep 4, 2025
11 checks passed
@rustbot rustbot added this to the 1.91.0 milestone Sep 4, 2025
rust-timer added a commit that referenced this pull request Sep 4, 2025
Rollup merge of #143725 - kennytm:peekable_next_if_map, r=jhpratt

core: add Peekable::next_if_map

Implementation for #143702
@kennytm kennytm deleted the peekable_next_if_map branch September 4, 2025 10:13
github-actions bot pushed a commit to rust-lang/miri that referenced this pull request Sep 5, 2025
Rollup of 24 pull requests

Successful merges:

 - rust-lang/rust#140459 (Add `read_buf` equivalents for positioned reads)
 - rust-lang/rust#143725 (core: add Peekable::next_if_map)
 - rust-lang/rust#145209 (Stabilize `path_add_extension`)
 - rust-lang/rust#145342 (fix drop scope for `super let` bindings within `if let`)
 - rust-lang/rust#145750 (raw_vec.rs: Remove superfluous fn alloc_guard)
 - rust-lang/rust#145827 (On unused binding or binding not present in all patterns, suggest potential typo of unit struct/variant or const)
 - rust-lang/rust#145932 (Allow `inline(always)` with a target feature behind a unstable feature `target_feature_inline_always`.)
 - rust-lang/rust#145962 (Ensure we emit an allocator shim when only some crate types need one)
 - rust-lang/rust#145963 (Add LSX accelerated implementation for source file analysis)
 - rust-lang/rust#146054 (add `#[must_use]` to `array::repeat`)
 - rust-lang/rust#146090 (Derive `PartialEq` for `InvisibleOrigin`)
 - rust-lang/rust#146112 (don't uppercase error messages)
 - rust-lang/rust#146120 (Correct typo in `rustc_errors` comment)
 - rust-lang/rust#146124 (Test `rustc-dev` in `distcheck`)
 - rust-lang/rust#146127 (Rename `ToolRustc` to `ToolRustcPrivate`)
 - rust-lang/rust#146131 (rustdoc-search: add test case for indexing every item type)
 - rust-lang/rust#146134 (llvm: nvptx: Layout update to match LLVM)
 - rust-lang/rust#146136 (docs(std): add missing closing code block fences in doc comments)
 - rust-lang/rust#146137 (Disallow frontmatter in `--cfg` and `--check-cfg` arguments)
 - rust-lang/rust#146140 (compiletest: cygwin follows windows in using PATH for dynamic libraries)
 - rust-lang/rust#146150 (fix(rustdoc): match rustc `--emit` precedence )
 - rust-lang/rust#146155 (Make bootstrap self test parallel)
 - rust-lang/rust#146161 ([rustdoc] Uncomment code to add scraped rustdoc examples in loaded paths)
 - rust-lang/rust#146172 (triagebot: configure some pings when certain attributes are used)

r? `@ghost`
`@rustbot` modify labels: rollup
github-actions bot pushed a commit to rust-lang/rustc-dev-guide that referenced this pull request Sep 8, 2025
Rollup of 24 pull requests

Successful merges:

 - rust-lang/rust#140459 (Add `read_buf` equivalents for positioned reads)
 - rust-lang/rust#143725 (core: add Peekable::next_if_map)
 - rust-lang/rust#145209 (Stabilize `path_add_extension`)
 - rust-lang/rust#145342 (fix drop scope for `super let` bindings within `if let`)
 - rust-lang/rust#145750 (raw_vec.rs: Remove superfluous fn alloc_guard)
 - rust-lang/rust#145827 (On unused binding or binding not present in all patterns, suggest potential typo of unit struct/variant or const)
 - rust-lang/rust#145932 (Allow `inline(always)` with a target feature behind a unstable feature `target_feature_inline_always`.)
 - rust-lang/rust#145962 (Ensure we emit an allocator shim when only some crate types need one)
 - rust-lang/rust#145963 (Add LSX accelerated implementation for source file analysis)
 - rust-lang/rust#146054 (add `#[must_use]` to `array::repeat`)
 - rust-lang/rust#146090 (Derive `PartialEq` for `InvisibleOrigin`)
 - rust-lang/rust#146112 (don't uppercase error messages)
 - rust-lang/rust#146120 (Correct typo in `rustc_errors` comment)
 - rust-lang/rust#146124 (Test `rustc-dev` in `distcheck`)
 - rust-lang/rust#146127 (Rename `ToolRustc` to `ToolRustcPrivate`)
 - rust-lang/rust#146131 (rustdoc-search: add test case for indexing every item type)
 - rust-lang/rust#146134 (llvm: nvptx: Layout update to match LLVM)
 - rust-lang/rust#146136 (docs(std): add missing closing code block fences in doc comments)
 - rust-lang/rust#146137 (Disallow frontmatter in `--cfg` and `--check-cfg` arguments)
 - rust-lang/rust#146140 (compiletest: cygwin follows windows in using PATH for dynamic libraries)
 - rust-lang/rust#146150 (fix(rustdoc): match rustc `--emit` precedence )
 - rust-lang/rust#146155 (Make bootstrap self test parallel)
 - rust-lang/rust#146161 ([rustdoc] Uncomment code to add scraped rustdoc examples in loaded paths)
 - rust-lang/rust#146172 (triagebot: configure some pings when certain attributes are used)

r? `@ghost`
`@rustbot` modify labels: rollup
github-actions bot pushed a commit to model-checking/verify-rust-std that referenced this pull request Sep 9, 2025
…pratt

core: add Peekable::next_if_map

Implementation for rust-lang#143702
github-actions bot pushed a commit to model-checking/verify-rust-std that referenced this pull request Sep 9, 2025
Rollup of 24 pull requests

Successful merges:

 - rust-lang#140459 (Add `read_buf` equivalents for positioned reads)
 - rust-lang#143725 (core: add Peekable::next_if_map)
 - rust-lang#145209 (Stabilize `path_add_extension`)
 - rust-lang#145342 (fix drop scope for `super let` bindings within `if let`)
 - rust-lang#145750 (raw_vec.rs: Remove superfluous fn alloc_guard)
 - rust-lang#145827 (On unused binding or binding not present in all patterns, suggest potential typo of unit struct/variant or const)
 - rust-lang#145932 (Allow `inline(always)` with a target feature behind a unstable feature `target_feature_inline_always`.)
 - rust-lang#145962 (Ensure we emit an allocator shim when only some crate types need one)
 - rust-lang#145963 (Add LSX accelerated implementation for source file analysis)
 - rust-lang#146054 (add `#[must_use]` to `array::repeat`)
 - rust-lang#146090 (Derive `PartialEq` for `InvisibleOrigin`)
 - rust-lang#146112 (don't uppercase error messages)
 - rust-lang#146120 (Correct typo in `rustc_errors` comment)
 - rust-lang#146124 (Test `rustc-dev` in `distcheck`)
 - rust-lang#146127 (Rename `ToolRustc` to `ToolRustcPrivate`)
 - rust-lang#146131 (rustdoc-search: add test case for indexing every item type)
 - rust-lang#146134 (llvm: nvptx: Layout update to match LLVM)
 - rust-lang#146136 (docs(std): add missing closing code block fences in doc comments)
 - rust-lang#146137 (Disallow frontmatter in `--cfg` and `--check-cfg` arguments)
 - rust-lang#146140 (compiletest: cygwin follows windows in using PATH for dynamic libraries)
 - rust-lang#146150 (fix(rustdoc): match rustc `--emit` precedence )
 - rust-lang#146155 (Make bootstrap self test parallel)
 - rust-lang#146161 ([rustdoc] Uncomment code to add scraped rustdoc examples in loaded paths)
 - rust-lang#146172 (triagebot: configure some pings when certain attributes are used)

r? `@ghost`
`@rustbot` modify labels: rollup
Zalathar added a commit to Zalathar/rust that referenced this pull request Jan 11, 2026
stabilize `Peekable::next_if_map` (`#![feature(peekable_next_if_map)]`)

# Stabilization report

## Summary

`#![feature(peekable_next_if_map)]` is a variation  of `next_if` on peekable iterators that can transform the peeked item. This creates a way to take ownership of the next item in an iterator when some condition holds, but put the item back when the condition doesn't hold. This pattern would otherwise have needed unwraps in many cases.

[Tracking issue](rust-lang#143702)

### What is stabilized

```rust
impl<I: Iterator> Peekable<I> {
    pub fn next_if_map<R>(
        &mut self,
        f: impl FnOnce(I::Item) -> Result<R, I::Item>,
    ) -> Option<R> {
        ..
    }
    pub fn next_if_map_mut<R>(
        &mut self,
        f: impl FnOnce(&mut I::Item) -> Option<R>,
    ) -> Option<R> {
        ..
    }
}
```

Example usage adapted from the ACP:

```rust
let mut it = Peekable::new("123".chars());

while let Some(digit) = it.next_if_map(|c| c.to_digit(10).ok_or(c)) {
    codepoint = codepoint * 10 + digit;
}
```

or with `next_if_map_mut`:

```rust
let mut it = Peekable::new("123".chars());

while let Some(digit) = iter.next_if_map_mut(|c| c.to_digit(10)) {
    line_num = line_num * 10 + digit;
}
```

Note that the major difference here is that `next_if_map_mut` does not get owned items from the iterator, but mutable references. With that api, the closure can return an `Option` which avoids an `ok_or`. This may require cloning or copying the iterator elements, so if that is expensive, the owned version, `next_if_map`, may be preferable.

### Nightly use

At the moment, this feature is barely used in nightly, though I've found multiple good uses for it in my own projects, hence my pushing for stabilization. It makes the kind of patterns used in recursive descent parsing super concise and maybe with its stabilization it will find more use.

### Test coverage

Besides a quite comprehensive doctest, this feature is tested (including panicking in the closure) here:

https://github.com/rust-lang/rust/blob/c880acdd3171dfafdb55be8cd9822a857e99348d/library/coretests/tests/iter/adapters/peekable.rs#L275-L359

## History

- ACP: rust-lang/libs-team#613 accepted with rust-lang/libs-team#613 (comment)
- implementation: rust-lang#143725 with tests, and no issues reported since july.

## Acknowledgments

ACP, implementation and tracking issue for this feature all by @kennytm <3
Zalathar added a commit to Zalathar/rust that referenced this pull request Jan 11, 2026
stabilize `Peekable::next_if_map` (`#![feature(peekable_next_if_map)]`)

# Stabilization report

## Summary

`#![feature(peekable_next_if_map)]` is a variation  of `next_if` on peekable iterators that can transform the peeked item. This creates a way to take ownership of the next item in an iterator when some condition holds, but put the item back when the condition doesn't hold. This pattern would otherwise have needed unwraps in many cases.

[Tracking issue](rust-lang#143702)

### What is stabilized

```rust
impl<I: Iterator> Peekable<I> {
    pub fn next_if_map<R>(
        &mut self,
        f: impl FnOnce(I::Item) -> Result<R, I::Item>,
    ) -> Option<R> {
        ..
    }
    pub fn next_if_map_mut<R>(
        &mut self,
        f: impl FnOnce(&mut I::Item) -> Option<R>,
    ) -> Option<R> {
        ..
    }
}
```

Example usage adapted from the ACP:

```rust
let mut it = Peekable::new("123".chars());

while let Some(digit) = it.next_if_map(|c| c.to_digit(10).ok_or(c)) {
    codepoint = codepoint * 10 + digit;
}
```

or with `next_if_map_mut`:

```rust
let mut it = Peekable::new("123".chars());

while let Some(digit) = iter.next_if_map_mut(|c| c.to_digit(10)) {
    line_num = line_num * 10 + digit;
}
```

Note that the major difference here is that `next_if_map_mut` does not get owned items from the iterator, but mutable references. With that api, the closure can return an `Option` which avoids an `ok_or`. This may require cloning or copying the iterator elements, so if that is expensive, the owned version, `next_if_map`, may be preferable.

### Nightly use

At the moment, this feature is barely used in nightly, though I've found multiple good uses for it in my own projects, hence my pushing for stabilization. It makes the kind of patterns used in recursive descent parsing super concise and maybe with its stabilization it will find more use.

### Test coverage

Besides a quite comprehensive doctest, this feature is tested (including panicking in the closure) here:

https://github.com/rust-lang/rust/blob/c880acdd3171dfafdb55be8cd9822a857e99348d/library/coretests/tests/iter/adapters/peekable.rs#L275-L359

## History

- ACP: rust-lang/libs-team#613 accepted with rust-lang/libs-team#613 (comment)
- implementation: rust-lang#143725 with tests, and no issues reported since july.

## Acknowledgments

ACP, implementation and tracking issue for this feature all by @kennytm <3
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this pull request Jan 11, 2026
stabilize `Peekable::next_if_map` (`#![feature(peekable_next_if_map)]`)

# Stabilization report

## Summary

`#![feature(peekable_next_if_map)]` is a variation  of `next_if` on peekable iterators that can transform the peeked item. This creates a way to take ownership of the next item in an iterator when some condition holds, but put the item back when the condition doesn't hold. This pattern would otherwise have needed unwraps in many cases.

[Tracking issue](rust-lang#143702)

### What is stabilized

```rust
impl<I: Iterator> Peekable<I> {
    pub fn next_if_map<R>(
        &mut self,
        f: impl FnOnce(I::Item) -> Result<R, I::Item>,
    ) -> Option<R> {
        ..
    }
    pub fn next_if_map_mut<R>(
        &mut self,
        f: impl FnOnce(&mut I::Item) -> Option<R>,
    ) -> Option<R> {
        ..
    }
}
```

Example usage adapted from the ACP:

```rust
let mut it = Peekable::new("123".chars());

while let Some(digit) = it.next_if_map(|c| c.to_digit(10).ok_or(c)) {
    codepoint = codepoint * 10 + digit;
}
```

or with `next_if_map_mut`:

```rust
let mut it = Peekable::new("123".chars());

while let Some(digit) = iter.next_if_map_mut(|c| c.to_digit(10)) {
    line_num = line_num * 10 + digit;
}
```

Note that the major difference here is that `next_if_map_mut` does not get owned items from the iterator, but mutable references. With that api, the closure can return an `Option` which avoids an `ok_or`. This may require cloning or copying the iterator elements, so if that is expensive, the owned version, `next_if_map`, may be preferable.

### Nightly use

At the moment, this feature is barely used in nightly, though I've found multiple good uses for it in my own projects, hence my pushing for stabilization. It makes the kind of patterns used in recursive descent parsing super concise and maybe with its stabilization it will find more use.

### Test coverage

Besides a quite comprehensive doctest, this feature is tested (including panicking in the closure) here:

https://github.com/rust-lang/rust/blob/c880acdd3171dfafdb55be8cd9822a857e99348d/library/coretests/tests/iter/adapters/peekable.rs#L275-L359

## History

- ACP: rust-lang/libs-team#613 accepted with rust-lang/libs-team#613 (comment)
- implementation: rust-lang#143725 with tests, and no issues reported since july.

## Acknowledgments

ACP, implementation and tracking issue for this feature all by @kennytm <3
rust-timer added a commit that referenced this pull request Jan 11, 2026
Rollup merge of #148941 - stabilize-map-if, r=jhpratt

stabilize `Peekable::next_if_map` (`#![feature(peekable_next_if_map)]`)

# Stabilization report

## Summary

`#![feature(peekable_next_if_map)]` is a variation  of `next_if` on peekable iterators that can transform the peeked item. This creates a way to take ownership of the next item in an iterator when some condition holds, but put the item back when the condition doesn't hold. This pattern would otherwise have needed unwraps in many cases.

[Tracking issue](#143702)

### What is stabilized

```rust
impl<I: Iterator> Peekable<I> {
    pub fn next_if_map<R>(
        &mut self,
        f: impl FnOnce(I::Item) -> Result<R, I::Item>,
    ) -> Option<R> {
        ..
    }
    pub fn next_if_map_mut<R>(
        &mut self,
        f: impl FnOnce(&mut I::Item) -> Option<R>,
    ) -> Option<R> {
        ..
    }
}
```

Example usage adapted from the ACP:

```rust
let mut it = Peekable::new("123".chars());

while let Some(digit) = it.next_if_map(|c| c.to_digit(10).ok_or(c)) {
    codepoint = codepoint * 10 + digit;
}
```

or with `next_if_map_mut`:

```rust
let mut it = Peekable::new("123".chars());

while let Some(digit) = iter.next_if_map_mut(|c| c.to_digit(10)) {
    line_num = line_num * 10 + digit;
}
```

Note that the major difference here is that `next_if_map_mut` does not get owned items from the iterator, but mutable references. With that api, the closure can return an `Option` which avoids an `ok_or`. This may require cloning or copying the iterator elements, so if that is expensive, the owned version, `next_if_map`, may be preferable.

### Nightly use

At the moment, this feature is barely used in nightly, though I've found multiple good uses for it in my own projects, hence my pushing for stabilization. It makes the kind of patterns used in recursive descent parsing super concise and maybe with its stabilization it will find more use.

### Test coverage

Besides a quite comprehensive doctest, this feature is tested (including panicking in the closure) here:

https://github.com/rust-lang/rust/blob/c880acdd3171dfafdb55be8cd9822a857e99348d/library/coretests/tests/iter/adapters/peekable.rs#L275-L359

## History

- ACP: rust-lang/libs-team#613 accepted with rust-lang/libs-team#613 (comment)
- implementation: #143725 with tests, and no issues reported since july.

## Acknowledgments

ACP, implementation and tracking issue for this feature all by @kennytm <3
github-actions bot pushed a commit to rust-lang/miri that referenced this pull request Jan 12, 2026
stabilize `Peekable::next_if_map` (`#![feature(peekable_next_if_map)]`)

# Stabilization report

## Summary

`#![feature(peekable_next_if_map)]` is a variation  of `next_if` on peekable iterators that can transform the peeked item. This creates a way to take ownership of the next item in an iterator when some condition holds, but put the item back when the condition doesn't hold. This pattern would otherwise have needed unwraps in many cases.

[Tracking issue](rust-lang/rust#143702)

### What is stabilized

```rust
impl<I: Iterator> Peekable<I> {
    pub fn next_if_map<R>(
        &mut self,
        f: impl FnOnce(I::Item) -> Result<R, I::Item>,
    ) -> Option<R> {
        ..
    }
    pub fn next_if_map_mut<R>(
        &mut self,
        f: impl FnOnce(&mut I::Item) -> Option<R>,
    ) -> Option<R> {
        ..
    }
}
```

Example usage adapted from the ACP:

```rust
let mut it = Peekable::new("123".chars());

while let Some(digit) = it.next_if_map(|c| c.to_digit(10).ok_or(c)) {
    codepoint = codepoint * 10 + digit;
}
```

or with `next_if_map_mut`:

```rust
let mut it = Peekable::new("123".chars());

while let Some(digit) = iter.next_if_map_mut(|c| c.to_digit(10)) {
    line_num = line_num * 10 + digit;
}
```

Note that the major difference here is that `next_if_map_mut` does not get owned items from the iterator, but mutable references. With that api, the closure can return an `Option` which avoids an `ok_or`. This may require cloning or copying the iterator elements, so if that is expensive, the owned version, `next_if_map`, may be preferable.

### Nightly use

At the moment, this feature is barely used in nightly, though I've found multiple good uses for it in my own projects, hence my pushing for stabilization. It makes the kind of patterns used in recursive descent parsing super concise and maybe with its stabilization it will find more use.

### Test coverage

Besides a quite comprehensive doctest, this feature is tested (including panicking in the closure) here:

https://github.com/rust-lang/rust/blob/c880acdd3171dfafdb55be8cd9822a857e99348d/library/coretests/tests/iter/adapters/peekable.rs#L275-L359

## History

- ACP: rust-lang/libs-team#613 accepted with rust-lang/libs-team#613 (comment)
- implementation: rust-lang/rust#143725 with tests, and no issues reported since july.

## Acknowledgments

ACP, implementation and tracking issue for this feature all by @kennytm <3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-libs Relevant to the library team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants