[Http] Remove some unsafe code and save a string allocation by BrennanConroy · Pull Request #31267 · dotnet/aspnetcore (original) (raw)

For some reason the following code is slower and supposedly allocates more than the current impl (using BenchmarkDotnet):

private static ReadOnlySpan<char> MimePrefix => new char[] { '"', '=', '?', 'u', 't', 'f', '-', '8', '?', 'B', '?' };
private static ReadOnlySpan<char> MimeSuffix => new char[] { '?', '=', '"' };
// ...

var utf8Length = Encoding.UTF8.GetByteCount(input.AsSpan());
var buffer = ArrayPool<byte>.Shared.Rent(utf8Length);
try
{
    Encoding.UTF8.GetBytes(input.AsSpan(), buffer);

    return string.Create(MimePrefix.Length + MimeSuffix.Length + GetBase64Length(utf8Length), (buffer, utf8Length), static (span, state) =>
    {
        MimePrefix.CopyTo(span);
        span = span.Slice(MimePrefix.Length);
        var ret = Convert.TryToBase64Chars(state.buffer.AsSpan().Slice(0, state.utf8Length),
            span, out var written);
        Debug.Assert(ret);

        span = span.Slice(written);
        MimeSuffix.CopyTo(span);

        if (span.Length != MimeSuffix.Length)
        {
            throw new InvalidOperationException();
        }
    });
}
finally
{
    ArrayPool<byte>.Shared.Return(buffer);
}
var contentDisposition = new ContentDispositionHeaderValue("inline");
contentDisposition.FileName = "FileÃName.bat";

I'm going to stop work on this and merge as is assuming there are no glaring issues with the recent changes during PR review.