yuanshen/Yuanshen.Kcp/KcpBuffer.cs
wisedev 61cc2055cf First working version of the server
KCP gameserver with packet dispatch, scene streaming, combat, gacha and the
shop, plus a small HTTP server for the login flow and the wish history page.

Game data under assets is pulled out of the client instead of being typed by
hand. The excel tables come from the packed bin container and the spawn points
from the compiled scene scripts.
2026-09-04 02:06:53 +03:00

59 lines
1.7 KiB
C#

using System.Diagnostics;
namespace Yuanshen.Kcp
{
internal readonly struct KcpBuffer
{
private readonly object _owner;
private readonly Memory<byte> _memory;
private readonly int _length;
public ReadOnlyMemory<byte> DataRegion => _memory.Slice(0, _length);
public int Length => _length;
private KcpBuffer(object owner, Memory<byte> memory, int length)
{
_owner = owner;
_memory = memory;
_length = length;
}
public static KcpBuffer CreateFromSpan(KcpRentedBuffer buffer, ReadOnlySpan<byte> dataSource)
{
Memory<byte> memory = buffer.Memory;
if (dataSource.Length > memory.Length)
{
ThrowRentedBufferTooSmall();
}
dataSource.CopyTo(memory.Span);
return new KcpBuffer(buffer.Owner, memory, dataSource.Length);
}
public KcpBuffer AppendData(ReadOnlySpan<byte> data)
{
if (_length + data.Length > _memory.Length)
{
ThrowRentedBufferTooSmall();
}
data.CopyTo(_memory.Span.Slice(_length));
return new KcpBuffer(_owner, _memory, _length + data.Length);
}
public KcpBuffer Consume(int length)
{
Debug.Assert((uint)length <= (uint)_length);
return new KcpBuffer(_owner, _memory.Slice(length), _length - length);
}
public void Release()
{
new KcpRentedBuffer(_owner, _memory).Dispose();
}
private static void ThrowRentedBufferTooSmall()
{
throw new InvalidOperationException("The rented buffer is not large enough to hold the data.");
}
}
}