Skip to content

Commit

Permalink
Change KVBinaryBlob to Memory<byte>, faster to string conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
xPaw committed Feb 11, 2024
1 parent d1f6acd commit edc6504
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
15 changes: 15 additions & 0 deletions ValveKeyValue/ValveKeyValue/HexStringHelper.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Globalization;
using System.Runtime.CompilerServices;

namespace ValveKeyValue
{
Expand All @@ -17,5 +18,19 @@ public static byte[] ParseHexStringAsByteArray(string hexadecimalRepresentation)

return data;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static char HexToCharUpper(int value)
{
value &= 0xF;
value += '0';

if (value > '9')
{
value += ('A' - ('9' + 1));
}

return (char)value;
}
}
}
11 changes: 7 additions & 4 deletions ValveKeyValue/ValveKeyValue/KVBinaryBlob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace ValveKeyValue
{
public class KVBinaryBlob : KVValue
{
public byte[] Bytes { get; }
public Memory<byte> Bytes { get; }

public override KVValueType ValueType => KVValueType.BinaryBlob;

Expand Down Expand Up @@ -102,11 +102,14 @@ public override ulong ToUInt64(IFormatProvider provider)

public override string ToString()
{
var builder = new StringBuilder();
var bytes = Bytes.Span;
var builder = new StringBuilder(bytes.Length * 3);

foreach (var oneByte in Bytes)
for (var i = 0; i < Bytes.Length; i++)
{
builder.Append(oneByte.ToString("X2"));
var b = bytes[i];
builder.Append(HexStringHelper.HexToCharUpper(b >> 4));
builder.Append(HexStringHelper.HexToCharUpper(b));
builder.Append(' ');
}

Expand Down

0 comments on commit edc6504

Please sign in to comment.