summaryrefslogtreecommitdiff
path: root/Impostor-dev/src/Impostor.Benchmarks/Data/Span/MessageReader_Span.cs
blob: 5636dbed09a42f0e060906888fffc9f0be6ddc9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Buffers.Binary;
using Impostor.Hazel;

namespace Impostor.Benchmarks.Data.Span
{
    public ref struct MessageReader_Span
    {
        private readonly MessageReaderOwner _owner;
        private readonly byte _tag;
        private readonly Span<byte> _data;

        public MessageReader_Span(MessageReaderOwner owner, byte tag, Span<byte> data)
        {
            _owner = owner;
            _tag = tag;
            _data = data;
        }

        public MessageReader_Span ReadMessage()
        {
            var length = ReadUInt16();
            var tag = ReadByte();
            var pos = _owner.Position;

            _owner.Position += length;

            return new MessageReader_Span(_owner, tag, _data.Slice(3, length));
        }

        public byte ReadByte()
        {
            return _data[_owner.Position++];
        }

        public ushort ReadUInt16()
        {
            var output = BinaryPrimitives.ReadUInt16LittleEndian(_data.Slice(_owner.Position));
            _owner.Position += sizeof(ushort);
            return output;
        }

        public int ReadInt32()
        {
            var output = BinaryPrimitives.ReadInt32LittleEndian(_data.Slice(_owner.Position));
            _owner.Position += sizeof(int);
            return output;
        }
    }
}