-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathBsonReader.cs
More file actions
498 lines (435 loc) · 17.3 KB
/
BsonReader.cs
File metadata and controls
498 lines (435 loc) · 17.3 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
/* 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.Collections.Generic;
using System.IO;
using System.Linq;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
namespace MongoDB.Bson.IO
{
/// <summary>
/// Represents a BSON reader for some external format (see subclasses).
/// </summary>
public abstract class BsonReader : IBsonReader
{
// private fields
private bool _disposed = false;
private BsonReaderSettings _settings;
private BsonReaderState _state;
private BsonType _currentBsonType;
private string _currentName;
private readonly Stack<BsonReaderSettings> _settingsStack = new Stack<BsonReaderSettings>();
// constructors
/// <summary>
/// Initializes a new instance of the BsonReader class.
/// </summary>
/// <param name="settings">The reader settings.</param>
protected BsonReader(BsonReaderSettings settings)
{
if (settings == null)
{
throw new ArgumentNullException("settings");
}
_settings = settings.FrozenCopy();
_state = BsonReaderState.Initial;
}
// public properties
/// <summary>
/// Gets the current BsonType.
/// </summary>
public BsonType CurrentBsonType
{
get { return _currentBsonType; }
protected set { _currentBsonType = value; }
}
/// <summary>
/// Gets the settings of the reader.
/// </summary>
public BsonReaderSettings Settings
{
get { return _settings; }
}
/// <summary>
/// Gets the current state of the reader.
/// </summary>
public BsonReaderState State
{
get { return _state; }
protected set { _state = value; }
}
// protected properties
/// <summary>
/// Gets the current name.
/// </summary>
protected string CurrentName
{
get { return _currentName; }
set { _currentName = value; }
}
/// <summary>
/// Gets whether the BsonReader has been disposed.
/// </summary>
protected bool Disposed
{
get { return _disposed; }
}
// public methods
/// <summary>
/// Closes the reader.
/// </summary>
public abstract void Close();
/// <summary>
/// Disposes of any resources used by the reader.
/// </summary>
public void Dispose()
{
if (!_disposed)
{
Dispose(true);
_disposed = true;
}
}
/// <summary>
/// Gets a bookmark to the reader's current position and state.
/// </summary>
/// <returns>A bookmark.</returns>
public abstract BsonReaderBookmark GetBookmark();
/// <summary>
/// Gets the current BsonType (calls ReadBsonType if necessary).
/// </summary>
/// <returns>The current BsonType.</returns>
public BsonType GetCurrentBsonType()
{
if (_state == BsonReaderState.Initial || _state == BsonReaderState.ScopeDocument || _state == BsonReaderState.Type)
{
ReadBsonType();
}
if (_state != BsonReaderState.Value)
{
ThrowInvalidState("GetCurrentBsonType", BsonReaderState.Value);
}
return _currentBsonType;
}
/// <summary>
/// Determines whether this reader is at end of file.
/// </summary>
/// <returns>
/// Whether this reader is at end of file.
/// </returns>
public abstract bool IsAtEndOfFile();
/// <inheritdoc/>
public void PopSettings()
{
_settings = _settingsStack.Pop();
}
/// <inheritdoc/>
public void PushSettings(Action<BsonReaderSettings> configurator)
{
var newSettings = _settings.Clone();
configurator(newSettings);
newSettings.Freeze();
_settingsStack.Push(_settings);
_settings = newSettings;
}
/// <summary>
/// Reads BSON binary data from the reader.
/// </summary>
/// <returns>A BsonBinaryData.</returns>
public abstract BsonBinaryData ReadBinaryData();
/// <summary>
/// Reads a BSON boolean from the reader.
/// </summary>
/// <returns>A Boolean.</returns>
public abstract bool ReadBoolean();
/// <summary>
/// Reads a BsonType from the reader.
/// </summary>
/// <returns>A BsonType.</returns>
public abstract BsonType ReadBsonType();
/// <summary>
/// Reads BSON binary data from the reader.
/// </summary>
/// <returns>A byte array.</returns>
public abstract byte[] ReadBytes();
/// <summary>
/// Reads a BSON DateTime from the reader.
/// </summary>
/// <returns>The number of milliseconds since the Unix epoch.</returns>
public abstract long ReadDateTime();
/// <inheritdoc />
public abstract Decimal128 ReadDecimal128();
/// <summary>
/// Reads a BSON Double from the reader.
/// </summary>
/// <returns>A Double.</returns>
public abstract double ReadDouble();
/// <summary>
/// Reads the end of a BSON array from the reader.
/// </summary>
public abstract void ReadEndArray();
/// <summary>
/// Reads the end of a BSON document from the reader.
/// </summary>
public abstract void ReadEndDocument();
/// <inheritdoc/>
public virtual Guid ReadGuid()
{
var binaryData = ReadBinaryData();
var bytes = binaryData.Bytes;
var subType = binaryData.SubType;
if (subType != BsonBinarySubType.UuidStandard)
{
throw new FormatException($"GuidRepresentation is unknown for binary subtype {binaryData.SubType}.");
}
if (bytes.Length != 16)
{
throw new FormatException($"Expected length to be 16, not {bytes.Length}.");
}
return GuidConverter.FromBytes(bytes, GuidRepresentation.Standard);
}
/// <inheritdoc/>
public virtual Guid ReadGuid(GuidRepresentation guidRepresentation)
{
var binaryData = ReadBinaryData();
var bytes = binaryData.Bytes;
var subType = binaryData.SubType;
var expectedSubType = GuidConverter.GetSubType(guidRepresentation);
if (subType != expectedSubType)
{
throw new FormatException($"Expected BsonBinarySubType to be {expectedSubType}, but it is {subType}.");
}
if (bytes.Length != 16)
{
throw new FormatException($"Expected length to be 16, not {bytes.Length}.");
}
return GuidConverter.FromBytes(bytes, guidRepresentation);
}
/// <summary>
/// Reads a BSON Int32 from the reader.
/// </summary>
/// <returns>An Int32.</returns>
public abstract int ReadInt32();
/// <summary>
/// Reads a BSON Int64 from the reader.
/// </summary>
/// <returns>An Int64.</returns>
public abstract long ReadInt64();
/// <summary>
/// Reads a BSON JavaScript from the reader.
/// </summary>
/// <returns>A string.</returns>
public abstract string ReadJavaScript();
/// <summary>
/// Reads a BSON JavaScript with scope from the reader (call ReadStartDocument next to read the scope).
/// </summary>
/// <returns>A string.</returns>
public abstract string ReadJavaScriptWithScope();
/// <summary>
/// Reads a BSON MaxKey from the reader.
/// </summary>
public abstract void ReadMaxKey();
/// <summary>
/// Reads a BSON MinKey from the reader.
/// </summary>
public abstract void ReadMinKey();
/// <summary>
/// Reads the name of an element from the reader.
/// </summary>
/// <returns>The name of the element.</returns>
public virtual string ReadName()
{
return ReadName(Utf8NameDecoder.Instance);
}
/// <summary>
/// Reads the name of an element from the reader (using the provided name decoder).
/// </summary>
/// <param name="nameDecoder">The name decoder.</param>
/// <returns>
/// The name of the element.
/// </returns>
public abstract string ReadName(INameDecoder nameDecoder);
/// <summary>
/// Reads a BSON null from the reader.
/// </summary>
public abstract void ReadNull();
/// <summary>
/// Reads a BSON ObjectId from the reader.
/// </summary>
/// <returns>An ObjectId.</returns>
public abstract ObjectId ReadObjectId();
/// <summary>
/// Reads a raw BSON array.
/// </summary>
/// <returns>The raw BSON array.</returns>
public virtual IByteBuffer ReadRawBsonArray()
{
// overridden in BsonBinaryReader to read the raw bytes from the stream
// for all other streams, deserialize the array and reserialize it using a BsonBinaryWriter to get the raw bytes
var deserializationContext = BsonDeserializationContext.CreateRoot(this);
var array = BsonArraySerializer.Instance.Deserialize(deserializationContext);
using (var memoryStream = new MemoryStream())
using (var bsonWriter = new BsonBinaryWriter(memoryStream, BsonBinaryWriterSettings.Defaults))
{
var serializationContext = BsonSerializationContext.CreateRoot(bsonWriter);
bsonWriter.WriteStartDocument();
var startPosition = memoryStream.Position + 3; // just past BsonType, "x" and null byte
bsonWriter.WriteName("x");
BsonArraySerializer.Instance.Serialize(serializationContext, array);
var endPosition = memoryStream.Position;
bsonWriter.WriteEndDocument();
byte[] memoryStreamBuffer;
memoryStreamBuffer = memoryStream.GetBuffer();
var buffer = new ByteArrayBuffer(memoryStreamBuffer, (int)memoryStream.Length, isReadOnly: true);
return new ByteBufferSlice(buffer, (int)startPosition, (int)(endPosition - startPosition));
}
}
/// <summary>
/// Reads a raw BSON document.
/// </summary>
/// <returns>The raw BSON document.</returns>
public virtual IByteBuffer ReadRawBsonDocument()
{
// overridden in BsonBinaryReader to read the raw bytes from the stream
// for all other streams, deserialize the document and use ToBson to get the raw bytes
var deserializationContext = BsonDeserializationContext.CreateRoot(this);
var document = BsonDocumentSerializer.Instance.Deserialize(deserializationContext);
var bytes = document.ToBson();
return new ByteArrayBuffer(bytes, isReadOnly: true);
}
/// <summary>
/// Reads a BSON regular expression from the reader.
/// </summary>
/// <returns>A BsonRegularExpression.</returns>
public abstract BsonRegularExpression ReadRegularExpression();
/// <summary>
/// Reads the start of a BSON array.
/// </summary>
public abstract void ReadStartArray();
/// <summary>
/// Reads the start of a BSON document.
/// </summary>
public abstract void ReadStartDocument();
/// <summary>
/// Reads a BSON string from the reader.
/// </summary>
/// <returns>A String.</returns>
public abstract string ReadString();
/// <summary>
/// Reads a BSON symbol from the reader.
/// </summary>
/// <returns>A string.</returns>
public abstract string ReadSymbol();
/// <summary>
/// Reads a BSON timestamp from the reader.
/// </summary>
/// <returns>The combined timestamp/increment.</returns>
public abstract long ReadTimestamp();
/// <summary>
/// Reads a BSON undefined from the reader.
/// </summary>
public abstract void ReadUndefined();
/// <summary>
/// Returns the reader to previously bookmarked position and state.
/// </summary>
/// <param name="bookmark">The bookmark.</param>
public abstract void ReturnToBookmark(BsonReaderBookmark bookmark);
/// <summary>
/// Skips the name (reader must be positioned on a name).
/// </summary>
public abstract void SkipName();
/// <summary>
/// Skips the value (reader must be positioned on a value).
/// </summary>
public abstract void SkipValue();
// protected methods
/// <summary>
/// Disposes of any resources used by the reader.
/// </summary>
/// <param name="disposing">True if called from Dispose.</param>
protected virtual void Dispose(bool disposing)
{
}
/// <summary>
/// Throws an InvalidOperationException when the method called is not valid for the current ContextType.
/// </summary>
/// <param name="methodName">The name of the method.</param>
/// <param name="actualContextType">The actual ContextType.</param>
/// <param name="validContextTypes">The valid ContextTypes.</param>
protected void ThrowInvalidContextType(
string methodName,
ContextType actualContextType,
params ContextType[] validContextTypes)
{
var validContextTypesString = string.Join(" or ", validContextTypes.Select(c => c.ToString()).ToArray());
var message = string.Format(
"{0} can only be called when ContextType is {1}, not when ContextType is {2}.",
methodName, validContextTypesString, actualContextType);
throw new InvalidOperationException(message);
}
/// <summary>
/// Throws an InvalidOperationException when the method called is not valid for the current state.
/// </summary>
/// <param name="methodName">The name of the method.</param>
/// <param name="validStates">The valid states.</param>
protected void ThrowInvalidState(string methodName, params BsonReaderState[] validStates)
{
var validStatesString = string.Join(" or ", validStates.Select(s => s.ToString()).ToArray());
var message = string.Format(
"{0} can only be called when State is {1}, not when State is {2}.",
methodName, validStatesString, _state);
throw new InvalidOperationException(message);
}
/// <summary>
/// Throws an ObjectDisposedException.
/// </summary>
protected void ThrowObjectDisposedException()
{
throw new ObjectDisposedException(this.GetType().Name);
}
/// <summary>
/// Verifies the current state and BsonType of the reader.
/// </summary>
/// <param name="methodName">The name of the method calling this one.</param>
/// <param name="requiredBsonType">The required BSON type.</param>
protected void VerifyBsonType(string methodName, BsonType requiredBsonType) =>
VerifyBsonType(requiredBsonType, methodName);
/// <summary>
/// Verifies the current state and BsonType of the reader.
/// </summary>
/// /// <param name="requiredBsonType">The required BSON type.</param>
/// <param name="methodName">The name of the method calling this one.</param>
protected void VerifyBsonType(BsonType requiredBsonType, [System.Runtime.CompilerServices.CallerMemberName]string methodName = null)
{
if (_state is BsonReaderState.Initial or BsonReaderState.ScopeDocument or BsonReaderState.Type)
{
ReadBsonType();
}
if (_state == BsonReaderState.Name)
{
// ignore name
SkipName();
}
if (_state != BsonReaderState.Value)
{
ThrowInvalidState(methodName, BsonReaderState.Value);
}
if (_currentBsonType != requiredBsonType)
{
throw new InvalidOperationException($"{methodName} can only be called when CurrentBsonType is {requiredBsonType}, not when CurrentBsonType is {_currentBsonType}.");
}
}
}
}