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

Optimize TypeExtensions.HexStr #1278

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
53 changes: 46 additions & 7 deletions src/sys/TypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,21 +122,60 @@ public static string HexStr(this byte[] buffer, char? separator = null)

public static string HexStr(this byte[] buffer, int length, char? separator = null)
{
string rv = string.Empty;
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
if (separator is { } s)
Copy link
Member

Choose a reason for hiding this comment

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

if(separator != null) is a lot clearer here.

{
return string.Create(length * 3 - 1, (buffer, length, s), static (chars, state) =>
{
var (buffer, length, s) = state;
for (int i = 0, j = 0; i < length; i++)
{
var val = buffer[i];
chars[j++] = char.ToUpperInvariant(hexmap[val >> 4]);
chars[j++] = char.ToUpperInvariant(hexmap[val & 15]);
if (j < chars.Length)
{
chars[j++] = s;
}
}
});
}
else
{
return string.Create(length * 2, (buffer, length), static (chars, state) =>
{
var (buffer, length) = state;
for (int i = 0, j = 0; i < length; i++)
{
var val = buffer[i];
chars[j++] = char.ToUpperInvariant(hexmap[val >> 4]);
chars[j++] = char.ToUpperInvariant(hexmap[val & 15]);
}
});
}
#else
var numberOfChars = length * 2;
if (separator.HasValue)
{
numberOfChars += length - 1;
}

var rv = new char[numberOfChars];

for (int i = 0; i < length; i++)
for (int i = 0, j = 0; i < length; i++)
{
var val = buffer[i];
rv += hexmap[val >> 4];
rv += hexmap[val & 15];
rv[j++] = char.ToUpperInvariant(hexmap[val >> 4]);
rv[j++] = char.ToUpperInvariant(hexmap[val & 15]);

if (separator != null && i != length - 1)
if (separator != null && i != length - 1 && separator is { } s)
{
rv += separator;
rv[j++] = s;
}
}

return rv.ToUpper();
return new string(rv);
#endif
}

public static byte[] ParseHexStr(string hexStr)
Expand Down