-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathBsonStreamAdapter.cs
559 lines (492 loc) · 15.6 KB
/
BsonStreamAdapter.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
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
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using System.Text;
using System.Buffers.Binary;
using System.Threading;
using System.Threading.Tasks;
namespace MongoDB.Bson.IO
{
/// <summary>
/// A Stream that wraps another Stream while implementing the BsonStream abstract methods.
/// </summary>
public sealed class BsonStreamAdapter : BsonStream
{
// fields
private bool _disposed;
private bool _ownsStream;
private readonly Stream _stream;
private readonly byte[] _temp = new byte[12];
// constructors
/// <summary>
/// Initializes a new instance of the <see cref="BsonStreamAdapter"/> class.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="ownsStream">if set to <c>true</c> [owns stream].</param>
/// <exception cref="System.ArgumentNullException">stream</exception>
public BsonStreamAdapter(Stream stream, bool ownsStream = false)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
_stream = stream;
_ownsStream = ownsStream;
}
// properties
/// <summary>
/// Gets the base stream.
/// </summary>
/// <value>
/// The base stream.
/// </value>
public Stream BaseStream
{
get
{
ThrowIfDisposed();
return _stream;
}
}
/// <inheritdoc/>
public override bool CanRead
{
get
{
ThrowIfDisposed();
return _stream.CanRead;
}
}
/// <inheritdoc/>
public override bool CanSeek
{
get
{
ThrowIfDisposed();
return _stream.CanSeek;
}
}
/// <inheritdoc/>
public override bool CanTimeout
{
get
{
ThrowIfDisposed();
return _stream.CanTimeout;
}
}
/// <inheritdoc/>
public override bool CanWrite
{
get
{
ThrowIfDisposed();
return _stream.CanWrite;
}
}
/// <inheritdoc/>
public override long Length
{
get
{
ThrowIfDisposed();
return _stream.Length;
}
}
/// <inheritdoc/>
public override long Position
{
get
{
ThrowIfDisposed();
return _stream.Position;
}
set
{
ThrowIfDisposed();
_stream.Position = value;
}
}
/// <inheritdoc/>
public override int ReadTimeout
{
get
{
ThrowIfDisposed();
return _stream.ReadTimeout;
}
set
{
ThrowIfDisposed();
_stream.ReadTimeout = value;
}
}
/// <inheritdoc/>
public override int WriteTimeout
{
get
{
ThrowIfDisposed();
return _stream.WriteTimeout;
}
set
{
ThrowIfDisposed();
_stream.WriteTimeout = value;
}
}
// methods
/// <inheritdoc/>
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
ThrowIfDisposed();
return _stream.BeginRead(buffer, offset, count, callback, state);
}
/// <inheritdoc/>
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
ThrowIfDisposed();
return _stream.BeginWrite(buffer, offset, count, callback, state);
}
/// <inheritdoc/>
public override void Close()
{
base.Close(); // base class will call Dispose
}
/// <inheritdoc/>
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
ThrowIfDisposed();
return _stream.CopyToAsync(destination, bufferSize, cancellationToken);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_ownsStream)
{
_stream.Dispose();
}
}
_disposed = true;
}
base.Dispose(disposing);
}
/// <inheritdoc/>
public override int EndRead(IAsyncResult asyncResult)
{
ThrowIfDisposed();
return _stream.EndRead(asyncResult);
}
/// <inheritdoc/>
public override void EndWrite(IAsyncResult asyncResult)
{
ThrowIfDisposed();
_stream.EndWrite(asyncResult);
}
/// <inheritdoc/>
public override void Flush()
{
ThrowIfDisposed();
_stream.Flush();
}
/// <inheritdoc/>
public override Task FlushAsync(CancellationToken cancellationToken)
{
ThrowIfDisposed();
return _stream.FlushAsync(cancellationToken);
}
/// <inheritdoc/>
public override int Read(byte[] buffer, int offset, int count)
{
ThrowIfDisposed();
return _stream.Read(buffer, offset, count);
}
/// <inheritdoc/>
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ThrowIfDisposed();
return _stream.ReadAsync(buffer, offset, count, cancellationToken);
}
/// <inheritdoc/>
public override int ReadByte()
{
ThrowIfDisposed();
return _stream.ReadByte();
}
/// <inheritdoc/>
public override string ReadCString(UTF8Encoding encoding)
{
if (encoding == null)
{
throw new ArgumentNullException("encoding");
}
ThrowIfDisposed();
var bytes = ReadCStringBytes();
return Utf8Helper.DecodeUtf8String(bytes.Array, 0, bytes.Count, encoding);
}
/// <inheritdoc/>
public override ArraySegment<byte> ReadCStringBytes()
{
ThrowIfDisposed();
var memoryStream = new MemoryStream(32);
while (true)
{
var b = _stream.ReadByte();
if (b == -1)
{
throw new EndOfStreamException();
}
if (b == 0)
{
byte[] memoryStreamBuffer;
memoryStreamBuffer = memoryStream.GetBuffer();
return new ArraySegment<byte>(memoryStreamBuffer, 0, (int)memoryStream.Length);
}
memoryStream.WriteByte((byte)b);
}
}
/// <inheritdoc/>
public override Decimal128 ReadDecimal128()
{
ThrowIfDisposed();
var lowBits = (ulong)ReadInt64();
var highBits = (ulong)ReadInt64();
return Decimal128.FromIEEEBits(highBits, lowBits);
}
/// <inheritdoc/>
public override double ReadDouble()
{
ThrowIfDisposed();
this.ReadBytes(_temp, 0, 8);
return BinaryPrimitivesCompat.ReadDoubleLittleEndian(_temp);
}
/// <inheritdoc/>
public override int ReadInt32()
{
ThrowIfDisposed();
this.ReadBytes(_temp, 0, 4);
return _temp[0] | (_temp[1] << 8) | (_temp[2] << 16) | (_temp[3] << 24);
}
/// <inheritdoc/>
public override long ReadInt64()
{
ThrowIfDisposed();
this.ReadBytes(_temp, 0, 8);
return BinaryPrimitives.ReadInt64LittleEndian(_temp);
}
/// <inheritdoc/>
public override ObjectId ReadObjectId()
{
ThrowIfDisposed();
this.ReadBytes(_temp, 0, 12);
return new ObjectId(_temp, 0);
}
/// <inheritdoc/>
public override IByteBuffer ReadSlice()
{
ThrowIfDisposed();
var position = _stream.Position;
var length = ReadInt32();
var bytes = new byte[length];
_stream.Position = position;
this.ReadBytes(bytes, 0, length);
return new ByteArrayBuffer(bytes, isReadOnly: true);
}
/// <inheritdoc/>
public override string ReadString(UTF8Encoding encoding)
{
if (encoding == null)
{
throw new ArgumentNullException("encoding");
}
ThrowIfDisposed();
var length = ReadInt32();
using var rentedBuffer = ThreadStaticBuffer.RentBuffer(length);
var bytes = rentedBuffer.Bytes;
this.ReadBytes(bytes, 0, length);
if (bytes[length - 1] != 0)
{
throw new FormatException("String is missing terminating null byte.");
}
return encoding.GetString(bytes, 0, length - 1);
}
/// <inheritdoc/>
public override long Seek(long offset, SeekOrigin origin)
{
ThrowIfDisposed();
return _stream.Seek(offset, origin);
}
/// <inheritdoc/>
public override void SetLength(long value)
{
ThrowIfDisposed();
_stream.SetLength(value);
}
/// <inheritdoc/>
public override void SkipCString()
{
ThrowIfDisposed();
while (true)
{
var b = _stream.ReadByte();
if (b == -1)
{
throw new EndOfStreamException();
}
if (b == 0)
{
return;
}
}
}
/// <inheritdoc/>
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
/// <inheritdoc/>
public override void Write(byte[] buffer, int offset, int count)
{
ThrowIfDisposed();
_stream.Write(buffer, offset, count);
}
/// <inheritdoc/>
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ThrowIfDisposed();
return _stream.WriteAsync(buffer, offset, count, cancellationToken);
}
/// <inheritdoc/>
public override void WriteByte(byte value)
{
ThrowIfDisposed();
_stream.WriteByte(value);
}
/// <inheritdoc/>
public override void WriteCString(string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
ThrowIfDisposed();
// Compare to 128 to preserve original behavior
const int maxLengthToUseCStringUtf8EncodingWith = 128;
if (CStringUtf8Encoding.GetMaxByteCount(value.Length) <= maxLengthToUseCStringUtf8EncodingWith)
{
using var rentedBuffer = ThreadStaticBuffer.RentBuffer(maxLengthToUseCStringUtf8EncodingWith);
var length = CStringUtf8Encoding.GetBytes(value, rentedBuffer.Bytes, 0, Utf8Encodings.Strict);
WriteBytes(rentedBuffer.Bytes, length);
}
else
{
using var rentedSegment = Utf8Encodings.Strict.GetBytesUsingThreadStaticBuffer(value);
var segment = rentedSegment.Segment;
if (Array.IndexOf<byte>(segment.Array, 0, 0, segment.Count) != -1)
{
throw new ArgumentException("A CString cannot contain null bytes.", "value");
}
WriteBytes(segment.Array, segment.Count);
}
void WriteBytes(byte[] bytes, int length)
{
_stream.Write(bytes, 0, length);
_stream.WriteByte(0);
}
}
/// <inheritdoc/>
public override void WriteCStringBytes(byte[] value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
ThrowIfDisposed();
this.WriteBytes(value, 0, value.Length);
WriteByte(0);
}
/// <inheritdoc/>
public override void WriteCStringBytes(ArraySegment<byte> value)
{
ThrowIfDisposed();
this.WriteBytes(value.Array, value.Offset, value.Count);
WriteByte(0);
}
/// <inheritdoc/>
public override void WriteDecimal128(Decimal128 value)
{
ThrowIfDisposed();
WriteInt64((long)value.GetIEEELowBits());
WriteInt64((long)value.GetIEEEHighBits());
}
/// <inheritdoc/>
public override void WriteDouble(double value)
{
ThrowIfDisposed();
BinaryPrimitivesCompat.WriteDoubleLittleEndian(_temp, value);
_stream.Write(_temp, 0, 8);
}
/// <inheritdoc/>
public override void WriteInt32(int value)
{
ThrowIfDisposed();
_temp[0] = (byte)(value);
_temp[1] = (byte)(value >> 8);
_temp[2] = (byte)(value >> 16);
_temp[3] = (byte)(value >> 24);
_stream.Write(_temp, 0, 4);
}
/// <inheritdoc/>
public override void WriteInt64(long value)
{
ThrowIfDisposed();
BinaryPrimitives.WriteInt64LittleEndian(_temp, value);
_stream.Write(_temp, 0, 8);
}
/// <inheritdoc/>
public override void WriteObjectId(ObjectId value)
{
ThrowIfDisposed();
value.ToByteArray(_temp, 0);
_stream.Write(_temp, 0, 12);
}
/// <inheritdoc/>
public override void WriteString(string value, UTF8Encoding encoding)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (encoding == null)
{
throw new ArgumentNullException("encoding");
}
ThrowIfDisposed();
using var rentedSegment = encoding.GetBytesUsingThreadStaticBuffer(value);
var segment = rentedSegment.Segment;
WriteInt32(segment.Count + 1);
_stream.Write(segment.Array, 0, segment.Count);
_stream.WriteByte(0);
}
}
}