Skip to content

Commit 5601559

Browse files
committed
Codegen improvements to Numerics.Clamp
1 parent 1a3e1e7 commit 5601559

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

src/ImageSharp/Common/Helpers/Numerics.cs

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -425,33 +425,42 @@ private static void ClampImpl<T>(Span<T> span, T min, T max)
425425
where T : unmanaged
426426
{
427427
ref T sRef = ref MemoryMarshal.GetReference(span);
428-
ref Vector<T> vsBase = ref Unsafe.As<T, Vector<T>>(ref MemoryMarshal.GetReference(span));
429428
var vmin = new Vector<T>(min);
430429
var vmax = new Vector<T>(max);
431430

432431
int n = span.Length / Vector<T>.Count;
433432
int m = Modulo4(n);
434433
int u = n - m;
435434

436-
for (int i = 0; i < u; i += 4)
437-
{
438-
ref Vector<T> vs0 = ref Unsafe.Add(ref vsBase, i);
439-
ref Vector<T> vs1 = ref Unsafe.Add(ref vs0, 1);
440-
ref Vector<T> vs2 = ref Unsafe.Add(ref vs0, 2);
441-
ref Vector<T> vs3 = ref Unsafe.Add(ref vs0, 3);
435+
ref Vector<T> vs0 = ref Unsafe.As<T, Vector<T>>(ref MemoryMarshal.GetReference(span));
436+
ref Vector<T> vs1 = ref Unsafe.Add(ref vs0, 1);
437+
ref Vector<T> vs2 = ref Unsafe.Add(ref vs0, 2);
438+
ref Vector<T> vs3 = ref Unsafe.Add(ref vs0, 3);
439+
ref Vector<T> vsEnd = ref Unsafe.Add(ref vs0, u);
442440

441+
while (Unsafe.IsAddressLessThan(ref vs0, ref vsEnd))
442+
{
443443
vs0 = Vector.Min(Vector.Max(vmin, vs0), vmax);
444444
vs1 = Vector.Min(Vector.Max(vmin, vs1), vmax);
445445
vs2 = Vector.Min(Vector.Max(vmin, vs2), vmax);
446446
vs3 = Vector.Min(Vector.Max(vmin, vs3), vmax);
447+
448+
vs0 = ref Unsafe.Add(ref vs0, 4);
449+
vs1 = ref Unsafe.Add(ref vs1, 4);
450+
vs2 = ref Unsafe.Add(ref vs2, 4);
451+
vs3 = ref Unsafe.Add(ref vs3, 4);
447452
}
448453

449454
if (m > 0)
450455
{
451-
for (int i = u; i < n; i++)
456+
vs0 = ref vsEnd;
457+
vsEnd = ref Unsafe.Add(ref vsEnd, m);
458+
459+
while (Unsafe.IsAddressLessThan(ref vs0, ref vsEnd))
452460
{
453-
ref Vector<T> vs0 = ref Unsafe.Add(ref vsBase, i);
454461
vs0 = Vector.Min(Vector.Max(vmin, vs0), vmax);
462+
463+
vs0 = ref Unsafe.Add(ref vs0, 1);
455464
}
456465
}
457466
}

0 commit comments

Comments
 (0)