Ejemplo n.º 1
0
        private MessageData DeserializeMessage(Span <byte> buffer, out int consumed)
        {
            consumed = 0;
            var header = new MessageHeader();

            header.MessageType     = (MessageType)buffer[0];
            buffer                 = buffer.Slice(sizeof(byte));
            consumed              += sizeof(byte);
            header.MessageLength   = NetworkBitConverter.ToUInt24(buffer);
            buffer                 = buffer.Slice(3);
            consumed              += 3;
            header.Timestamp       = NetworkBitConverter.ToUInt32(buffer);
            buffer                 = buffer.Slice(sizeof(uint));
            consumed              += sizeof(uint);
            header.MessageStreamId = header.MessageStreamId;
            // Override message stream id
            buffer    = buffer.Slice(3);
            consumed += 3;
            var offset = consumed;

            consumed += (int)header.MessageLength;

            header.Timestamp += MessageHeader.Timestamp;

            return(new MessageData()
            {
                Header = header,
                DataOffset = offset,
                DataLength = header.MessageLength
            });
        }
Ejemplo n.º 2
0
        private async Task <MessageHeader> ReadHeader(CancellationToken ct = default)
        {
            byte[] headerBuffer    = null;
            byte[] timestampBuffer = null;
            try
            {
                headerBuffer    = _arrayPool.Rent(15);
                timestampBuffer = _arrayPool.Rent(4);
                await _stream.ReadBytesAsync(headerBuffer.AsMemory(0, 15), ct);

                var type   = (MessageType)headerBuffer[4];
                var length = NetworkBitConverter.ToUInt24(headerBuffer.AsSpan(5, 3));

                headerBuffer.AsSpan(8, 3).CopyTo(timestampBuffer.AsSpan(1));
                timestampBuffer[0] = headerBuffer[11];
                var timestamp = NetworkBitConverter.ToInt32(timestampBuffer.AsSpan(0, 4));
                var streamId  = NetworkBitConverter.ToUInt24(headerBuffer.AsSpan(12, 3));
                var header    = new MessageHeader()
                {
                    MessageLength   = length,
                    MessageStreamId = streamId,
                    MessageType     = type,
                    Timestamp       = (uint)timestamp
                };
                return(header);
            }
            finally
            {
                if (headerBuffer != null)
                {
                    _arrayPool.Return(headerBuffer);
                }
                if (timestampBuffer != null)
                {
                    _arrayPool.Return(timestampBuffer);
                }
            }
        }