diff --git a/compiler/rustc_builtin_macros/src/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs index ae62b5ea2a097..971b68d14757a 100644 --- a/compiler/rustc_builtin_macros/src/asm.rs +++ b/compiler/rustc_builtin_macros/src/asm.rs @@ -368,7 +368,7 @@ fn expand_preparsed_asm( if args.options.contains(ast::InlineAsmOptions::RAW) { template.push(ast::InlineAsmTemplatePiece::String(template_str.to_string().into())); let template_num_lines = 1 + template_str.matches('\n').count(); - line_spans.extend(std::iter::repeat(template_sp).take(template_num_lines)); + line_spans.extend(std::iter::repeat_n(template_sp, template_num_lines)); continue; } @@ -523,7 +523,7 @@ fn expand_preparsed_asm( if parser.line_spans.is_empty() { let template_num_lines = 1 + template_str.matches('\n').count(); - line_spans.extend(std::iter::repeat(template_sp).take(template_num_lines)); + line_spans.extend(std::iter::repeat_n(template_sp, template_num_lines)); } else { line_spans.extend( parser diff --git a/compiler/rustc_codegen_cranelift/src/constant.rs b/compiler/rustc_codegen_cranelift/src/constant.rs index a56466750e75c..faca92957e1a6 100644 --- a/compiler/rustc_codegen_cranelift/src/constant.rs +++ b/compiler/rustc_codegen_cranelift/src/constant.rs @@ -318,7 +318,7 @@ fn data_id_for_static( let mut data = DataDescription::new(); data.set_align(align); let data_gv = module.declare_data_in_data(data_id, &mut data); - data.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect()); + data.define(std::iter::repeat_n(0, pointer_ty(tcx).bytes() as usize).collect()); data.write_data_addr(0, data_gv, 0); match module.define_data(ref_data_id, &data) { // Every time the static is referenced there will be another definition of this global, diff --git a/compiler/rustc_const_eval/src/const_eval/error.rs b/compiler/rustc_const_eval/src/const_eval/error.rs index e00fb2c1eaf98..69a8f163ca93c 100644 --- a/compiler/rustc_const_eval/src/const_eval/error.rs +++ b/compiler/rustc_const_eval/src/const_eval/error.rs @@ -110,7 +110,7 @@ pub fn get_span_and_frames<'tcx>( if frame.times < 3 { let times = frame.times; frame.times = 0; - frames.extend(std::iter::repeat(frame).take(times as usize)); + frames.extend(std::iter::repeat_n(frame, times as usize)); } else { frames.push(frame); } diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index 785978b4d7111..630e99ad4c74e 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -878,7 +878,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { .compute_size_in_bytes(layout.size, count) .ok_or_else(|| err_ub_custom!(fluent::const_eval_size_overflow, name = name))?; - let bytes = std::iter::repeat(byte).take(len.bytes_usize()); + let bytes = std::iter::repeat_n(byte, len.bytes_usize()); self.write_bytes_ptr(dst, bytes) } diff --git a/compiler/rustc_const_eval/src/util/check_validity_requirement.rs b/compiler/rustc_const_eval/src/util/check_validity_requirement.rs index 1dea7e4252d7f..34bd8423e8e15 100644 --- a/compiler/rustc_const_eval/src/util/check_validity_requirement.rs +++ b/compiler/rustc_const_eval/src/util/check_validity_requirement.rs @@ -59,7 +59,7 @@ fn check_validity_requirement_strict<'tcx>( if kind == ValidityRequirement::Zero { cx.write_bytes_ptr( allocated.ptr(), - std::iter::repeat(0_u8).take(ty.layout.size().bytes_usize()), + std::iter::repeat_n(0_u8, ty.layout.size().bytes_usize()), ) .expect("failed to write bytes for zero valid check"); } diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 02baaec37138c..24e20ef5b1b2e 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -590,7 +590,7 @@ fn get_new_lifetime_name<'tcx>( let a_to_z_repeat_n = |n| { (b'a'..=b'z').map(move |c| { let mut s = '\''.to_string(); - s.extend(std::iter::repeat(char::from(c)).take(n)); + s.extend(std::iter::repeat_n(char::from(c), n)); s }) }; diff --git a/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs b/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs index 8a9f9130feacb..30324da3c6516 100644 --- a/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs +++ b/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs @@ -339,8 +339,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { hir::GenericArg::Lifetime(lt) => Some(lt), _ => None, }) { - return std::iter::repeat(lt.to_string()) - .take(num_params_to_take) + return std::iter::repeat_n(lt.to_string(), num_params_to_take) .collect::>() .join(", "); } @@ -362,8 +361,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { matches!(fn_decl.output, hir::FnRetTy::Return(ty) if ty.hir_id == ty_id); if in_arg || (in_ret && fn_decl.lifetime_elision_allowed) { - return std::iter::repeat("'_".to_owned()) - .take(num_params_to_take) + return std::iter::repeat_n("'_".to_owned(), num_params_to_take) .collect::>() .join(", "); } @@ -388,10 +386,12 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { }) | hir::Node::AnonConst(..) = node { - return std::iter::repeat("'static".to_owned()) - .take(num_params_to_take.saturating_sub(ret.len())) - .collect::>() - .join(", "); + return std::iter::repeat_n( + "'static".to_owned(), + num_params_to_take.saturating_sub(ret.len()), + ) + .collect::>() + .join(", "); } let params = if let Some(generics) = node.generics() { diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index f9cdc923670f0..e57f970a0e9a2 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -2602,7 +2602,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let suggestion = |name, args| { format!( "::{name}({})", - std::iter::repeat("_").take(args).collect::>().join(", ") + std::iter::repeat_n("_", args).collect::>().join(", ") ) }; match &items[..] { diff --git a/compiler/rustc_lint/src/if_let_rescope.rs b/compiler/rustc_lint/src/if_let_rescope.rs index ff67ed1bc5532..2521c2b4eb6ac 100644 --- a/compiler/rustc_lint/src/if_let_rescope.rs +++ b/compiler/rustc_lint/src/if_let_rescope.rs @@ -1,4 +1,4 @@ -use std::iter::repeat; +use std::iter::repeat_n; use std::ops::ControlFlow; use hir::intravisit::{self, Visitor}; @@ -351,7 +351,7 @@ impl Subdiagnostic for IfLetRescopeRewrite { .then_some(" _ => {}".chars()) .into_iter() .flatten() - .chain(repeat('}').take(closing_brackets.count)) + .chain(repeat_n('}', closing_brackets.count)) .collect(), )); let msg = diag.eagerly_translate(crate::fluent_generated::lint_suggestion); diff --git a/compiler/rustc_middle/src/values.rs b/compiler/rustc_middle/src/values.rs index 4d70a70873267..bc73d36216ef4 100644 --- a/compiler/rustc_middle/src/values.rs +++ b/compiler/rustc_middle/src/values.rs @@ -63,7 +63,7 @@ impl<'tcx> Value> for ty::Binder<'_, ty::FnSig<'_>> { }; let fn_sig = ty::Binder::dummy(tcx.mk_fn_sig( - std::iter::repeat(err).take(arity), + std::iter::repeat_n(err, arity), err, false, rustc_hir::Safety::Safe, diff --git a/compiler/rustc_mir_build/src/check_tail_calls.rs b/compiler/rustc_mir_build/src/check_tail_calls.rs index d40c77d145f47..9115c17f37525 100644 --- a/compiler/rustc_mir_build/src/check_tail_calls.rs +++ b/compiler/rustc_mir_build/src/check_tail_calls.rs @@ -283,7 +283,7 @@ impl<'tcx> TailCallCkVisitor<'_, 'tcx> { fn report_calling_closure(&mut self, fun: &Expr<'_>, tupled_args: Ty<'_>, expr: &Expr<'_>) { let underscored_args = match tupled_args.kind() { ty::Tuple(tys) if tys.is_empty() => "".to_owned(), - ty::Tuple(tys) => std::iter::repeat("_, ").take(tys.len() - 1).chain(["_"]).collect(), + ty::Tuple(tys) => std::iter::repeat_n("_, ", tys.len() - 1).chain(["_"]).collect(), _ => "_".to_owned(), }; diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 4ea237cfa0321..ad4b035916cd9 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -2019,10 +2019,13 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } let expected_sig = tcx.mk_fn_sig( - std::iter::repeat(token_stream).take(match kind { - ProcMacroKind::Attribute => 2, - ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1, - }), + std::iter::repeat_n( + token_stream, + match kind { + ProcMacroKind::Attribute => 2, + ProcMacroKind::Derive | ProcMacroKind::FunctionLike => 1, + }, + ), token_stream, false, Safety::Safe, diff --git a/compiler/rustc_query_system/src/dep_graph/serialized.rs b/compiler/rustc_query_system/src/dep_graph/serialized.rs index 79b99c52d0c01..f5eb61a449f8b 100644 --- a/compiler/rustc_query_system/src/dep_graph/serialized.rs +++ b/compiler/rustc_query_system/src/dep_graph/serialized.rs @@ -566,7 +566,7 @@ impl EncoderState { edge_count: 0, node_count: 0, encoder: MemEncoder::new(), - kind_stats: iter::repeat(0).take(D::DEP_KIND_MAX as usize + 1).collect(), + kind_stats: iter::repeat_n(0, D::DEP_KIND_MAX as usize + 1).collect(), }) }), marker: PhantomData, @@ -735,7 +735,7 @@ impl EncoderState { let mut encoder = self.file.lock().take().unwrap(); - let mut kind_stats: Vec = iter::repeat(0).take(D::DEP_KIND_MAX as usize + 1).collect(); + let mut kind_stats: Vec = iter::repeat_n(0, D::DEP_KIND_MAX as usize + 1).collect(); let mut node_max = 0; let mut node_count = 0; diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 8c2ddda7f9834..1589e3f4092c4 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -2214,10 +2214,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { .collect::>(); items.sort_by_key(|(order, _, _)| *order); let suggestion = |name, args| { - format!( - "::{name}({})", - std::iter::repeat("_").take(args).collect::>().join(", ") - ) + format!("::{name}({})", std::iter::repeat_n("_", args).collect::>().join(", ")) }; match &items[..] { [] => {} @@ -3485,17 +3482,14 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { (lt.span.shrink_to_hi(), format!("{existing_name} ")) } MissingLifetimeKind::Comma => { - let sugg: String = std::iter::repeat([existing_name.as_str(), ", "]) - .take(lt.count) + let sugg: String = std::iter::repeat_n([existing_name.as_str(), ", "], lt.count) .flatten() .collect(); (lt.span.shrink_to_hi(), sugg) } MissingLifetimeKind::Brackets => { let sugg: String = std::iter::once("<") - .chain( - std::iter::repeat(existing_name.as_str()).take(lt.count).intersperse(", "), - ) + .chain(std::iter::repeat_n(existing_name.as_str(), lt.count).intersperse(", ")) .chain([">"]) .collect(); (lt.span.shrink_to_hi(), sugg) diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs index 5b8315841765b..3ee6e6b739c03 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs @@ -305,7 +305,7 @@ fn make_elided_region_spans_suggs<'a>( consecutive_brackets += 1; } else if let Some(bracket_span) = bracket_span.take() { let sugg = std::iter::once("<") - .chain(std::iter::repeat(name).take(consecutive_brackets).intersperse(", ")) + .chain(std::iter::repeat_n(name, consecutive_brackets).intersperse(", ")) .chain([">"]) .collect(); spans_suggs.push((bracket_span.shrink_to_hi(), sugg)); diff --git a/compiler/rustc_transmute/src/layout/tree.rs b/compiler/rustc_transmute/src/layout/tree.rs index 7f626e8c4e886..d9ebdadf3b79c 100644 --- a/compiler/rustc_transmute/src/layout/tree.rs +++ b/compiler/rustc_transmute/src/layout/tree.rs @@ -326,8 +326,7 @@ pub(crate) mod rustc { let inner_layout = layout_of(cx, *inner_ty)?; assert_eq!(*stride, inner_layout.size); let elt = Tree::from_ty(*inner_ty, cx)?; - Ok(std::iter::repeat(elt) - .take(*count as usize) + Ok(std::iter::repeat_n(elt, *count as usize) .fold(Tree::unit(), |tree, elt| tree.then(elt))) } diff --git a/library/core/src/iter/sources/repeat.rs b/library/core/src/iter/sources/repeat.rs index 4bcd5b16aea6a..7fcd6f8963a48 100644 --- a/library/core/src/iter/sources/repeat.rs +++ b/library/core/src/iter/sources/repeat.rs @@ -8,6 +8,9 @@ use crate::num::NonZero; /// Infinite iterators like `repeat()` are often used with adapters like /// [`Iterator::take()`], in order to make them finite. /// +/// If you know the number of repetitions in advance, consider using [`repeat_n()`] +/// instead, as it is more efficient and conveys the intent more clearly. +/// /// Use [`str::repeat()`] instead of this function if you just want to repeat /// a char/string `n` times. /// @@ -15,6 +18,7 @@ use crate::num::NonZero; /// or if you do not want to keep the repeated element in memory, you can /// instead use the [`repeat_with()`] function. /// +/// [`repeat_n()`]: crate::iter::repeat_n /// [`repeat_with()`]: crate::iter::repeat_with /// [`str::repeat()`]: ../../std/primitive.str.html#method.repeat ///