perf(net): borrow inbound packet storage

Decode headers, optional fields, fragments, and single-fragment messages directly over pooled datagrams. Copy only fragment state that crosses a datagram lifetime, preserve synchronous dispatch and ACK ordering, and lock the path to the owned decoder with differential and zero-allocation tests.
This commit is contained in:
Erik 2026-07-25 05:58:55 +02:00
parent 7211bb1bf7
commit e928c5dd02
18 changed files with 1329 additions and 66 deletions

View file

@ -0,0 +1,74 @@
namespace AcDream.Core.Net.Packets;
/// <summary>
/// Allocation-free decoded packet view. Every memory member borrows the
/// caller's datagram and is valid only while that owner retains the buffer.
/// </summary>
internal readonly record struct BorrowedPacket(
PacketHeader Header,
BorrowedOptionalHeader Optional,
ReadOnlyMemory<byte> Body,
ReadOnlyMemory<byte> FragmentBytes,
int FragmentCount)
{
public BorrowedFragmentEnumerable Fragments =>
new(FragmentBytes);
}
internal readonly record struct BorrowedOptionalHeader(
uint AckSequence,
double TimeSync,
float EchoRequestClientTime,
uint FlowBytes,
ushort FlowInterval,
double ConnectRequestServerTime,
ulong ConnectRequestCookie,
uint ConnectRequestClientId,
uint ConnectRequestServerSeed,
uint ConnectRequestClientSeed,
ReadOnlyMemory<byte> RawBytes,
ReadOnlyMemory<byte> RetransmitRequestBytes,
int RetransmitRequestCount);
internal readonly record struct BorrowedPacketDecodeResult(
BorrowedPacket Packet,
PacketCodec.DecodeError Error)
{
public bool IsOk => Error == PacketCodec.DecodeError.None;
}
internal readonly record struct BorrowedMessageFragment(
MessageFragmentHeader Header,
ReadOnlyMemory<byte> Payload);
internal readonly struct BorrowedFragmentEnumerable(
ReadOnlyMemory<byte> encoded)
{
public Enumerator GetEnumerator() => new(encoded);
internal struct Enumerator(ReadOnlyMemory<byte> remaining)
{
private ReadOnlyMemory<byte> _remaining = remaining;
public BorrowedMessageFragment Current { get; private set; }
public bool MoveNext()
{
if (_remaining.IsEmpty)
return false;
if (!MessageFragment.TryParseBorrowed(
_remaining,
out BorrowedMessageFragment fragment,
out int consumed))
{
throw new InvalidOperationException(
"validated packet contained an invalid fragment");
}
Current = fragment;
_remaining = _remaining.Slice(consumed);
return true;
}
}
}