From 99929e900ffd0c73da12d6f91e4aabee171d7bb0 Mon Sep 17 00:00:00 2001 From: EgorBo Date: Sat, 25 Apr 2026 19:34:54 +0200 Subject: [PATCH] Use safe Span.Slice loop pattern in Enumerable.FillIncrementing Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../System.Linq/src/System/Linq/Range.cs | 21 ++++++------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/src/libraries/System.Linq/src/System/Linq/Range.cs b/src/libraries/System.Linq/src/System/Linq/Range.cs index 7c5bae3f395e80..a67be74d552bb9 100644 --- a/src/libraries/System.Linq/src/System/Linq/Range.cs +++ b/src/libraries/System.Linq/src/System/Linq/Range.cs @@ -4,8 +4,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Numerics; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; namespace System.Linq { @@ -79,33 +77,26 @@ public override void Dispose() /// Fills the with incrementing numbers, starting from . private static void FillIncrementing(Span destination, T value) where T : INumber { - ref T pos = ref MemoryMarshal.GetReference(destination); - ref T end = ref Unsafe.Add(ref pos, destination.Length); - if (Vector.IsHardwareAccelerated && Vector.IsSupported && destination.Length >= Vector.Count) { - Vector init = Vector.Indices; - Vector current = new Vector(value) + init; + Vector current = new Vector(value) + Vector.Indices; Vector increment = new Vector(T.CreateTruncating(Vector.Count)); - ref T oneVectorFromEnd = ref Unsafe.Subtract(ref end, Vector.Count); - do + while (destination.Length >= Vector.Count) { - current.StoreUnsafe(ref pos); + current.CopyTo(destination); current += increment; - pos = ref Unsafe.Add(ref pos, Vector.Count); + destination = destination.Slice(Vector.Count); } - while (Unsafe.IsAddressLessThanOrEqualTo(ref pos, ref oneVectorFromEnd)); value = current[0]; } - while (Unsafe.IsAddressLessThan(ref pos, ref end)) + foreach (ref T slot in destination) { - pos = value++; - pos = ref Unsafe.Add(ref pos, 1); + slot = value++; } } }