Open annelo-msft opened 1 year ago
FYI, I was thinking about something like this (probably 100x faster than the current SB implementation):
static readonly string prefixUtf16 = "sha256:";
static readonly string nibbleToHexMap = "0123456789abcdef";
public static bool TryFormatAsHexUtf16(byte[] bytes, scoped Span<char> utf16, out int charsWritten)
{
charsWritten = 0;
if (utf16.Length < prefixUtf16.Length + (bytes.Length << 1)) return false;
prefixUtf16.CopyTo(utf16);
charsWritten = prefixUtf16.Length;
for (int i = 0; i < bytes.Length; i++)
{
var nextByte = bytes[i];
var high = (byte)(nextByte >> 4);
utf16[charsWritten++] = nibbleToHexMap[high];
var low = (byte)(nextByte & 0x0F);
utf16[charsWritten++] = nibbleToHexMap[low];
}
return true;
}
if you really need a string then this method could be called as:
public static string BytesToString(byte[] bytes)
{
var length = prefixUtf16.Length + (bytes.Length << 1);
char[] chars = new char[length];
if (!TryFormatAsHexUtf16(bytes, chars, out var written)) throw new Exception("should not happen");
return new string(chars);
}
Another suggestion to consider here: https://github.com/Azure/azure-sdk-for-net/pull/34940#discussion_r1140506122