-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBitReader.cs
More file actions
563 lines (338 loc) · 15 KB
/
BitReader.cs
File metadata and controls
563 lines (338 loc) · 15 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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
using Gsemac.IO.Properties;
using System;
using System.IO;
using System.Text;
namespace Gsemac.IO {
public sealed class BitReader :
BinaryReader {
// Public members
public BitReader(Stream stream) :
this(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), ByteOrder.Default) {
}
public BitReader(Stream stream, ByteOrder byteOrder) :
this(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), byteOrder) {
}
public BitReader(Stream stream, Encoding encoding) :
this(stream, encoding, ByteOrder.Default) {
this.encoding = encoding;
}
public BitReader(Stream stream, Encoding encoding, ByteOrder byteOrder) :
base(stream, encoding) {
this.encoding = encoding;
this.byteOrder = byteOrder;
bytesPerChar = encoding is UnicodeEncoding ? 2 : 1;
}
public override int Read() {
char[] buffer = new char[1];
if (Read(buffer, 0, 1) <= 0)
return -1;
return buffer[0];
}
public override int Read(byte[] buffer, int index, int count) {
if (buffer is null)
throw new ArgumentNullException(nameof(buffer));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (buffer.Length - index < count)
throw new ArgumentException($"The buffer length minus {nameof(index)} is less than {nameof(count)}.");
int bytesRead = 0;
for (int i = index; i < index + count; ++i) {
if (NeedsNextByte() && !LoadNextByte())
break;
buffer[i] = ReadByte();
++bytesRead;
}
return bytesRead;
}
public override int Read(char[] buffer, int index, int count) {
if (buffer is null)
throw new ArgumentNullException(nameof(buffer));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (buffer.Length - index < count)
throw new ArgumentException($"The buffer length minus {nameof(index)} is less than {nameof(count)}.");
// This method is not trivial to implement, and BinaryReader has a far more robust implementation.
// https://github.com/microsoft/referencesource/blob/master/mscorlib/system/io/binaryreader.cs#L300
Decoder decoder = encoding.GetDecoder();
byte[] byteBuffer = new byte[bytesPerChar];
int charsRead = 0;
while (charsRead <= 0) {
int bytesRead = Read(byteBuffer, 0, byteBuffer.Length);
if (bytesRead <= 0)
return 0;
charsRead = decoder.GetChars(byteBuffer, 0, bytesRead, buffer, 0);
}
return charsRead;
}
public override bool ReadBoolean() {
if (NeedsNextByte() && !LoadNextByte())
throw new EndOfStreamException();
return (currentByte & (0x80 >> bitIndex++)) > 0;
}
public override byte ReadByte() {
if (NeedsNextByte() && !LoadNextByte())
throw new EndOfStreamException();
byte result = 0;
result |= (byte)(currentByte << bitIndex);
int bitsRequired = bitIndex;
// We either consumed the entire byte, or the remains of the byte.
if (bitsRequired > 0) {
if (!LoadNextByte())
throw new EndOfStreamException();
result |= (byte)(currentByte >> (BitsPerByte - bitsRequired));
bitIndex = (byte)bitsRequired;
}
else {
bitIndex = BitsPerByte;
}
return result;
}
public override byte[] ReadBytes(int count) {
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (count == 0)
return new byte[] { };
byte[] buffer = new byte[count];
int bytesRead = Read(buffer, 0, count);
if (bytesRead < buffer.Length) {
byte[] newBuffer = new byte[bytesRead];
Array.Copy(buffer, newBuffer, newBuffer.Length);
buffer = newBuffer;
}
return buffer;
}
public override int PeekChar() {
// BinaryReader implements by reading a character and seeking back, but this could be done more efficiently and without seeking by using a buffer.
if (!BaseStream.CanSeek)
return -1;
long position = BaseStream.Position;
int result = Read();
BaseStream.Position = position;
return result;
}
public override char ReadChar() {
int result = Read();
if (result < 0)
throw new EndOfStreamException();
return (char)result;
}
public override char[] ReadChars(int count) {
if (count <= 0)
throw new ArgumentOutOfRangeException(nameof(count));
char[] buffer = new char[count];
int charsRead = Read(buffer, 0, count);
if (charsRead < count) {
char[] newBuffer = new char[charsRead];
Array.Copy(buffer, newBuffer, newBuffer.Length);
buffer = newBuffer;
}
return buffer;
}
public override string ReadString() {
int stringLengthInBytes = Read7BitEncodedInt();
if (stringLengthInBytes < 0)
throw new IOException(string.Format(ExceptionMessages.BitReaderInvalidStringLength, stringLengthInBytes));
if (stringLengthInBytes == 0)
return string.Empty;
byte[] buffer = new byte[stringLengthInBytes];
int bytesRead = Read(buffer, 0, buffer.Length);
return encoding.GetString(buffer, 0, bytesRead);
}
public override decimal ReadDecimal() {
byte[] buffer = new byte[sizeof(decimal)];
if (Read(buffer, 0, buffer.Length) < buffer.Length)
throw new EndOfStreamException();
return BytesToDecimal(buffer);
}
public override double ReadDouble() {
byte[] buffer = new byte[sizeof(double)];
if (Read(buffer, 0, buffer.Length) < buffer.Length)
throw new EndOfStreamException();
return BitConverter.ToDouble(buffer, 0);
}
public override float ReadSingle() {
byte[] buffer = new byte[sizeof(float)];
if (Read(buffer, 0, buffer.Length) < buffer.Length)
throw new EndOfStreamException();
return BitConverter.ToSingle(buffer, 0);
}
public override short ReadInt16() {
byte[] buffer = new byte[sizeof(short)];
if (ReadOrderedBytes(buffer, 0, buffer.Length) < buffer.Length)
throw new EndOfStreamException();
return BitConverter.ToInt16(buffer, 0);
}
public override int ReadInt32() {
byte[] buffer = new byte[sizeof(int)];
if (ReadOrderedBytes(buffer, 0, buffer.Length) < buffer.Length)
throw new EndOfStreamException();
return BitConverter.ToInt32(buffer, 0);
}
public override long ReadInt64() {
byte[] buffer = new byte[sizeof(long)];
if (ReadOrderedBytes(buffer, 0, buffer.Length) < buffer.Length)
throw new EndOfStreamException();
return BitConverter.ToInt64(buffer, 0);
}
public override sbyte ReadSByte() {
return (sbyte)ReadByte();
}
public override ushort ReadUInt16() {
byte[] buffer = new byte[sizeof(ushort)];
if (ReadOrderedBytes(buffer, 0, buffer.Length) < buffer.Length)
throw new EndOfStreamException();
return BitConverter.ToUInt16(buffer, 0);
}
public override uint ReadUInt32() {
byte[] buffer = new byte[sizeof(uint)];
if (ReadOrderedBytes(buffer, 0, buffer.Length) < buffer.Length)
throw new EndOfStreamException();
return BitConverter.ToUInt32(buffer, 0);
}
public override ulong ReadUInt64() {
byte[] buffer = new byte[sizeof(ulong)];
if (ReadOrderedBytes(buffer, 0, buffer.Length) < buffer.Length)
throw new EndOfStreamException();
return BitConverter.ToUInt64(buffer, 0);
}
public byte ReadByte(int bits) {
if (bits < 0)
throw new ArgumentOutOfRangeException(nameof(bits));
byte result = 0;
for (int i = 0; i < bits; ++i) {
if (ReadBoolean())
result |= (byte)(1 << bits - i - 1);
}
return result;
}
public ushort ReadUInt16(int bits) {
byte[] buffer = new byte[sizeof(ushort)];
ReadLowOrderBits(buffer, bits);
return BitConverter.ToUInt16(buffer, 0);
}
public uint ReadUInt32(int bits) {
byte[] buffer = new byte[sizeof(uint)];
ReadLowOrderBits(buffer, bits);
return BitConverter.ToUInt32(buffer, 0);
}
public ulong ReadUInt64(int bits) {
byte[] buffer = new byte[sizeof(ulong)];
ReadLowOrderBits(buffer, bits);
return BitConverter.ToUInt64(buffer, 0);
}
// Private members
private const byte BitsPerByte = BitUtilities.BitsPerByte;
private readonly Encoding encoding;
private readonly ByteOrder byteOrder;
private int bytesPerChar;
private bool isBufferInitialized = false;
private byte currentByte = 0;
private byte bitIndex = 0;
private bool NeedsNextByte() {
return !isBufferInitialized ||
bitIndex >= BitsPerByte;
}
private bool LoadNextByte() {
int nextByteFromStream = BaseStream.ReadByte();
if (nextByteFromStream < 0)
return false;
currentByte = (byte)nextByteFromStream;
bitIndex = 0;
isBufferInitialized = true;
return true;
}
private bool IsByteReorderingRequired() {
return BitConverter.IsLittleEndian && byteOrder == ByteOrder.BigEndian ||
!BitConverter.IsLittleEndian && byteOrder == ByteOrder.LittleEndian;
}
private int ReadOrderedBytes(byte[] buffer, int index, int count) {
if (buffer is null)
throw new ArgumentNullException(nameof(buffer));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (buffer.Length - index < count)
throw new ArgumentException($"The buffer length minus {nameof(index)} is less than {nameof(count)}.");
if (count <= 0)
return 0;
int bytesRead = 0;
while (bytesRead < count) {
bytesRead += Read(buffer, index, count);
if (bytesRead <= 0)
break;
index += bytesRead;
}
if (IsByteReorderingRequired())
Array.Reverse(buffer);
return bytesRead;
}
private void ReadLowOrderBits(byte[] buffer, int numberOfBits) {
if (buffer is null)
throw new ArgumentNullException(nameof(buffer));
if (numberOfBits < 0)
throw new ArgumentOutOfRangeException(nameof(numberOfBits));
if (numberOfBits <= 0)
return;
int bytesNeeded = (int)Math.Ceiling(numberOfBits / (double)BitsPerByte);
int bitsNeeded = numberOfBits % BitsPerByte;
if (bitsNeeded > 0)
--bytesNeeded;
// Note that this method assumes that the buffer is already zeroed out.
if (byteOrder == ByteOrder.BigEndian || (byteOrder == ByteOrder.Default && !BitConverter.IsLittleEndian)) {
// Read the bytes in big endian order.
// Assume the cutoff occurred in the last partial byte.
// For example, the number 3 represented in 9 bits would look like:
// .......0
// 00000011
// Read extra bits into the end of the first partial byte.
int byteIndex = 0;
if (bitsNeeded > 0) {
byteIndex = bytesNeeded - 1;
buffer[byteIndex++] = ReadByte(bitsNeeded);
}
// Read the remaining bytes.
Read(buffer, byteIndex, bytesNeeded);
}
else {
// Read the bytes in little endian order.
// Assume the cutoff occurred in the first partial byte.
// For example, the number 3 represented in 9 bits would look like:
// 00000011
// 0.......
// Read the initial bytes.
int byteIndex = 0;
if (bytesNeeded > 0)
Read(buffer, byteIndex, bytesNeeded);
// Read extra bits into the beginning of the last partial byte.
byteIndex += bytesNeeded;
for (int i = 0; i < bitsNeeded; ++i) {
if (ReadBoolean())
buffer[byteIndex] |= (byte)(1 << numberOfBits - i - 1);
}
}
if (IsByteReorderingRequired())
Array.Reverse(buffer);
}
public static decimal BytesToDecimal(byte[] buffer) {
// The following implementation is based on decimal.ToDecimal:
// https://github.com/microsoft/referencesource/blob/master/mscorlib/system/decimal.cs#L594
if (buffer is null)
throw new ArgumentNullException(nameof(buffer));
int lo = buffer[0] | (buffer[1] << 8) | (buffer[2] << 16) | (buffer[3] << 24);
int mid = buffer[4] | (buffer[5] << 8) | (buffer[6] << 16) | (buffer[7] << 24);
int hi = buffer[8] | (buffer[9] << 8) | (buffer[10] << 16) | (buffer[11] << 24);
int flags = buffer[12] | (buffer[13] << 8) | (buffer[14] << 16) | (buffer[15] << 24);
return new decimal(new int[] {
lo,
mid,
hi,
flags,
});
}
}
}