From edc6504a8478b0596cdad674a64edde138b0dbd9 Mon Sep 17 00:00:00 2001 From: Pavel Djundik Date: Sun, 11 Feb 2024 11:47:59 +0200 Subject: [PATCH] Change `KVBinaryBlob` to `Memory`, faster to string conversion --- ValveKeyValue/ValveKeyValue/HexStringHelper.cs | 15 +++++++++++++++ ValveKeyValue/ValveKeyValue/KVBinaryBlob.cs | 11 +++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/ValveKeyValue/ValveKeyValue/HexStringHelper.cs b/ValveKeyValue/ValveKeyValue/HexStringHelper.cs index 0e4f835e..640e49a5 100644 --- a/ValveKeyValue/ValveKeyValue/HexStringHelper.cs +++ b/ValveKeyValue/ValveKeyValue/HexStringHelper.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Runtime.CompilerServices; namespace ValveKeyValue { @@ -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; + } } } diff --git a/ValveKeyValue/ValveKeyValue/KVBinaryBlob.cs b/ValveKeyValue/ValveKeyValue/KVBinaryBlob.cs index c2956fb9..a3cc7d34 100644 --- a/ValveKeyValue/ValveKeyValue/KVBinaryBlob.cs +++ b/ValveKeyValue/ValveKeyValue/KVBinaryBlob.cs @@ -4,7 +4,7 @@ namespace ValveKeyValue { public class KVBinaryBlob : KVValue { - public byte[] Bytes { get; } + public Memory Bytes { get; } public override KVValueType ValueType => KVValueType.BinaryBlob; @@ -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(' '); }