-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer.cs
52 lines (44 loc) · 1.2 KB
/
buffer.cs
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
using System.Text;
namespace Bufferprotocol;
internal class BufferProtocol
{
private readonly MemoryStream buffer = new ();
private void WriteVarint(long val)
{
do
{
byte b = (byte)(val & 0X7F);
val >>= 7; // Extracting the remaining 7 bits
if(val != 0)
b |= 0x80;
buffer.WriteByte(b);
}while(val != 0);
}
// Creating the header
private void WriteField(int field, byte wire)
{
long fieldIntoBytes = (long)field << 3;
long wireIntoBytes = (long)wire & 0x07;
long val = fieldIntoBytes | wireIntoBytes;
WriteVarint(val);
}
public BufferProtocol AddNumber(int field, long val)
{
WriteField(field, 0);
WriteVarint(val);
return this;
}
public BufferProtocol AddBytes(int field, byte[] bytes)
{
WriteField(field, 2);
WriteVarint(bytes.Length);
buffer.Write(bytes, 0, bytes.Length);
return this;
}
public BufferProtocol AddString(int field, string str)
{
AddBytes(field, Encoding.UTF8.GetBytes(str));
return this;
}
public byte[] ToBytesArray() => buffer.ToArray();
}