Files
EonaCat.Connections/EonaCat.Connections/Framing/MessageFrameEncoder.cs
T
2026-11-04 07:53:40 +01:00

110 lines
3.8 KiB
C#

using EonaCat.Connections.Models;
namespace EonaCat.Connections.Framing
{
internal static class MessageFrameEncoder
{
public static byte[] Encode(byte[] payload, Configuration configuration)
{
var result = new byte[GetEncodedLength(payload, configuration)];
Write(result, payload, configuration);
return result;
}
public static int GetEncodedLength(byte[] payload, Configuration configuration)
{
if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
return checked(payload.Length + GetFramingOverhead(configuration));
}
public static int Write(byte[] buffer, byte[] payload, Configuration configuration)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (payload == null)
{
throw new ArgumentNullException(nameof(payload));
}
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
var requiredLength = GetEncodedLength(payload, configuration);
if (buffer.Length < requiredLength)
{
throw new InvalidOperationException("Buffer is too small for the framed message.");
}
var offset = 0;
if (configuration.MessageFraming == FramingMode.LengthPrefixed)
{
WriteLengthPrefix(buffer, payload.Length, configuration.LengthPrefixedLength, configuration.UseBigEndian);
offset = configuration.LengthPrefixedLength;
}
Buffer.BlockCopy(payload, 0, buffer, offset, payload.Length);
offset += payload.Length;
if (configuration.MessageFraming == FramingMode.Delimiter && configuration.Delimiter?.Length > 0)
{
Buffer.BlockCopy(configuration.Delimiter, 0, buffer, offset, configuration.Delimiter.Length);
offset += configuration.Delimiter.Length;
}
return offset;
}
private static int GetFramingOverhead(Configuration configuration)
{
return configuration.MessageFraming switch
{
FramingMode.LengthPrefixed => ValidatePrefixSize(configuration.LengthPrefixedLength),
FramingMode.Delimiter => configuration.Delimiter?.Length ?? 0,
_ => 0
};
}
private static int ValidatePrefixSize(int prefixSize)
{
if (prefixSize < 1 || prefixSize > sizeof(long))
{
throw new ArgumentOutOfRangeException(nameof(prefixSize), "Length prefix must contain between 1 and 8 bytes.");
}
return prefixSize;
}
private static void WriteLengthPrefix(byte[] buffer, int payloadLength, int prefixSize, bool useBigEndian)
{
ValidatePrefixSize(prefixSize);
var maxLength = prefixSize == sizeof(long) ? long.MaxValue : (1L << (prefixSize * 8)) - 1;
if (payloadLength > maxLength)
{
throw new InvalidOperationException("Data length exceeds length prefix capacity.");
}
long remainingLength = payloadLength;
for (var index = 0; index < prefixSize; index++)
{
var targetIndex = useBigEndian ? prefixSize - 1 - index : index;
buffer[targetIndex] = (byte)(remainingLength & 0xFF);
remainingLength >>= 8;
}
}
}
}