diff --git a/src/mscorlib/shared/System/SpanHelpers.Char.cs b/src/mscorlib/shared/System/SpanHelpers.Char.cs index 6ca215d6a3dc..51ace58a39d5 100644 --- a/src/mscorlib/shared/System/SpanHelpers.Char.cs +++ b/src/mscorlib/shared/System/SpanHelpers.Char.cs @@ -93,9 +93,13 @@ public static unsafe int IndexOf(ref char searchSpace, char value, int length) #if !netstandard11 if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { + // Figure out how many characters to read sequentially until we are vector aligned + // This is equivalent to: + // unaligned = ((int)pCh % Unsafe.SizeOf>()) / elementsPerByte + // length = (Vector.Count - unaligned) % Vector.Count const int elementsPerByte = sizeof(ushort) / sizeof(byte); int unaligned = ((int)pCh & (Unsafe.SizeOf>() - 1)) / elementsPerByte; - length = ((Vector.Count - unaligned) & (Vector.Count - 1)); + length = (Vector.Count - unaligned) & (Vector.Count - 1); } SequentialScan: #endif @@ -129,6 +133,9 @@ public static unsafe int IndexOf(ref char searchSpace, char value, int length) // the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated. if (Vector.IsHardwareAccelerated && pCh < pEndCh) { + // Get the highest multiple of Vector.Count that is within the search space. + // That will be how many times we iterate in the loop below. + // This is equivalent to: length = Vector.Count * ((int)(pEndCh - pCh) / Vector.Count) length = (int)((pEndCh - pCh) & ~(Vector.Count - 1)); // Get comparison Vector @@ -180,8 +187,10 @@ public static unsafe int LastIndexOf(ref char searchSpace, char value, int lengt #if !netstandard11 if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { + // Figure out how many characters to read sequentially from the end until we are vector aligned + // This is equivalent to: length = ((int)pCh % Unsafe.SizeOf>()) / elementsPerByte const int elementsPerByte = sizeof(ushort) / sizeof(byte); - length = (((int)pCh & (Unsafe.SizeOf>() - 1)) / elementsPerByte); + length = ((int)pCh & (Unsafe.SizeOf>() - 1)) / elementsPerByte; } SequentialScan: #endif @@ -213,6 +222,9 @@ public static unsafe int LastIndexOf(ref char searchSpace, char value, int lengt // the JIT to see that the code is unreachable and eliminate it when the platform does not have hardware accelerated. if (Vector.IsHardwareAccelerated && pCh > pEndCh) { + // Get the highest multiple of Vector.Count that is within the search space. + // That will be how many times we iterate in the loop below. + // This is equivalent to: length = Vector.Count * ((int)(pCh - pEndCh) / Vector.Count) length = (int)((pCh - pEndCh) & ~(Vector.Count - 1)); // Get comparison Vector