Skip to content

Commit e4945d8

Browse files
Add span-based byte buffer ToString helper
1 parent d5f866c commit e4945d8

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

Program/PacketParsing/Backends/PcapBackend.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ private static unsafe void OnPacketArrival(object sender, PacketCapture packet)
128128
if (LogPackets)
129129
{
130130
string packetLogString = $"{packet.Header.Timeval.Date:yyyy-MM-dd hh:mm:ss.fff} [{packet.Data.Length}] " +
131-
$"{BitConverter.ToString(headerData.ToArray())} | {BitConverter.ToString(packetData.ToArray())}";
131+
$"{ParsingUtils.ToString(headerData)} | {ParsingUtils.ToString(packetData)}";
132132
Console.WriteLine(packetLogString);
133133
Logging.Packet_WriteLine(packetLogString);
134134
}

Program/PacketParsing/ParsingUtils.cs

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ public static bool DecodeLEB128(ReadOnlySpan<byte> data, out int result, out int
3333
// Detect length sequences longer than 4 bytes
3434
if ((value & 0x80) != 0)
3535
{
36-
Debug.WriteLine($"Variable-length value is greater than 4 bytes! Buffer: {BitConverter.ToString(data.ToArray())}");
36+
Debug.WriteLine($"Variable-length value is greater than 4 bytes! Buffer: {ToString(data)}");
3737
byteLength = 0;
3838
result = 0;
3939
return false;
@@ -42,6 +42,28 @@ public static bool DecodeLEB128(ReadOnlySpan<byte> data, out int result, out int
4242
return true;
4343
}
4444

45+
public static string ToString(ReadOnlySpan<byte> buffer)
46+
{
47+
const string characters = "0123456789ABCDEF";
48+
49+
if (buffer.IsEmpty)
50+
return "";
51+
52+
Span<char> stringBuffer = stackalloc char[buffer.Length * 3];
53+
for (int i = 0; i < buffer.Length; i++)
54+
{
55+
byte value = buffer[i];
56+
int stringIndex = i * 3;
57+
stringBuffer[stringIndex] = characters[(value & 0xF0) >> 4];
58+
stringBuffer[stringIndex + 1] = characters[value & 0x0F];
59+
stringBuffer[stringIndex + 2] = '-';
60+
}
61+
// Exclude last '-'
62+
stringBuffer = stringBuffer.Slice(0, stringBuffer.Length - 1);
63+
64+
return stringBuffer.ToString();
65+
}
66+
4567
/// <summary>
4668
/// Scales a byte to a short, starting from the negative end.
4769
/// </summary>

0 commit comments

Comments
 (0)