Skip to content
Merged
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@

using System;
using System.Collections.Immutable;
using System.Globalization;
using Microsoft.AspNetCore.Razor.PooledObjects;

namespace Microsoft.AspNetCore.Razor.Language;

Expand All @@ -17,15 +15,22 @@ public static string BytesToString(ImmutableArray<byte> bytes)
throw new ArgumentNullException(nameof(bytes));
}

using var _ = StringBuilderPool.GetPooledObject(out var builder);
builder.EnsureCapacity(bytes.Length);

foreach (var b in bytes)
#if NET9_0_OR_GREATER
return Convert.ToHexStringLower(bytes.AsSpan());
#else
return string.Create(bytes.Length * 2, bytes, static (span, bytes) =>
{
// The x2 format means lowercase hex, where each byte is a 2-character string.
builder.Append(b.ToString("x2", CultureInfo.InvariantCulture));
}
foreach (var b in bytes)
{
// Write hex chars directly
span[0] = GetHexChar(b >> 4);
span[1] = GetHexChar(b & 0xf);
span = span[2..];
}
});

return builder.ToString();
static char GetHexChar(int value)
=> (char)(value < 10 ? '0' + value : 'a' + (value - 10));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this faster than indexing into a pre-allocated array of chars?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably slightly slower, but I didn't want to duplicate HexConverter.CharToHexLookup, especially as this won't be used OOP once we move to net9

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wouldn't duplicate all of that either! I was just thinking of something like this:

private static char GetHexChar(int value) => s_hexChars[value];

private static readonly char[] s_hexChars = new[] { '0', '1', '2', '3', '4', '5', '6', '7, '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, that's definitely into the micro-optimization level. I agree that it's not needed for just netstandard2.0. 👍

#endif
}
}