Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 04451dc

Browse files
benaadamsdotnet-bot
authored andcommitted
Speedup SpanHelpers.IndexOf{Any}(byte, ...) (dotnet/coreclr#22118)
* Speedup SpanHelpers.IndexOf(byte) * 128 * 2 alignment * Move TrailingZeroCountFallback to common SpanHelpers So it can be used by other types than byte * Speedup SpanHelpers.IndexOfAny(byte, ...) * Indent for support flags * More helpers, constency in local names/formatting, feedback * Skip bounds check in software fallback Signed-off-by: dotnet-bot <[email protected]>
1 parent ffce8c2 commit 04451dc

File tree

4 files changed

+709
-344
lines changed

4 files changed

+709
-344
lines changed

src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
<Compile Include="$(MSBuildThisFileDirectory)System\AttributeUsageAttribute.cs" />
4848
<Compile Include="$(MSBuildThisFileDirectory)System\BadImageFormatException.cs" />
4949
<Compile Include="$(MSBuildThisFileDirectory)System\BitConverter.cs" />
50+
<Compile Include="$(MSBuildThisFileDirectory)System\BitOps.cs" />
5051
<Compile Include="$(MSBuildThisFileDirectory)System\Boolean.cs" />
5152
<Compile Include="$(MSBuildThisFileDirectory)System\Buffers\ArrayPool.cs" />
5253
<Compile Include="$(MSBuildThisFileDirectory)System\Buffers\ArrayPoolEventSource.cs" />
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using System.Runtime.CompilerServices;
6+
using System.Runtime.InteropServices;
7+
using System.Runtime.Intrinsics.X86;
8+
9+
using Internal.Runtime.CompilerServices;
10+
11+
namespace System
12+
{
13+
internal static class BitOps
14+
{
15+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
16+
public static int TrailingZeroCount(int matches)
17+
{
18+
if (Bmi1.IsSupported)
19+
{
20+
return (int)Bmi1.TrailingZeroCount((uint)matches);
21+
}
22+
else // Software fallback
23+
{
24+
// https://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup
25+
// uint.MaxValue >> 27 is always in range [0 - 31] so we use Unsafe.AddByteOffset to avoid bounds check
26+
return Unsafe.AddByteOffset(
27+
ref MemoryMarshal.GetReference(TrailingCountMultiplyDeBruijn),
28+
((uint)((matches & -matches) * 0x077CB531U)) >> 27);
29+
}
30+
}
31+
32+
private static ReadOnlySpan<byte> TrailingCountMultiplyDeBruijn => new byte[32]
33+
{
34+
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
35+
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
36+
};
37+
}
38+
}

0 commit comments

Comments
 (0)