-
Notifications
You must be signed in to change notification settings - Fork 0
/
BitBuffer.cs
105 lines (88 loc) · 2.67 KB
/
BitBuffer.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
[DebuggerDisplay("Bit = {_pos}, Byte = {CurByte}")]
internal class BitBuffer
{
private static readonly byte[] Mtbl = {0, 1, 3, 7, 15, 31, 63, 127, 255};
private readonly byte[] _buf;
private uint _pos;
public BitBuffer(byte[] data)
{
_buf = data;
}
public uint CurByte => (uint) (_pos/8.0f);
public void Seek(uint bits) => _pos += bits;
public uint ReadBits(uint bits)
{
uint ret = 0;
var left = bits;
while (left > 0)
{
var idx = _pos >> 3;
var bit = _pos & 7;
var toget = Math.Min(8 - bit, left);
var nib = (uint) (_buf[idx] >> (int) bit & Mtbl[toget]);
ret |= nib << (int) (bits - left);
_pos += toget;
left -= toget;
}
return ret;
}
public bool ReadBool()
{
return ReadBits(1) != 0;
}
public float ReadFloat() => new UIntFloat {intvalue = ReadBits(32)}.floatvalue;
public string ReadString()
{
var temp = new List<byte>();
while (true)
{
var c = (byte) ReadBits(8);
if (c == 0)
break;
temp.Add(c);
}
return Encoding.UTF8.GetString(temp.ToArray());
}
public float ReadCoord()
{
var hasint = ReadBool();
var hasfract = ReadBool();
float value = 0;
if (hasint || hasfract)
{
var sign = ReadBool();
if (hasint)
value += ReadBits(14) + 1;
if (hasfract)
value += ReadBits(5)*(1/32f);
if (sign)
value = -value;
}
return value;
}
public float[] ReadVecCoord()
{
var hasx = ReadBool();
var hasy = ReadBool();
var hasz = ReadBool();
return new[]
{
hasx ? ReadCoord() : 0,
hasy ? ReadCoord() : 0,
hasz ? ReadCoord() : 0
};
}
public uint BitsLeft()
{
// Protected from overflow
if ((_buf.Length << 3) >= _pos)
return (uint) (_buf.Length << 3) - _pos;
return 0;
}
[StructLayout(LayoutKind.Explicit)]
private struct UIntFloat
{
[FieldOffset(0)] public uint intvalue;
[FieldOffset(0)] public readonly float floatvalue;
}
}