using System.Net;
using CommunityToolkit.HighPerformance;
namespace Brutal.RakNetApi.Utility;
///
/// A utility struct for reading and writing unmanaged types to and from a buffer.
///
///
/// This is a ref struct. So if you pass it to a method it will be copied so writes
/// will not be visible in the caller's instance of the stream. Either pass by ref, or have your
/// method return the stream so you can go stream = DoWriting(stream);
///
public ref struct Stream
{
///
/// Provides a high-performance structure to manage a mutable buffer using spans,
/// allowing read and write operations for both primitive types and byte spans.
/// Enables efficient serialization and deserialization of data directly into the buffer.
///
public Stream(Span buffer)
{
_buffer = buffer;
}
#region Write
///
/// Writes the provided value of unmanaged type into the stream at the current position.
/// Advances the writing position by the size of after writing.
///
///
/// The type of the value to write. Must be unmanaged and may allow usage in a ref struct.
///
///
/// The value to write into the stream. Passed by reference for efficient handling of unmanaged types.
///
public unsafe void Write(in T data)
where T : unmanaged
{
EnsureRemaining(sizeof(T));
RemainingAs()[0] = data;
_pos += sizeof(T);
}
///
/// Writes a sequence of bytes from the specified read-only span into the current stream.
/// Ensures that the data being written does not exceed the available buffer space.
///
/// The read-only span of bytes containing the data to be written.
public void Write(ReadOnlySpan data)
{
data.CopyTo(Remaining());
_pos += data.Length;
}
///
/// Writes a message with a specified timestamp and a unique message identifier to the stream.
/// This method adds a predefined ID for timestamp messages, followed by the timestamp (converted to network byte order)
/// and the message ID, ensuring proper format for timestamped messages in the communication protocol.
///
/// The timestamp in host byte order to be included in the message.
/// The unique identifier of the message being written.
public void WriteTimestampMessageId(long hostOrderTimestamp, byte messageId)
{
Write((byte)DefaultMessageIDTypes.Timestamp);
Write(IPAddress.HostToNetworkOrder(hostOrderTimestamp));
Write(messageId);
}
#endregion
#region Read
///
/// Reads data of a specified unmanaged type from the current position in the buffer
/// and writes it into the provided reference. Updates the buffer's position after reading.
///
/// The reference to write the read data into.
/// The unmanaged type of the data to read.
public unsafe void Read(ref T destination)
where T : unmanaged
{
EnsureRemaining(sizeof(T));
destination = RemainingAs()[0];
_pos += sizeof(T);
}
///
/// Reads and returns data of a specified unmanaged type from the current position in the buffer.
/// Updates the buffer's position after reading.
///
/// The unmanaged type of the data to read.
/// The data of the specified type read from the buffer.
public T Read()
where T : unmanaged
{
T t = default;
Read(ref t);
return t;
}
///
/// Reads a timestamp from the stream, converting it from network byte order to host byte order.
///
///
/// The timestamp as a value in host byte order.
///
public long ReadTimestamp()
{
return IPAddress.NetworkToHostOrder(Read());
}
///
/// Reads a single byte from the stream and interprets it as a message identifier.
/// The method is typically used to parse and handle serialized message data.
///
/// The message identifier as a byte.
public byte ReadMessageId()
{
return Read();
}
///
/// Attempts to read a timestamped message from the stream. If the message contains a timestamp, it is converted from network byte order to host byte order.
///
///
/// The message Id of the underlying message
/// When this method returns, contains the timestamp in host byte order if the message was timestamped; otherwise, contains 0.
///
/// if the stream contained a timestamped message; otherwise, .
///
public bool TryReadTimestampedMessageId(out byte messageId, out long hostOrderTimestamp)
{
messageId = ReadMessageId();
if (messageId == (byte)DefaultMessageIDTypes.Timestamp)
{
hostOrderTimestamp = ReadTimestamp();
messageId = ReadMessageId();
return true;
}
hostOrderTimestamp = 0;
return false;
}
#endregion
///
/// Returns a span representing the remaining writable portion of the buffer managed by the stream.
/// The returned span starts at the current position within the buffer and extends to the end of the buffer.
///
///
/// A span of bytes representing the unwritten portion of the buffer, allowing direct access to the remaining space.
///
public Span Remaining()
{
return _buffer[_pos..];
}
///
/// Returns a read-only span of bytes representing the segment of the buffer
/// that has been written to. This enables access to the data written
/// without modifying the underlying buffer.
///
///
/// A ReadOnlySpan representing the written portion of the buffer.
///
public ReadOnlySpan Written()
{
return _buffer[.._pos];
}
private Span RemainingAs()
where T : unmanaged
{
return Remaining().Cast();
}
private void EnsureRemaining(int requiredBytes)
{
var remaining = _buffer.Length - _pos;
if (remaining < requiredBytes)
throw new ArgumentException($"Buffer has {remaining} byte(s) remaining but {requiredBytes} are required.");
}
private int _pos;
private readonly Span _buffer;
}