using System.Buffers;
using System.Buffers.Binary;
using System.Text;
namespace Chronos.Data.Postgres;
/// Growable outgoing buffer that frames protocol messages (type byte + big-endian length).
internal sealed class PgWriteBuffer : IBufferWriter
{
private byte[] _buffer = new byte[8192];
private int _messageStart = -1;
public int Length { get; private set; }
public ReadOnlyMemory Written => _buffer.AsMemory(0, Length);
/// Starts a message; its length is patched by .
public void StartMessage(char type)
{
GetSpan(1)[0] = (byte)type;
Advance(1);
StartUntypedMessage();
}
/// Starts a message without a type byte (startup, SSL and cancel requests).
public void StartUntypedMessage()
{
_messageStart = Length;
Advance(4);
}
public void EndMessage()
{
BinaryPrimitives.WriteInt32BigEndian(_buffer.AsSpan(_messageStart), Length - _messageStart);
_messageStart = -1;
}
public void WriteByte(byte value)
{
GetSpan(1)[0] = value;
Advance(1);
}
public void WriteInt16(int value)
{
BinaryPrimitives.WriteInt16BigEndian(GetSpan(2), checked((short)value));
Advance(2);
}
public void WriteInt32(int value)
{
BinaryPrimitives.WriteInt32BigEndian(GetSpan(4), value);
Advance(4);
}
public void Write(ReadOnlySpan bytes)
{
bytes.CopyTo(GetSpan(bytes.Length));
Advance(bytes.Length);
}
/// UTF-8 text followed by a NUL terminator.
public void WriteCString(string text)
{
var n = Encoding.UTF8.GetBytes(text, GetSpan(Encoding.UTF8.GetMaxByteCount(text.Length) + 1));
_buffer[Length + n] = 0;
Advance(n + 1);
}
/// Empties the buffer; an oversized one (a big bytea parameter) is released so pooled connections stay small.
public void Clear()
{
Length = 0;
_messageStart = -1;
if (_buffer.Length > 1 << 20) _buffer = new byte[8192];
}
public void Advance(int count) => Length += count;
public Memory GetMemory(int sizeHint = 0)
{
Ensure(sizeHint);
return _buffer.AsMemory(Length);
}
public Span GetSpan(int sizeHint = 0)
{
Ensure(sizeHint);
return _buffer.AsSpan(Length);
}
private void Ensure(int sizeHint)
{
var needed = Length + Math.Max(sizeHint, 1);
if (needed <= _buffer.Length) return;
Array.Resize(ref _buffer, Math.Max(needed, _buffer.Length * 2));
}
}