2y ago · Jan 8, 2024 5:15 PM
When reading binary packet streams or file headers, using copies fields one by one.
Using to cast raw byte spans directly into structured types in O(0) time:
performs bounds checking and reinterprets the span memory layout without allocating or copying a single byte!
CODE
BinaryReaderUsing
CODE
MemoryMarshal.Cast CSHARP
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public readonly record struct PacketHeader(uint Magic, ushort PacketType, uint PayloadLength, ulong Timestamp);
public static class FastPacketParser
{
public static bool TryParseHeader(ReadOnlySpan<byte> rawBytes, out PacketHeader header)
{
// Cast ReadOnlySpan<byte> into ReadOnlySpan<PacketHeader>
ReadOnlySpan<PacketHeader> headerSpan = MemoryMarshal.Cast<byte, PacketHeader>(rawBytes);
if (headerSpan.IsEmpty)
{
header = default;
return false;
}
header = headerSpan[0];
return header.Magic == 0x504B5431; // 'PKT1'
}
} CODE
MemoryMarshal.Cast
BytePusher · Memory & Performance
Zero-allocation C# code using Span<T>, Memory<T>, and Unsafe...
Zero-allocation C# code using Span<T>, Memory<T>, and Unsafe...
The following users thanked BytePusher for this post: