LobbyServer/LobbyServerDto/LobbyMessageIdentifier.cs

45 lines
1.4 KiB
C#

namespace LobbyServerDto
{
/// <summary>
/// Used to read the message identifer from a received object
/// </summary>
public static class LobbyMessageIdentifier
{
/// <summary>
/// Read the message identifiere from the stream
/// </summary>
/// <param name="buffer"></param>
/// <returns>The message identifier or -1 if invalid</returns>
public static int ReadLobbyMessageIdentifier(ReadOnlySpan<byte> buffer)
{
if(buffer.Length == 0)
return -1;
int typeId = 0;
int shift = 0;
int offset = 0;
byte currentByte;
do
{
if (offset < buffer.Length)
{
// Check for a corrupted stream. Read a max of 5 bytes.
// In a future version, add a DataFormatException.
if (shift == 5 * 7) // 5 bytes max per Int32, shift += 7
return -1;
// ReadByte handles end of stream cases for us.
currentByte = buffer[offset++];
typeId |= (currentByte & 0x7F) << shift;
shift += 7;
}
else
return -1;
} while ((currentByte & 0x80) != 0);
return typeId;
}
}
}