Skip to content

Commit 2127e5d

Browse files
benaadamsjkotalik
authored andcommitted
Remove Unsafe from ChunkWriter (#18450)
1 parent bc60e95 commit 2127e5d

File tree

1 file changed

+8
-11
lines changed

1 file changed

+8
-11
lines changed

src/Servers/Kestrel/Core/src/Internal/Http/ChunkWriter.cs

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,11 @@
44
using System;
55
using System.Buffers;
66
using System.IO.Pipelines;
7-
using System.Text;
8-
using System.Runtime.CompilerServices;
9-
using System.Runtime.InteropServices;
107

118
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
129
{
1310
internal static class ChunkWriter
1411
{
15-
// This uses C# compiler's ability to refer to static data directly. For more information see https://vcsjones.dev/2019/02/01/csharp-readonly-span-bytes-static
16-
private static ReadOnlySpan<byte> Hex => new byte[16] { (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f' };
17-
1812
public static int BeginChunkBytes(int dataCount, Span<byte> span)
1913
{
2014
// Determine the most-significant non-zero nibble
@@ -29,14 +23,17 @@ public static int BeginChunkBytes(int dataCount, Span<byte> span)
2923

3024
count = (total >> 2) + 3;
3125

32-
var offset = 0;
33-
ref var startHex = ref MemoryMarshal.GetReference(Hex);
26+
// This must be explicity typed as ReadOnlySpan<byte>
27+
// It then becomes a non-allocating mapping to the data section of the assembly.
28+
// For more information see https://vcsjones.dev/2019/02/01/csharp-readonly-span-bytes-static
29+
ReadOnlySpan<byte> hex = new byte[16] { (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f' };
3430

31+
var offset = 0;
3532
for (shift = total; shift >= 0; shift -= 4)
3633
{
37-
// Using Unsafe.Add to elide the bounds check on _hex as the & 0x0f definitely
38-
// constrains it to the range 0x0 - 0xf, matching the bounds of the array
39-
span[offset] = Unsafe.Add(ref startHex, ((dataCount >> shift) & 0x0f));
34+
// Uses dotnet/runtime#1644 to elide the bounds check on hex as the & 0x0f definitely
35+
// constrains it to the range 0x0 - 0xf, matching the bounds of the array.
36+
span[offset] = hex[(dataCount >> shift) & 0x0f];
4037
offset++;
4138
}
4239

0 commit comments

Comments
 (0)