forked from futo-org/JustCef
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPacketReader.cs
More file actions
77 lines (62 loc) · 1.93 KB
/
PacketReader.cs
File metadata and controls
77 lines (62 loc) · 1.93 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System.Text;
namespace DotCef;
public class PacketReader
{
private byte[] _data;
private int _position;
public int RemainingSize => _data.Length - _position;
public PacketReader(byte[] data) : this(data, data.Length) { }
public PacketReader(byte[] data, int size)
{
if (size > data.Length)
throw new ArgumentException("Size must be less than data size.");
_data = data;
_position = 0;
}
public unsafe T Read<T>() where T : unmanaged
{
int sizeOfT = sizeof(T);
if (_position + sizeOfT > _data.Length)
throw new InvalidOperationException("Reading past the end of the data buffer.");
T value;
fixed (byte* ptr = &_data[_position])
{
value = *(T*)ptr;
}
_position += sizeOfT;
return value;
}
public string ReadString(int size)
{
if (_position + size > _data.Length)
throw new InvalidOperationException("Reading past the end of the data buffer.");
string result = Encoding.UTF8.GetString(_data, _position, size);
_position += size;
return result;
}
public byte[] ReadBytes(int size)
{
if (_position + size > _data.Length)
throw new InvalidOperationException("Reading past the end of the data buffer.");
byte[] result = _data.AsSpan().Slice(_position, size).ToArray();
_position += size;
return result;
}
public string? ReadSizePrefixedString()
{
int size = Read<int>();
if (size == -1)
return null;
return ReadString(size);
}
public void Skip(int size)
{
if (_position + size > _data.Length)
throw new InvalidOperationException("Skipping past the end of the data buffer.");
_position += size;
}
public bool HasAvailable(int size)
{
return _position + size <= _data.Length;
}
}