-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBitWriter.cs
More file actions
450 lines (280 loc) · 12.4 KB
/
BitWriter.cs
File metadata and controls
450 lines (280 loc) · 12.4 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
using System;
using System.IO;
using System.Linq;
using System.Text;
namespace Gsemac.IO {
// TODO: Implementing seeking (by bytes and bits), and implementing reading bytes from the stream to modify their bits.
// For now, this class works best for writing to a stream that doesn't already contain data.
public sealed class BitWriter :
BinaryWriter {
// Public members
public BitWriter(Stream stream) :
this(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), ByteOrder.Default) {
}
public BitWriter(Stream stream, ByteOrder byteOrder) :
this(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), byteOrder) {
}
public BitWriter(Stream stream, Encoding encoding) :
this(stream, encoding, ByteOrder.Default) {
}
public BitWriter(Stream stream, Encoding encoding, bool leaveOpen) :
this(stream, encoding, ByteOrder.Default, leaveOpen) {
}
public BitWriter(Stream stream, Encoding encoding, ByteOrder byteOrder) :
this(stream, encoding, byteOrder, leaveOpen: false) {
}
public BitWriter(Stream stream, Encoding encoding, ByteOrder byteOrder, bool leaveOpen) :
base(stream, encoding) {
this.encoding = encoding;
this.byteOrder = byteOrder;
this.leaveOpen = leaveOpen;
}
public override void Write(bool value) {
WriteBit(value);
}
public override void Write(byte value) {
// The bit index will always remain the same after writing a byte.
byte previousBitIndex = bitIndex;
currentByte |= (byte)(value >> bitIndex);
CommitByte();
currentByte |= (byte)(value << (BitsPerByte - previousBitIndex));
bitIndex = previousBitIndex;
}
public override void Write(byte[] buffer) {
if (buffer is null)
throw new ArgumentNullException(nameof(buffer));
Write(buffer, 0, buffer.Length);
}
public override void Write(byte[] buffer, int index, int count) {
if (buffer is null)
throw new ArgumentNullException(nameof(buffer));
if (index < 0 || index >= buffer.Length || count < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (buffer.Length - index < count)
throw new ArgumentException($"The buffer length minus {nameof(index)} is less than {nameof(count)}.");
for (int i = index; i < index + count; ++i)
Write(buffer[i]);
}
public override void Write(char ch) {
Write(encoding.GetBytes(new char[] { ch }, 0, 1));
}
public override void Write(char[] chars) {
if (chars is null)
throw new ArgumentNullException(nameof(chars));
Write(chars, 0, chars.Length);
}
public override void Write(char[] chars, int index, int count) {
if (chars is null)
throw new ArgumentNullException(nameof(chars));
if (index < 0 || index >= chars.Length || count < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (chars.Length - index < count)
throw new ArgumentException($"The buffer length minus {nameof(index)} is less than {nameof(count)}.");
for (int i = index; i < index + count; ++i)
Write(chars[i]);
}
public override void Write(string value) {
if (value is null)
throw new ArgumentNullException(nameof(value));
// BinaryWriter writes the string prefixed with a 7-bit encoded integer length.
Write7BitEncodedInt(encoding.GetByteCount(value));
Write(encoding.GetBytes(value));
}
public override void Write(decimal value) {
// Note that the byte order for a decimal is the same regardless of endianess.
// https://github.com/microsoft/referencesource/blob/master/mscorlib/system/decimal.cs#L567
byte[] buffer = DecimalToBytes(value);
Write(buffer, 0, buffer.Length);
}
public override void Write(double value) {
Write(BitConverter.GetBytes(value));
}
public override void Write(float value) {
Write(BitConverter.GetBytes(value));
}
public override void Write(int value) {
WriteOrderedBytes(BitConverter.GetBytes(value));
}
public override void Write(long value) {
WriteOrderedBytes(BitConverter.GetBytes(value));
}
public override void Write(sbyte value) {
WriteOrderedBytes(BitConverter.GetBytes(value));
}
public override void Write(short value) {
WriteOrderedBytes(BitConverter.GetBytes(value));
}
public override void Write(uint value) {
WriteOrderedBytes(BitConverter.GetBytes(value));
}
public override void Write(ulong value) {
WriteOrderedBytes(BitConverter.GetBytes(value));
}
public override void Write(ushort value) {
WriteOrderedBytes(BitConverter.GetBytes(value));
}
public void Write(byte value, int bits) {
if (bits < 0)
throw new ArgumentOutOfRangeException(nameof(bits));
if (bits <= 0)
return;
// Write the N low order bits.
for (int i = 0; i < bits; ++i) {
WriteBit((value & (1 << (bits - i - 1))) > 0);
}
}
public void Write(uint value, int bits) {
WriteLowOrderBits(BitConverter.GetBytes(value), bits);
}
public void Write(ulong value, int bits) {
WriteLowOrderBits(BitConverter.GetBytes(value), bits);
}
public void Write(ushort value, int bits) {
WriteLowOrderBits(BitConverter.GetBytes(value), bits);
}
public override void Flush() {
if (bitIndex > 0)
CommitByte();
base.Flush();
}
public override void Close() {
Flush();
base.Close();
}
// Protected members
protected override void Dispose(bool disposing) {
if (disposing) {
// We only flush instead of closing.
// The underlying BinaryWriter does not call Close() when disposing.
Flush();
}
// Calling Dispose on the base BinaryReader will also close the underlying stream.
// .NET 4.5 added a "leaveOpen" parameter to avoid this behavior, but this parameter isn't present in .NET 4.0.
// Since calling Dispose only closes the underlying stream, it's safe to skip it to avoid closing the stream.
// https://stackoverflow.com/a/1084828/5383169
if (!leaveOpen)
base.Dispose(disposing);
}
// Private members
private const byte BitsPerByte = BitUtilities.BitsPerByte;
private readonly Encoding encoding;
private readonly ByteOrder byteOrder;
private readonly bool leaveOpen = false;
private byte currentByte = 0;
private byte bitIndex = 0;
private void WriteBit(bool value) {
byte bitMask = (byte)(0x80 >> bitIndex);
if (value) {
currentByte |= bitMask;
}
else {
currentByte &= (byte)~bitMask;
}
if (++bitIndex >= 8)
CommitByte();
}
private void WriteBits(byte value, int startIndex, int count) {
for (int j = startIndex; j < Math.Min(startIndex + count, BitsPerByte); ++j) {
WriteBit((value & (0x80 >> j)) > 0);
}
}
private void WriteLowOrderBits(byte[] bytes, int numberOfBits) {
if (bytes is null)
throw new ArgumentNullException(nameof(bytes));
if (numberOfBits < 0)
throw new ArgumentOutOfRangeException(nameof(numberOfBits));
if (numberOfBits <= 0)
return;
// If we're on a little endian system, we want to write the first N bytes.
// If we're on a big endian system, we want to write the last N bytes.
// For simplicity, we'll just normalize our byte array to little endian.
bytes = ToLittleEndian(bytes);
if (byteOrder == ByteOrder.BigEndian || (byteOrder == ByteOrder.Default && !BitConverter.IsLittleEndian)) {
// Write the bytes in big endian order.
// If we're writing a partial byte, we want the cutoff in the last partial byte.
// The number 3 represented in 9 bits would look like:
// .......0
// 00000011
int bitIndex = (BitsPerByte - numberOfBits % BitsPerByte) % BitsPerByte;
int byteIndex = Math.Max(Math.Min(numberOfBits / BitsPerByte, bytes.Length), 1) - 1;
for (int i = byteIndex; i >= 0; --i) {
WriteBits(bytes[i], bitIndex, BitsPerByte - bitIndex);
bitIndex = 0;
}
}
else {
// Write the bytes in little endian order.
// If we're writing a partial byte, we want the cutoff in the first partial byte.
// The number 3 represented in 9 bits would look like:
// 00000011
// 0.......
int byteIndex = 0;
int totalBytes = (int)Math.Ceiling(numberOfBits / (double)BitsPerByte);
for (int i = byteIndex; i < totalBytes; ++i) {
bool isLastIteration = i + 1 >= totalBytes;
int bitIndex = isLastIteration ?
(BitsPerByte - numberOfBits % BitsPerByte) % BitsPerByte :
0;
WriteBits(bytes[i], bitIndex, BitsPerByte - bitIndex);
}
}
}
private bool IsByteReorderingRequired() {
return BitConverter.IsLittleEndian && byteOrder == ByteOrder.BigEndian ||
!BitConverter.IsLittleEndian && byteOrder == ByteOrder.LittleEndian;
}
private byte[] ToLittleEndian(byte[] bytes) {
if (bytes is null)
throw new ArgumentNullException(nameof(bytes));
if (!BitConverter.IsLittleEndian)
return bytes.Reverse().ToArray();
return bytes;
}
private void WriteOrderedBytes(byte[] bytes) {
if (bytes is null)
throw new ArgumentNullException(nameof(bytes));
if (bytes.Length <= 0)
return;
if (IsByteReorderingRequired()) {
for (int i = bytes.Length - 1; i >= 0; --i) {
Write(bytes[i]);
}
}
else {
Write(bytes);
}
}
private void CommitByte() {
base.Write(currentByte);
currentByte = 0;
bitIndex = 0;
}
public static byte[] DecimalToBytes(decimal value) {
// The following implementation is based on decimal.GetBytes:
// https://github.com/microsoft/referencesource/blob/master/mscorlib/system/decimal.cs#L571
byte[] buffer = new byte[16];
int[] bits = decimal.GetBits(value);
// lo
buffer[0] = (byte)bits[0];
buffer[1] = (byte)(bits[0] >> 8);
buffer[2] = (byte)(bits[0] >> 16);
buffer[3] = (byte)(bits[0] >> 24);
// mid
buffer[4] = (byte)bits[1];
buffer[5] = (byte)(bits[1] >> 8);
buffer[6] = (byte)(bits[1] >> 16);
buffer[7] = (byte)(bits[1] >> 24);
// hi
buffer[8] = (byte)bits[2];
buffer[9] = (byte)(bits[2] >> 8);
buffer[10] = (byte)(bits[2] >> 16);
buffer[11] = (byte)(bits[2] >> 24);
// flags
buffer[12] = (byte)bits[3];
buffer[13] = (byte)(bits[3] >> 8);
buffer[14] = (byte)(bits[3] >> 16);
buffer[15] = (byte)(bits[3] >> 24);
return buffer;
}
}
}