feat: implement mqtt packet-level parser and writer
This commit is contained in:
38
src/NATS.Server/Mqtt/MqttPacketWriter.cs
Normal file
38
src/NATS.Server/Mqtt/MqttPacketWriter.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
namespace NATS.Server.Mqtt;
|
||||
|
||||
public static class MqttPacketWriter
|
||||
{
|
||||
public static byte[] Write(MqttControlPacketType type, ReadOnlySpan<byte> payload, byte flags = 0)
|
||||
{
|
||||
if (type == MqttControlPacketType.Reserved)
|
||||
throw new ArgumentOutOfRangeException(nameof(type), "MQTT control packet type must be non-zero.");
|
||||
|
||||
var remainingLength = payload.Length;
|
||||
var encodedRemainingLength = EncodeRemainingLength(remainingLength);
|
||||
var buffer = new byte[1 + encodedRemainingLength.Length + remainingLength];
|
||||
buffer[0] = (byte)(((byte)type << 4) | (flags & 0x0F));
|
||||
encodedRemainingLength.CopyTo(buffer.AsSpan(1));
|
||||
payload.CopyTo(buffer.AsSpan(1 + encodedRemainingLength.Length));
|
||||
return buffer;
|
||||
}
|
||||
|
||||
internal static byte[] EncodeRemainingLength(int value)
|
||||
{
|
||||
if (value < 0 || value > 268_435_455)
|
||||
throw new ArgumentOutOfRangeException(nameof(value), "MQTT remaining length must be between 0 and 268435455.");
|
||||
|
||||
Span<byte> scratch = stackalloc byte[4];
|
||||
var index = 0;
|
||||
|
||||
do
|
||||
{
|
||||
var digit = (byte)(value % 128);
|
||||
value /= 128;
|
||||
if (value > 0)
|
||||
digit |= 0x80;
|
||||
scratch[index++] = digit;
|
||||
} while (value > 0);
|
||||
|
||||
return scratch[..index].ToArray();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user