-
Notifications
You must be signed in to change notification settings - Fork 0
/
Helper.cs
71 lines (65 loc) · 2.02 KB
/
Helper.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.IO;
using System.Text;
namespace Quras.VM
{
internal static class Helper
{
public static byte[] ReadVarBytes(this BinaryReader reader, int max = 0X7fffffc7)
{
return reader.ReadBytes((int)reader.ReadVarInt((ulong)max));
}
public static ulong ReadVarInt(this BinaryReader reader, ulong max = ulong.MaxValue)
{
byte fb = reader.ReadByte();
ulong value;
if (fb == 0xFD)
value = reader.ReadUInt16();
else if (fb == 0xFE)
value = reader.ReadUInt32();
else if (fb == 0xFF)
value = reader.ReadUInt64();
else
value = fb;
if (value > max) throw new FormatException();
return value;
}
public static string ReadVarString(this BinaryReader reader)
{
return Encoding.UTF8.GetString(reader.ReadVarBytes());
}
public static void WriteVarBytes(this BinaryWriter writer, byte[] value)
{
writer.WriteVarInt(value.Length);
writer.Write(value);
}
public static void WriteVarInt(this BinaryWriter writer, long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException();
if (value < 0xFD)
{
writer.Write((byte)value);
}
else if (value <= 0xFFFF)
{
writer.Write((byte)0xFD);
writer.Write((ushort)value);
}
else if (value <= 0xFFFFFFFF)
{
writer.Write((byte)0xFE);
writer.Write((uint)value);
}
else
{
writer.Write((byte)0xFF);
writer.Write(value);
}
}
public static void WriteVarString(this BinaryWriter writer, string value)
{
writer.WriteVarBytes(Encoding.UTF8.GetBytes(value));
}
}
}