This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit b578433e37
7 changed files with 784842 additions and 0 deletions

View file

@ -0,0 +1,40 @@
namespace Brutal.RakNetApi;
public partial struct AddressOrGUID
{
public static AddressOrGUID UnassignedGuid => new(RakNetGUID.UNASSIGNED_RAKNET_GUID);
public static AddressOrGUID From(RakNetGUID guid) => new(guid);
public static AddressOrGUID From(SystemAddress address) => new(address);
public AddressOrGUID(RakNetGUID guid)
{
RakNetGuid = guid;
SystemAddress = SystemAddress.UNASSIGNED_SYSTEM_ADDRESS;
}
public AddressOrGUID(SystemAddress systemAddress)
{
SystemAddress = systemAddress;
RakNetGuid = RakNetGUID.UNASSIGNED_RAKNET_GUID;
}
public string ToString(bool appendPort = false, char delimiter = ':')
{
return RakNetGuid != RakNetGUID.UNASSIGNED_RAKNET_GUID
? RakNetGuid.ToString()
: SystemAddress.ToString(appendPort, delimiter);
}
}
/*public readonly unsafe partial struct RakPeerInstance : IDisposable
{
public void Dispose()
{
if (impl != 0)
{
RakNetLibrary.DestroyInstance(this);
}
}
}*/

View file

@ -0,0 +1,70 @@
namespace Brutal.RakNetApi;
public partial struct RakNetGUID : IEquatable<RakNetGUID>
{
/// <summary>
/// A special RakNetGUID used in the API.
/// </summary>
/// <remarks>
/// UNASSIGNED_RAKNET_GUID is often means for concepts like "MY GUID" or "ANY GUID"
/// </remarks>
public static readonly RakNetGUID UNASSIGNED_RAKNET_GUID = new()
{
G = ulong.MaxValue,
SystemIndex = ushort.MaxValue,
};
/// <summary>
/// Converts the current <see cref="RakNetGUID"/> instance to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="RakNetGUID"/> instance. Returns "UNASSIGNED_RAKNET_GUID" if the instance is equal to <see cref="UNASSIGNED_RAKNET_GUID"/>, otherwise returns the value of the G field as a string.</returns>
public override string ToString()
{
return this == UNASSIGNED_RAKNET_GUID ? "UNASSIGNED_RAKNET_GUID" : $"{G}";
}
/// <summary>
/// Defines an equality operator for comparing two instances of <see cref="RakNetGUID"/>.
/// </summary>
/// <param name="left">The first <see cref="RakNetGUID"/> instance to compare.</param>
/// <param name="right">The second <see cref="RakNetGUID"/> instance to compare.</param>
/// <returns>True if the two instances are equal; otherwise, false.</returns>
public static bool operator ==(RakNetGUID left, RakNetGUID right) => left.G == right.G;
/// <summary>
/// Defines an equality operator for comparing two instances of <see cref="RakNetGUID"/>.
/// </summary>
/// <param name="left">The first <see cref="RakNetGUID"/> instance to compare.</param>
/// <param name="right">The second <see cref="RakNetGUID"/> instance to compare.</param>
/// <returns>True if the two instances are equal; otherwise, false.</returns>
public static bool operator !=(RakNetGUID left, RakNetGUID right) => !(left == right);
/// <summary>
/// Determines whether the current instance is equal to another instance of <see cref="RakNetGUID"/>.
/// </summary>
/// <param name="other">The <see cref="RakNetGUID"/> instance to compare with the current instance.</param>
/// <returns>True if the current instance is equal to the specified instance; otherwise, false.</returns>
public bool Equals(RakNetGUID other)
{
return G == other.G;
}
/// <summary>
/// Determines whether the current instance is equal to a specified object.
/// </summary>
/// <param name="obj">The object to compare with the current instance.</param>
/// <returns>True if the specified object is equal to the current instance; otherwise, false.</returns>
public override bool Equals(object? obj)
{
return obj is RakNetGUID other && Equals(other);
}
/// <summary>
/// Generates a hash code for the current instance of <see cref="RakNetGUID"/> based on its field values.
/// </summary>
/// <returns>A hash code representing the current instance.</returns>
public override int GetHashCode()
{
return G.GetHashCode();
}
}

View file

@ -0,0 +1,42 @@
using System.Runtime.InteropServices;
namespace Brutal.RakNetApi
{
public partial struct SockaddrIn
{
[FieldOffset(1)]
private byte SinFamilyBsd;
public ushort SinFamily
{
get => SockAddrUtility.Layout == SockAddrUtility.SockAddrLayout.Bsd ? SinFamilyBsd : SinFamilyNonBsd;
set
{
if (SockAddrUtility.Layout == SockAddrUtility.SockAddrLayout.Bsd)
SinFamilyBsd = (byte)value;
else
SinFamilyNonBsd = value;
}
}
}
public static partial class SockAddrUtility
{
static SockAddrUtility()
{
Layout = IsNonBsdSockAddrLayout() ? SockAddrLayout.NonBsd : SockAddrLayout.Bsd;
}
public enum SockAddrLayout : byte
{
Bsd = 0,
NonBsd = 1,
};
[LibraryImport("RakNetDLL", EntryPoint = "IsNonBsdSockAddrLayout")]
[return: MarshalAs(UnmanagedType.U1)]
public static partial bool IsNonBsdSockAddrLayout();
public static SockAddrLayout Layout { get; }
}
}

View file

@ -0,0 +1,115 @@
using System.Net.Sockets;
using System.Text;
using Brutal.Strings;
namespace Brutal.RakNetApi;
/// <summary>
/// Partial struct for SocketDescriptor that provides useful functionality.
/// </summary>
public unsafe partial struct SocketDescriptor
{
/// <summary>
/// Create a SocketDescriptor with an IPV4 address family.
/// </summary>
public SocketDescriptor()
: this(AddressFamily.InterNetwork) { }
/// <summary>
/// Create a socket descriptor for IPV4 with port and AddressFamily
/// </summary>
/// <param name="port">Port to use</param>
/// <param name="family">Address family to use</param>
public SocketDescriptor(int port, AddressFamily family = AddressFamily.InterNetwork)
: this("", port, family) { }
/// <summary>
/// Create a SocketDescriptor with an AddressFamily
/// </summary>
public SocketDescriptor(AddressFamily addressFamily)
: this(0, addressFamily) { }
/// <summary>
/// Create a SocketDescriptor with a host, port and optional AddressFamily.
/// </summary>
/// <param name="host">Host address or name</param>
/// <param name="port">Port to use</param>
/// <param name="family">The Address Family to use, defaults to IPV4</param>
public SocketDescriptor(string host, int port, AddressFamily family = AddressFamily.InterNetwork)
{
SetHostAddress(host);
Port = (ushort)port;
SocketFamily = (short)family;
BlockingSocket = true;
RemotePortRakNetWasStartedOnPS3PSP2 = 0;
ExtraSocketOptions = 0;
}
/// <summary>
/// Sets the host address for the socket descriptor. The address must encode to at most
/// <see cref="HostAddressLength"/> - 1 UTF-8 bytes so the buffer stays null-terminated;
/// any remaining buffer space is cleared. On failure the existing address is left unchanged.
/// </summary>
/// <param name="host">The host address as a string.</param>
/// <exception cref="ArgumentException">The encoded address does not fit.</exception>
public void SetHostAddress(string host)
{
Span<byte> encoded = stackalloc byte[HostAddressLength - 1];
if (!Utf8.TryGetBytes(host, encoded, out var bytesWritten))
throw new ArgumentException(
$"Host address must encode to at most {HostAddressLength - 1} UTF-8 bytes to leave room for the null terminator.",
nameof(host)
);
fixed (byte* ptr = HostAddress)
{
var buffer = new Span<byte>(ptr, HostAddressLength);
encoded[..bytesWritten].CopyTo(buffer);
buffer[bytesWritten..].Clear();
}
}
/// <summary>
/// Sets the host address for the socket descriptor using a Utf8String instance.
/// Trailing null bytes in <paramref name="host"/> are ignored; the content must be at most
/// <see cref="HostAddressLength"/> - 1 bytes so the buffer stays null-terminated, and any
/// remaining buffer space is cleared. On failure the existing address is left unchanged.
/// </summary>
/// <param name="host">The new host address</param>
/// <exception cref="ArgumentException">The address content does not fit.</exception>
public void SetHostAddress(ReadOnlySpan<byte> host)
{
var content = host.TrimEnd((byte)0);
if (content.Length >= HostAddressLength)
throw new ArgumentException(
$"Host address must be at most {HostAddressLength - 1} bytes to leave room for the null terminator.",
nameof(host)
);
fixed (byte* ptr = HostAddress)
{
var buffer = new Span<byte>(ptr, HostAddressLength);
content.CopyTo(buffer);
buffer[content.Length..].Clear();
}
}
public override string ToString()
{
if (HostAddress[0] != 0)
{
fixed (byte* ptr = HostAddress)
{
var length = 0;
while (length < HostAddressLength && ptr[length] != 0)
length++;
var s = Encoding.UTF8.GetString(ptr, length);
return $"{s}:{Port}";
}
}
return $"{Port}";
}
// Convenience value useful when you're copying into or out of the HostAddress array.
public const int HostAddressLength = 32;
}

View file

@ -0,0 +1,34 @@
using System.Buffers.Binary;
using System.Diagnostics.Contracts;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace Brutal.RakNetApi;
public partial struct SystemAddress
{
public SystemAddress()
{
// All other fields should be initialised to their default values, which will be 0.
Address.Addr4.SinFamily = (ushort)AddressFamily.InterNetwork;
SystemIndex = unchecked((ushort)(-1));
DebugPort = 0;
}
[Pure]
public string ToString(bool includePort = false, char portDelimiter = ':')
{
unsafe
{
fixed (byte* b = &Address.Addr4.SinAddr.SUn.SUnB.SB1)
{
var ip = new IPAddress(new ReadOnlySpan<byte>(b, sizeof(SUnBSUnInAddr)));
var port = BinaryPrimitives.ReverseEndianness(Address.Addr4.SinPort);
return ip + (includePort ? $"{portDelimiter}{port}" : "");
}
}
}
public static readonly SystemAddress UNASSIGNED_SYSTEM_ADDRESS = new();
}

View file

@ -0,0 +1,190 @@
using System.Net;
using CommunityToolkit.HighPerformance;
namespace Brutal.RakNetApi.Utility;
/// <summary>
/// A utility struct for reading and writing unmanaged types to and from a buffer.
///</summary>
/// <warning>
/// 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);
/// </warning>
public ref struct Stream
{
/// <summary>
/// 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.
/// </summary>
public Stream(Span<byte> buffer)
{
_buffer = buffer;
}
#region Write
/// <summary>
/// Writes the provided value of unmanaged type <typeparamref name="T"/> into the stream at the current position.
/// Advances the writing position by the size of <typeparamref name="T"/> after writing.
/// </summary>
/// <typeparam name="T">
/// The type of the value to write. Must be unmanaged and may allow usage in a ref struct.
/// </typeparam>
/// <param name="data">
/// The value to write into the stream. Passed by reference for efficient handling of unmanaged types.
/// </param>
public unsafe void Write<T>(in T data)
where T : unmanaged
{
EnsureRemaining(sizeof(T));
RemainingAs<T>()[0] = data;
_pos += sizeof(T);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="data">The read-only span of bytes containing the data to be written.</param>
public void Write(ReadOnlySpan<byte> data)
{
data.CopyTo(Remaining());
_pos += data.Length;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="hostOrderTimestamp">The timestamp in host byte order to be included in the message.</param>
/// <param name="messageId">The unique identifier of the message being written.</param>
public void WriteTimestampMessageId(long hostOrderTimestamp, byte messageId)
{
Write((byte)DefaultMessageIDTypes.Timestamp);
Write(IPAddress.HostToNetworkOrder(hostOrderTimestamp));
Write(messageId);
}
#endregion
#region Read
/// <summary>
/// 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.
/// </summary>
/// <param name="destination">The reference to write the read data into.</param>
/// <typeparam name="T">The unmanaged type of the data to read.</typeparam>
public unsafe void Read<T>(ref T destination)
where T : unmanaged
{
EnsureRemaining(sizeof(T));
destination = RemainingAs<T>()[0];
_pos += sizeof(T);
}
/// <summary>
/// Reads and returns data of a specified unmanaged type from the current position in the buffer.
/// Updates the buffer's position after reading.
/// </summary>
/// <typeparam name="T">The unmanaged type of the data to read.</typeparam>
/// <returns>The data of the specified type read from the buffer.</returns>
public T Read<T>()
where T : unmanaged
{
T t = default;
Read(ref t);
return t;
}
/// <summary>
/// Reads a timestamp from the stream, converting it from network byte order to host byte order.
/// </summary>
/// <returns>
/// The timestamp as a <see cref="long"/> value in host byte order.
/// </returns>
public long ReadTimestamp()
{
return IPAddress.NetworkToHostOrder(Read<long>());
}
/// <summary>
/// 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.
/// </summary>
/// <returns>The message identifier as a byte.</returns>
public byte ReadMessageId()
{
return Read<byte>();
}
/// <summary>
/// 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.
///
/// </summary>
/// <param name="messageId">The message Id of the underlying message</param>
/// <param name="hostOrderTimestamp">When this method returns, contains the timestamp in host byte order if the message was timestamped; otherwise, contains 0.</param>
/// <returns>
/// <see langword="true"/> if the stream contained a timestamped message; otherwise, <see langword="false"/>.
/// </returns>
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
/// <summary>
/// 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.
/// </summary>
/// <returns>
/// A span of bytes representing the unwritten portion of the buffer, allowing direct access to the remaining space.
/// </returns>
public Span<byte> Remaining()
{
return _buffer[_pos..];
}
/// <summary>
/// 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.
/// </summary>
/// <returns>
/// A ReadOnlySpan representing the written portion of the buffer.
/// </returns>
public ReadOnlySpan<byte> Written()
{
return _buffer[.._pos];
}
private Span<T> RemainingAs<T>()
where T : unmanaged
{
return Remaining().Cast<byte, T>();
}
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<byte> _buffer;
}

View file

@ -0,0 +1,23 @@
using System.Diagnostics;
namespace Brutal.RakNetApi.Utility;
/// <summary>
/// Time-based functions for dealing with RakNet timestamps.
/// </summary>
public static class Time
{
/// <summary>
/// Computes the current timestamp in raknet units (milliseconds) based on the system's high-resolution
/// performance counter and its frequency, ensuring precise time measurements.
/// The result is returned in host byte order.
/// </summary>
///
public static long RakNetTimeMs() => (long)(Stopwatch.GetTimestamp() * RakNetTimeUnits / Stopwatch.Frequency);
public static double SecondsFromRakNetTimestamp(long rakNetTimestamp) => rakNetTimestamp / RakNetTimeUnits;
public static double TimestampNowSeconds() => (double)Stopwatch.GetTimestamp() / Stopwatch.Frequency;
private const double RakNetTimeUnits = 1000.0d; // Milliseconds
}