-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathBsonBinaryWriter.cs
733 lines (640 loc) · 25.1 KB
/
BsonBinaryWriter.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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
/* 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.Buffers.Text;
using System.Collections.Generic;
using System.IO;
namespace MongoDB.Bson.IO
{
/// <summary>
/// Represents a BSON writer to a BSON Stream.
/// </summary>
public class BsonBinaryWriter : BsonWriter
{
// private fields
#pragma warning disable CA2213 // Disposable never disposed
private readonly Stream _baseStream;
#pragma warning restore CA2213 // Disposable never disposed
private readonly BsonStream _bsonStream;
private readonly byte[] _temp10Bytes = new byte[10];
private BsonBinaryWriterContext _context;
// constructors
/// <summary>
/// Initializes a new instance of the BsonBinaryWriter class.
/// </summary>
/// <param name="stream">A stream. The BsonBinaryWriter does not own the stream and will not Dispose it.</param>
public BsonBinaryWriter(Stream stream)
: this(stream, BsonBinaryWriterSettings.Defaults)
{
}
/// <summary>
/// Initializes a new instance of the BsonBinaryWriter class.
/// </summary>
/// <param name="stream">A stream. The BsonBinaryWriter does not own the stream and will not Dispose it.</param>
/// <param name="settings">The BsonBinaryWriter settings.</param>
public BsonBinaryWriter(Stream stream, BsonBinaryWriterSettings settings)
: base(settings)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
if (!stream.CanSeek)
{
throw new ArgumentException("The stream must be capable of seeking.", "stream");
}
_baseStream = stream;
_bsonStream = (stream as BsonStream) ?? new BsonStreamAdapter(stream);
_context = null;
State = BsonWriterState.Initial;
}
// public properties
/// <summary>
/// Gets the base stream.
/// </summary>
/// <value>
/// The base stream.
/// </value>
public Stream BaseStream
{
get { return _baseStream; }
}
/// <summary>
/// Gets the BSON stream.
/// </summary>
/// <value>
/// The BSON stream.
/// </value>
public BsonStream BsonStream
{
get { return _bsonStream; }
}
/// <inheritdoc />
public override long Position
{
get { return _baseStream.Position; }
}
/// <summary>
/// Gets the settings of the writer.
/// </summary>
public new BsonBinaryWriterSettings Settings
{
get { return (BsonBinaryWriterSettings)base.Settings; }
}
// public methods
/// <summary>
/// Closes the writer. Also closes the base stream.
/// </summary>
public override void Close()
{
// Close can be called on Disposed objects
if (State != BsonWriterState.Closed)
{
if (State == BsonWriterState.Done)
{
Flush();
}
_context = null;
State = BsonWriterState.Closed;
}
}
/// <summary>
/// Flushes any pending data to the output destination.
/// </summary>
public override void Flush()
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State == BsonWriterState.Closed)
{
throw new InvalidOperationException("Flush called on closed BsonWriter.");
}
if (State != BsonWriterState.Done)
{
throw new InvalidOperationException("Flush called before BsonBinaryWriter was finished writing to buffer.");
}
_bsonStream.Flush();
}
#pragma warning disable 618 // about obsolete BsonBinarySubType.OldBinary
/// <summary>
/// Writes BSON binary data to the writer.
/// </summary>
/// <param name="binaryData">The binary data.</param>
public override void WriteBinaryData(BsonBinaryData binaryData)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteBinaryData", BsonWriterState.Value);
}
var bytes = binaryData.Bytes;
var subType = binaryData.SubType;
if (subType == BsonBinarySubType.OldBinary && Settings.FixOldBinarySubTypeOnOutput)
{
subType = BsonBinarySubType.Binary; // replace obsolete OldBinary with new Binary sub type
}
_bsonStream.WriteBsonType(BsonType.Binary);
WriteNameHelper();
if (subType == BsonBinarySubType.OldBinary)
{
// sub type OldBinary has two sizes (for historical reasons)
_bsonStream.WriteInt32(bytes.Length + 4);
_bsonStream.WriteBinarySubType(subType);
_bsonStream.WriteInt32(bytes.Length);
}
else
{
_bsonStream.WriteInt32(bytes.Length);
_bsonStream.WriteBinarySubType(subType);
}
_bsonStream.WriteBytes(bytes, 0, bytes.Length);
State = GetNextState();
}
#pragma warning restore 618
/// <summary>
/// Writes a BSON Boolean to the writer.
/// </summary>
/// <param name="value">The Boolean value.</param>
public override void WriteBoolean(bool value)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteBoolean", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.Boolean);
WriteNameHelper();
_bsonStream.WriteBoolean(value);
State = GetNextState();
}
/// <summary>
/// Writes BSON binary data to the writer.
/// </summary>
/// <param name="bytes">The bytes.</param>
public override void WriteBytes(byte[] bytes)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteBytes", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.Binary);
WriteNameHelper();
_bsonStream.WriteInt32(bytes.Length);
_bsonStream.WriteBinarySubType(BsonBinarySubType.Binary);
_bsonStream.WriteBytes(bytes, 0, bytes.Length);
State = GetNextState();
}
/// <summary>
/// Writes a BSON DateTime to the writer.
/// </summary>
/// <param name="value">The number of milliseconds since the Unix epoch.</param>
public override void WriteDateTime(long value)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteDateTime", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.DateTime);
WriteNameHelper();
_bsonStream.WriteInt64(value);
State = GetNextState();
}
/// <inheritdoc />
public override void WriteDecimal128(Decimal128 value)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState(nameof(WriteDecimal128), BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.Decimal128);
WriteNameHelper();
_bsonStream.WriteDecimal128(value);
State = GetNextState();
}
/// <summary>
/// Writes a BSON Double to the writer.
/// </summary>
/// <param name="value">The Double value.</param>
public override void WriteDouble(double value)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteDouble", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.Double);
WriteNameHelper();
_bsonStream.WriteDouble(value);
State = GetNextState();
}
/// <summary>
/// Writes the end of a BSON array to the writer.
/// </summary>
public override void WriteEndArray()
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteEndArray", BsonWriterState.Value);
}
if (_context.ContextType != ContextType.Array)
{
ThrowInvalidContextType("WriteEndArray", _context.ContextType, ContextType.Array);
}
base.WriteEndArray();
_bsonStream.WriteByte(0);
BackpatchSize(); // size of document
_context = _context.ParentContext;
State = GetNextState();
}
/// <summary>
/// Writes the end of a BSON document to the writer.
/// </summary>
public override void WriteEndDocument()
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Name)
{
ThrowInvalidState("WriteEndDocument", BsonWriterState.Name);
}
if (_context.ContextType != ContextType.Document && _context.ContextType != ContextType.ScopeDocument)
{
ThrowInvalidContextType("WriteEndDocument", _context.ContextType, ContextType.Document, ContextType.ScopeDocument);
}
base.WriteEndDocument();
_bsonStream.WriteByte(0);
BackpatchSize(); // size of document
_context = _context.ParentContext;
if (_context == null)
{
State = BsonWriterState.Done;
}
else
{
if (_context.ContextType == ContextType.JavaScriptWithScope)
{
BackpatchSize(); // size of the JavaScript with scope value
_context = _context.ParentContext;
}
State = GetNextState();
}
}
/// <summary>
/// Writes a BSON Int32 to the writer.
/// </summary>
/// <param name="value">The Int32 value.</param>
public override void WriteInt32(int value)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteInt32", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.Int32);
WriteNameHelper();
_bsonStream.WriteInt32(value);
State = GetNextState();
}
/// <summary>
/// Writes a BSON Int64 to the writer.
/// </summary>
/// <param name="value">The Int64 value.</param>
public override void WriteInt64(long value)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteInt64", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.Int64);
WriteNameHelper();
_bsonStream.WriteInt64(value);
State = GetNextState();
}
/// <summary>
/// Writes a BSON JavaScript to the writer.
/// </summary>
/// <param name="code">The JavaScript code.</param>
public override void WriteJavaScript(string code)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteJavaScript", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.JavaScript);
WriteNameHelper();
_bsonStream.WriteString(code, Settings.Encoding);
State = GetNextState();
}
/// <summary>
/// Writes a BSON JavaScript to the writer (call WriteStartDocument to start writing the scope).
/// </summary>
/// <param name="code">The JavaScript code.</param>
public override void WriteJavaScriptWithScope(string code)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteJavaScriptWithScope", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.JavaScriptWithScope);
WriteNameHelper();
_context = new BsonBinaryWriterContext(_context, ContextType.JavaScriptWithScope, _bsonStream.Position);
_bsonStream.WriteInt32(0); // reserve space for size of JavaScript with scope value
_bsonStream.WriteString(code, Settings.Encoding);
State = BsonWriterState.ScopeDocument;
}
/// <summary>
/// Writes a BSON MaxKey to the writer.
/// </summary>
public override void WriteMaxKey()
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteMaxKey", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.MaxKey);
WriteNameHelper();
State = GetNextState();
}
/// <summary>
/// Writes a BSON MinKey to the writer.
/// </summary>
public override void WriteMinKey()
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteMinKey", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.MinKey);
WriteNameHelper();
State = GetNextState();
}
/// <summary>
/// Writes a BSON null to the writer.
/// </summary>
public override void WriteNull()
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteNull", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.Null);
WriteNameHelper();
State = GetNextState();
}
/// <summary>
/// Writes a BSON ObjectId to the writer.
/// </summary>
/// <param name="objectId">The ObjectId.</param>
public override void WriteObjectId(ObjectId objectId)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteObjectId", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.ObjectId);
WriteNameHelper();
_bsonStream.WriteObjectId(objectId);
State = GetNextState();
}
/// <summary>
/// Writes a raw BSON array.
/// </summary>
/// <param name="slice">The byte buffer containing the raw BSON array.</param>
public override void WriteRawBsonArray(IByteBuffer slice)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteRawBsonArray", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.Array);
WriteNameHelper();
_bsonStream.WriteSlice(slice); // assumes slice is a valid raw BSON array
State = GetNextState();
}
/// <summary>
/// Writes a raw BSON document.
/// </summary>
/// <param name="slice">The byte buffer containing the raw BSON document.</param>
public override void WriteRawBsonDocument(IByteBuffer slice)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Initial && State != BsonWriterState.Value && State != BsonWriterState.ScopeDocument && State != BsonWriterState.Done)
{
ThrowInvalidState("WriteRawBsonDocument", BsonWriterState.Initial, BsonWriterState.Value, BsonWriterState.ScopeDocument, BsonWriterState.Done);
}
if (State == BsonWriterState.Value)
{
_bsonStream.WriteBsonType(BsonType.Document);
WriteNameHelper();
}
_bsonStream.WriteSlice(slice); // assumes byteBuffer is a valid raw BSON document
if (_context == null)
{
State = BsonWriterState.Done;
}
else
{
if (_context.ContextType == ContextType.JavaScriptWithScope)
{
BackpatchSize(); // size of the JavaScript with scope value
_context = _context.ParentContext;
}
State = GetNextState();
}
}
/// <summary>
/// Writes a BSON regular expression to the writer.
/// </summary>
/// <param name="regex">A BsonRegularExpression.</param>
public override void WriteRegularExpression(BsonRegularExpression regex)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteRegularExpression", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.RegularExpression);
WriteNameHelper();
_bsonStream.WriteCString(regex.Pattern);
_bsonStream.WriteCString(regex.Options);
State = GetNextState();
}
/// <summary>
/// Writes the start of a BSON array to the writer.
/// </summary>
public override void WriteStartArray()
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteStartArray", BsonWriterState.Value);
}
base.WriteStartArray();
_bsonStream.WriteBsonType(BsonType.Array);
WriteNameHelper();
_context = new BsonBinaryWriterContext(_context, ContextType.Array, _bsonStream.Position);
_bsonStream.WriteInt32(0); // reserve space for size
State = BsonWriterState.Value;
}
/// <summary>
/// Writes the start of a BSON document to the writer.
/// </summary>
public override void WriteStartDocument()
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Initial && State != BsonWriterState.Value && State != BsonWriterState.ScopeDocument && State != BsonWriterState.Done)
{
ThrowInvalidState("WriteStartDocument", BsonWriterState.Initial, BsonWriterState.Value, BsonWriterState.ScopeDocument, BsonWriterState.Done);
}
base.WriteStartDocument();
if (State == BsonWriterState.Value)
{
_bsonStream.WriteBsonType(BsonType.Document);
WriteNameHelper();
}
var contextType = (State == BsonWriterState.ScopeDocument) ? ContextType.ScopeDocument : ContextType.Document;
_context = new BsonBinaryWriterContext(_context, contextType, _bsonStream.Position);
_bsonStream.WriteInt32(0); // reserve space for size
State = BsonWriterState.Name;
}
/// <summary>
/// Writes a BSON String to the writer.
/// </summary>
/// <param name="value">The String value.</param>
public override void WriteString(string value)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteString", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.String);
WriteNameHelper();
_bsonStream.WriteString(value, Settings.Encoding);
State = GetNextState();
}
/// <summary>
/// Writes a BSON Symbol to the writer.
/// </summary>
/// <param name="value">The symbol.</param>
public override void WriteSymbol(string value)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteSymbol", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.Symbol);
WriteNameHelper();
_bsonStream.WriteString(value, Settings.Encoding);
State = GetNextState();
}
/// <summary>
/// Writes a BSON timestamp to the writer.
/// </summary>
/// <param name="value">The combined timestamp/increment value.</param>
public override void WriteTimestamp(long value)
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteTimestamp", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.Timestamp);
WriteNameHelper();
_bsonStream.WriteInt64(value);
State = GetNextState();
}
/// <summary>
/// Writes a BSON undefined to the writer.
/// </summary>
public override void WriteUndefined()
{
if (Disposed) { throw new ObjectDisposedException("BsonBinaryWriter"); }
if (State != BsonWriterState.Value)
{
ThrowInvalidState("WriteUndefined", BsonWriterState.Value);
}
_bsonStream.WriteBsonType(BsonType.Undefined);
WriteNameHelper();
State = GetNextState();
}
// protected methods
/// <summary>
/// Disposes of any resources used by the writer.
/// </summary>
/// <param name="disposing">True if called from Dispose.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
Close();
}
catch { } // ignore exceptions
}
base.Dispose(disposing);
}
// private methods
private void BackpatchSize()
{
var size = _bsonStream.Position - _context.StartPosition;
if (size > Settings.MaxDocumentSize)
{
var message = string.Format("Size {0} is larger than MaxDocumentSize {1}.", size, Settings.MaxDocumentSize);
throw new FormatException(message);
}
var currentPosition = _bsonStream.Position;
_bsonStream.Position = _context.StartPosition;
_bsonStream.WriteInt32((int)size);
_bsonStream.Position = currentPosition;
}
private BsonWriterState GetNextState()
{
if (_context.ContextType == ContextType.Array)
{
return BsonWriterState.Value;
}
else
{
return BsonWriterState.Name;
}
}
private void WriteNameHelper()
{
if (_context.ContextType == ContextType.Array)
{
var index = _context.Index++;
Utf8Formatter.TryFormat(index, _temp10Bytes.AsSpan(), out var bytesWritten);
_bsonStream.WriteCStringBytes(new ArraySegment<byte>(_temp10Bytes, 0, bytesWritten));
}
else
{
_bsonStream.WriteCString(Name);
}
}
}
}