Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Http] Remove some unsafe code and save a string allocation #31267

Merged
merged 6 commits into from
Mar 30, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 4 additions & 12 deletions src/Http/Headers/src/ContentDispositionHeaderValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -532,19 +532,11 @@ private bool RequiresEncoding(StringSegment input)
}

// Encode using MIME encoding
private unsafe string EncodeMime(StringSegment input)
private string EncodeMime(StringSegment input)
{
fixed (char* chars = input.Buffer)
{
var byteCount = Encoding.UTF8.GetByteCount(chars + input.Offset, input.Length);
var buffer = new byte[byteCount];
fixed (byte* bytes = buffer)
{
Encoding.UTF8.GetBytes(chars + input.Offset, input.Length, bytes, byteCount);
}
var encodedName = Convert.ToBase64String(buffer);
return "=?utf-8?B?" + encodedName + "?=";
}
var buffer = Encoding.UTF8.GetBytes(input.Buffer);
BrennanConroy marked this conversation as resolved.
Show resolved Hide resolved
var encodedName = Convert.ToBase64String(buffer);
return string.Concat("=?utf-8?B?", encodedName, "?=");
BrennanConroy marked this conversation as resolved.
Show resolved Hide resolved
}

// Attempt to decode MIME encoded strings
Expand Down
72 changes: 10 additions & 62 deletions src/Http/Headers/src/HeaderUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ public static bool ContainsCacheDirective(StringValues cacheControlDirectives, s
return false;
}

private static unsafe bool TryParseNonNegativeInt64FromHeaderValue(int startIndex, string headerValue, out long result)
private static bool TryParseNonNegativeInt64FromHeaderValue(int startIndex, string headerValue, out long result)
{
// Trim leading whitespace
startIndex += HttpRuleParser.GetWhitespaceLength(headerValue, startIndex);
Expand Down Expand Up @@ -366,40 +366,15 @@ private static unsafe bool TryParseNonNegativeInt64FromHeaderValue(int startInde
/// result will be overwritten.
/// </param>
/// <returns><see langword="true" /> if parsing succeeded; otherwise, <see langword="false" />.</returns>
public static unsafe bool TryParseNonNegativeInt32(StringSegment value, out int result)
public static bool TryParseNonNegativeInt32(StringSegment value, out int result)
{
if (string.IsNullOrEmpty(value.Buffer) || value.Length == 0)
{
result = 0;
return false;
}

result = 0;
fixed (char* ptr = value.Buffer)
{
var ch = (ushort*)ptr + value.Offset;
var end = ch + value.Length;

ushort digit = 0;
while (ch < end && (digit = (ushort)(*ch - 0x30)) <= 9)
{
// Check for overflow
if ((result = result * 10 + digit) < 0)
{
result = 0;
return false;
}

ch++;
}

if (ch != end)
{
result = 0;
return false;
}
return true;
}
return int.TryParse(value.Buffer.AsSpan().Slice(value.Offset, value.Length), NumberStyles.None, NumberFormatInfo.InvariantInfo, out result);
BrennanConroy marked this conversation as resolved.
Show resolved Hide resolved
}

/// <summary>
Expand All @@ -417,40 +392,14 @@ public static unsafe bool TryParseNonNegativeInt32(StringSegment value, out int
/// originally supplied in result will be overwritten.
/// </param>
/// <returns><see langword="true" /> if parsing succeeded; otherwise, <see langword="false" />.</returns>
public static unsafe bool TryParseNonNegativeInt64(StringSegment value, out long result)
public static bool TryParseNonNegativeInt64(StringSegment value, out long result)
{
if (string.IsNullOrEmpty(value.Buffer) || value.Length == 0)
{
result = 0;
return false;
}

result = 0;
fixed (char* ptr = value.Buffer)
{
var ch = (ushort*)ptr + value.Offset;
var end = ch + value.Length;

ushort digit = 0;
while (ch < end && (digit = (ushort)(*ch - 0x30)) <= 9)
{
// Check for overflow
if ((result = result * 10 + digit) < 0)
{
result = 0;
return false;
}

ch++;
}

if (ch != end)
{
result = 0;
return false;
}
return true;
}
return long.TryParse(value.Buffer.AsSpan().Slice(value.Offset, value.Length), NumberStyles.None, NumberFormatInfo.InvariantInfo, out result);
BrennanConroy marked this conversation as resolved.
Show resolved Hide resolved
}

// Strict and fast RFC7231 5.3.1 Quality value parser (and without memory allocation)
Expand Down Expand Up @@ -553,7 +502,7 @@ internal static bool TryParseQualityDouble(StringSegment input, int startIndex,
/// <returns>
/// The string representation of the value of this instance, consisting of a sequence of digits ranging from 0 to 9 with no leading zeroes.
/// </returns>
public unsafe static string FormatNonNegativeInt64(long value)
public static string FormatNonNegativeInt64(long value)
{
if (value < 0)
{
Expand All @@ -566,18 +515,17 @@ public unsafe static string FormatNonNegativeInt64(long value)
}

var position = _int64MaxStringLength;
char* charBuffer = stackalloc char[_int64MaxStringLength];
Span<char> charBuffer = stackalloc char[_int64MaxStringLength];
BrennanConroy marked this conversation as resolved.
Show resolved Hide resolved

do
{
// Consider using Math.DivRem() if available
var quotient = value / 10;
charBuffer[--position] = (char)(0x30 + (value - quotient * 10)); // 0x30 = '0'
var (quotient, rem) = Math.DivRem(value, 10);
charBuffer[--position] = (char)(0x30 + rem); // 0x30 = '0'
value = quotient;
}
while (value != 0);

return new string(charBuffer, position, _int64MaxStringLength - position);
return new string(charBuffer.Slice(position));
}

/// <summary>
Expand Down
14 changes: 13 additions & 1 deletion src/Http/Headers/src/MediaTypeHeaderValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,19 @@ private static int GetMediaTypeExpressionLength(StringSegment input, int startIn
}
else
{
mediaType = input.Substring(startIndex, typeLength) + ForwardSlashCharacter + input.Substring(current, subtypeLength);
// Equivalent to: input.Substring(startIndex, typeLength) + ForwardSlashCharacter + input.Substring(current, subtypeLength);
// but saves an unnecessary string allocation
mediaType = string.Create(typeLength + subtypeLength + 1, (input, startIndex, typeLength, subtypeLength, current), static (span, state) =>
davidfowl marked this conversation as resolved.
Show resolved Hide resolved
{
var (input, startIndex, typeLength, subtypeLength, current) = state;
var segment = input.Buffer.AsSpan(input.Offset);
BrennanConroy marked this conversation as resolved.
Show resolved Hide resolved
BrennanConroy marked this conversation as resolved.
Show resolved Hide resolved
segment.Slice(startIndex, typeLength).CopyTo(span);

span[typeLength] = ForwardSlashCharacter;

span = span.Slice(typeLength + 1);
segment.Slice(current, subtypeLength).CopyTo(span);
});
}

return mediaTypeLength;
Expand Down
3 changes: 1 addition & 2 deletions src/Http/Headers/src/Microsoft.Net.Http.Headers.csproj
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Description>HTTP header parser implementations.</Description>
<TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework>
<IsAspNetCoreApp>true</IsAspNetCoreApp>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageTags>http</PackageTags>
<IsPackable>false</IsPackable>
Expand Down
4 changes: 2 additions & 2 deletions src/Http/Routing/src/Matching/SingleEntryAsciiJumpTable.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
Expand Down Expand Up @@ -27,7 +27,7 @@ public SingleEntryAsciiJumpTable(
_destination = destination;
}

public unsafe override int GetDestination(string path, PathSegment segment)
public override int GetDestination(string path, PathSegment segment)
{
var length = segment.Length;
if (length == 0)
Expand Down
1 change: 0 additions & 1 deletion src/Http/Routing/src/Microsoft.AspNetCore.Routing.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ Microsoft.AspNetCore.Routing.RouteCollection</Description>
<IsAspNetCoreApp>true</IsAspNetCoreApp>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageTags>aspnetcore;routing</PackageTags>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand Down