Skip to content

Commit ced0798

Browse files
authored
Rollup merge of rust-lang#149270 - jdonszelmann:exact-length-collection, r=Mark-Simulacrum
implement `Iterator::{exactly_one, collect_array}` As per rust-lang#149266
2 parents bbdb7bd + f201752 commit ced0798

File tree

11 files changed

+81
-17
lines changed

11 files changed

+81
-17
lines changed

compiler/rustc_codegen_ssa/src/back/metadata.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,8 @@ impl MetadataLoader for DefaultMetadataLoader {
8686
format!("failed to parse aix dylib '{}': {}", path.display(), e)
8787
})?;
8888

89-
match archive.members().exactly_one() {
89+
// FIXME: rewrite in terms of `#![feature(exact_length_collection)]`. See: #149266
90+
match Itertools::exactly_one(archive.members()) {
9091
Ok(lib) => {
9192
let lib = lib.map_err(|e| {
9293
format!("failed to parse aix dylib '{}': {}", path.display(), e)

library/core/src/iter/traits/iterator.rs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4034,6 +4034,62 @@ pub trait Iterator {
40344034
{
40354035
unreachable!("Always specialized");
40364036
}
4037+
4038+
/// Checks if the iterator contains *exactly* one element.
4039+
/// If so, returns this one element.
4040+
///
4041+
/// See also [`collect_array`](Iterator::collect_array) for lengths other than `1`.
4042+
///
4043+
/// # Examples
4044+
///
4045+
/// ```
4046+
/// #![feature(exact_length_collection)]
4047+
///
4048+
/// assert_eq!([1].into_iter().exactly_one(), Some(1));
4049+
/// assert_eq!([].into_iter().exactly_one(), None::<()>);
4050+
///
4051+
/// // There is exactly one even integer in the array:
4052+
/// assert_eq!([1, 2, 3].into_iter().filter(|x| x % 2 == 0).exactly_one(), Some(2));
4053+
/// // But there are two odds, which is too many:
4054+
/// assert_eq!([1, 2, 3].into_iter().filter(|x| x % 2 == 1).exactly_one(), None);
4055+
/// ```
4056+
#[inline]
4057+
#[unstable(feature = "exact_length_collection", issue = "149266")]
4058+
fn exactly_one(self) -> Option<Self::Item>
4059+
where
4060+
Self: Sized,
4061+
{
4062+
self.collect_array::<1>().map(|[i]| i)
4063+
}
4064+
4065+
/// Checks if an iterator has *exactly* `N` elements.
4066+
/// If so, returns those `N` elements in an array.
4067+
///
4068+
/// See also [`exactly_one`](Iterator::exactly_one) when expecting a single element.
4069+
///
4070+
/// # Examples
4071+
///
4072+
/// ```
4073+
/// #![feature(exact_length_collection)]
4074+
///
4075+
/// assert_eq!([1, 2, 3, 4].into_iter().collect_array(), Some([1, 2, 3, 4]));
4076+
/// assert_eq!([1, 2].into_iter().chain([3, 4]).collect_array(), Some([1, 2, 3, 4]));
4077+
///
4078+
/// // Iterator contains too few elements:
4079+
/// assert_eq!([1, 2].into_iter().collect_array::<4>(), None);
4080+
/// // Iterator contains too many elements:
4081+
/// assert_eq!([1, 2, 3, 4, 5].into_iter().collect_array::<4>(), None);
4082+
/// // Taking 4 makes it work again:
4083+
/// assert_eq!([1, 2, 3, 4, 5].into_iter().take(4).collect_array(), Some([1, 2, 3, 4]));
4084+
/// ```
4085+
#[inline]
4086+
#[unstable(feature = "exact_length_collection", issue = "149266")]
4087+
fn collect_array<const N: usize>(mut self) -> Option<[Self::Item; N]>
4088+
where
4089+
Self: Sized,
4090+
{
4091+
self.next_chunk().ok().filter(|_| self.next().is_none())
4092+
}
40374093
}
40384094

40394095
trait SpecIterEq<B: Iterator>: Iterator {

src/librustdoc/html/format.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,7 +1126,8 @@ pub(crate) fn print_impl(
11261126
}
11271127
if impl_.kind.is_fake_variadic()
11281128
&& let Some(generics) = ty.generics()
1129-
&& let Ok(inner_type) = generics.exactly_one()
1129+
// FIXME: rewrite in terms of `#![feature(exact_length_collection)]`. See: #149266
1130+
&& let Ok(inner_type) = Itertools::exactly_one(generics)
11301131
{
11311132
let last = ty.last();
11321133
if f.alternate() {
@@ -1206,7 +1207,8 @@ impl clean::Impl {
12061207
}
12071208
} else if let clean::Type::Path { path } = type_
12081209
&& let Some(generics) = path.generics()
1209-
&& let Ok(ty) = generics.exactly_one()
1210+
// FIXME: rewrite in terms of `#![feature(exact_length_collection)]`. See: #149266
1211+
&& let Ok(ty) = Itertools::exactly_one(generics)
12101212
&& self.kind.is_fake_variadic()
12111213
{
12121214
print_anchor(path.def_id(), path.last(), cx).fmt(f)?;

src/tools/clippy/clippy_lints/src/manual_non_exhaustive.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,8 @@ impl<'tcx> LateLintPass<'tcx> for ManualNonExhaustive {
9292
(matches!(v.data, VariantData::Unit(_, _)) && is_doc_hidden(cx.tcx.hir_attrs(v.hir_id)))
9393
.then_some((v.def_id, v.span))
9494
});
95-
if let Ok((id, span)) = iter.exactly_one()
95+
// FIXME: rewrite in terms of `#![feature(exact_length_collection)]`. See: #149266
96+
if let Ok((id, span)) = Itertools::exactly_one(iter)
9697
&& !find_attr!(cx.tcx.hir_attrs(item.hir_id()), AttributeKind::NonExhaustive(..))
9798
{
9899
self.potential_enums.push((item.owner_id.def_id, id, item.span, span));
@@ -104,7 +105,8 @@ impl<'tcx> LateLintPass<'tcx> for ManualNonExhaustive {
104105
.iter()
105106
.filter(|field| !cx.effective_visibilities.is_exported(field.def_id));
106107
if fields.len() > 1
107-
&& let Ok(field) = private_fields.exactly_one()
108+
// FIXME: rewrite in terms of `#![feature(exact_length_collection)]`. See: #149266
109+
&& let Ok(field) = Itertools::exactly_one(private_fields)
108110
&& let TyKind::Tup([]) = field.ty.kind
109111
{
110112
span_lint_and_then(

src/tools/rust-analyzer/crates/hir-expand/src/builtin/fn_macro.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -786,7 +786,8 @@ fn parse_string(tt: &tt::TopSubtree) -> Result<(Symbol, Span), ExpandError> {
786786
&& let DelimiterKind::Parenthesis | DelimiterKind::Invisible = sub.delimiter.kind
787787
{
788788
tt =
789-
tt_iter.exactly_one().map_err(|_| sub.delimiter.open.cover(sub.delimiter.close))?;
789+
// FIXME: rewrite in terms of `#![feature(exact_length_collection)]`. See: #149266
790+
Itertools::exactly_one(tt_iter).map_err(|_| sub.delimiter.open.cover(sub.delimiter.close))?;
790791
}
791792

792793
match tt {

src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_bool_then.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,8 @@ pub(crate) fn convert_bool_then_to_if(acc: &mut Assists, ctx: &AssistContext<'_>
163163
let name_ref = ctx.find_node_at_offset::<ast::NameRef>()?;
164164
let mcall = name_ref.syntax().parent().and_then(ast::MethodCallExpr::cast)?;
165165
let receiver = mcall.receiver()?;
166-
let closure_body = mcall.arg_list()?.args().exactly_one().ok()?;
166+
// FIXME: rewrite in terms of `#![feature(exact_length_collection)]`. See: #149266
167+
let closure_body = Itertools::exactly_one(mcall.arg_list()?.args()).ok()?;
167168
let closure_body = match closure_body {
168169
ast::Expr::ClosureExpr(expr) => expr.body()?,
169170
_ => return None,

src/tools/rust-analyzer/crates/ide-assists/src/handlers/convert_range_for_to_while.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ fn extract_range(iterable: &ast::Expr) -> Option<(ast::Expr, Option<ast::Expr>,
113113
(range.start()?, range.end(), make::expr_literal("1").into(), inclusive)
114114
}
115115
ast::Expr::MethodCallExpr(call) if call.name_ref()?.text() == "step_by" => {
116-
let [step] = call.arg_list()?.args().collect_array()?;
116+
let [step] = Itertools::collect_array(call.arg_list()?.args())?;
117117
let (start, end, _, inclusive) = extract_range(&call.receiver()?)?;
118118
(start, end, step, inclusive)
119119
}

src/tools/rust-analyzer/crates/ide-completion/src/tests/raw_identifiers.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,8 @@ fn check(#[rust_analyzer::rust_fixture] ra_fixture: &str, expect: Expect) {
88
let completions = completion_list_with_config_raw(TEST_CONFIG, ra_fixture, true, None);
99
let (db, position) = position(ra_fixture);
1010
let mut actual = db.file_text(position.file_id).text(&db).to_string();
11-
completions
12-
.into_iter()
13-
.exactly_one()
11+
// FIXME: rewrite in terms of `#![feature(exact_length_collection)]`. See: #149266
12+
Itertools::exactly_one(completions.into_iter())
1413
.expect("more than one completion")
1514
.text_edit
1615
.apply(&mut actual);

src/tools/rust-analyzer/crates/rust-analyzer/tests/slow-tests/support.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,8 @@ impl Project<'_> {
113113
let mut buf = Vec::new();
114114
flags::Lsif::run(
115115
flags::Lsif {
116-
path: tmp_dir_path.join(self.roots.iter().exactly_one().unwrap()).into(),
116+
// FIXME: rewrite in terms of `#![feature(exact_length_collection)]`. See: #149266
117+
path: tmp_dir_path.join(Itertools::exactly_one(self.roots.iter()).unwrap()).into(),
117118
exclude_vendored_libraries: false,
118119
},
119120
&mut buf,

tests/ui/const-generics/type-dependent/issue-71805.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::mem::MaybeUninit;
44
trait CollectSlice<'a>: Iterator {
55
fn inner_array<const N: usize>(&mut self) -> [Self::Item; N];
66

7-
fn collect_array<const N: usize>(&mut self) -> [Self::Item; N] {
7+
fn custom_collect_array<const N: usize>(&mut self) -> [Self::Item; N] {
88
let result = self.inner_array();
99
assert!(self.next().is_none());
1010
result
@@ -34,5 +34,5 @@ where
3434

3535
fn main() {
3636
let mut foos = [0u64; 9].iter().cloned();
37-
let _bar: [u64; 9] = foos.collect_array::<9_usize>();
37+
let _bar: [u64; 9] = foos.custom_collect_array::<9_usize>();
3838
}

0 commit comments

Comments
 (0)