forked from samus/mongodb-csharp
/
BsonWriter.cs
617 lines (570 loc) · 20.6 KB
/
BsonWriter.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace MongoDB.Bson
{
/// <summary>
/// Class that knows how to format a native object into bson bits.
/// </summary>
public class BsonWriter
{
private const int BufferLength = 256;
private readonly byte[] _buffer;
private readonly IBsonObjectDescriptor _descriptor;
private readonly int _maxChars;
private readonly Stream _stream;
private readonly BinaryWriter _writer;
/// <summary>
/// Initializes a new instance of the <see cref = "BsonWriter" /> class.
/// </summary>
/// <param name = "stream">The stream.</param>
/// <param name = "settings">The settings.</param>
public BsonWriter(Stream stream, BsonWriterSettings settings)
{
if(settings == null)
throw new ArgumentNullException("settings");
_stream = stream;
_descriptor = settings.Descriptor;
_writer = new BinaryWriter(_stream);
_buffer = new byte[BufferLength];
_maxChars = BufferLength/Encoding.UTF8.GetMaxByteCount(1);
}
/// <summary>
/// Initializes a new instance of the <see cref = "BsonWriter" /> class.
/// </summary>
/// <param name = "stream">The stream.</param>
/// <param name = "descriptor">The descriptor.</param>
public BsonWriter(Stream stream, IBsonObjectDescriptor descriptor)
{
_stream = stream;
_descriptor = descriptor;
_writer = new BinaryWriter(_stream);
_buffer = new byte[BufferLength];
_maxChars = BufferLength/Encoding.UTF8.GetMaxByteCount(1);
}
/// <summary>
/// Writes the value.
/// </summary>
/// <param name = "type">Type of the data.</param>
/// <param name = "obj">The obj.</param>
public void WriteValue(BsonType type, Object obj)
{
switch(type)
{
case BsonType.MinKey:
case BsonType.MaxKey:
case BsonType.Null:
return;
case BsonType.Boolean:
_writer.Write((bool)obj);
return;
case BsonType.Integer:
_writer.Write((int)obj);
return;
case BsonType.Long:
if(obj is TimeSpan)
_writer.Write(((TimeSpan)obj).Ticks);
else
_writer.Write((long)obj);
return;
case BsonType.Date:
Write((DateTime)obj);
return;
case BsonType.Oid:
Write((Oid)obj);
return;
case BsonType.Number:
_writer.Write(Convert.ToDouble(obj));
return;
case BsonType.String:
{
Write((String)obj);
return;
}
case BsonType.Obj:
if(obj is DBRef)
Write((DBRef)obj);
else
WriteObject(obj);
return;
case BsonType.Array:
WriteArray((IEnumerable)obj);
return;
case BsonType.Regex:
{
Write((MongoRegex)obj);
return;
}
case BsonType.Code:
{
Write((Code)obj);
return;
}
case BsonType.Symbol:
{
WriteValue(BsonType.String, ((MongoSymbol)obj).Value);
return;
}
case BsonType.CodeWScope:
{
Write((CodeWScope)obj);
return;
}
case BsonType.Binary:
{
if(obj is Guid)
Write((Guid)obj);
else if(obj is byte[])
Write((byte[])obj);
else
Write((Binary)obj);
return;
}
default:
throw new NotImplementedException(String.Format("Writing {0} types not implemented.", obj.GetType().Name));
}
}
/// <summary>
/// Writes the specified id.
/// </summary>
/// <param name = "id">The id.</param>
private void Write(Oid id)
{
_writer.Write(id.ToByteArray());
}
/// <summary>
/// Writes the specified binary.
/// </summary>
/// <param name = "binary">The binary.</param>
private void Write(Binary binary)
{
if(binary.Subtype == BinarySubtype.General)
{
_writer.Write(binary.Bytes.Length + 4);
_writer.Write((byte)binary.Subtype);
_writer.Write(binary.Bytes.Length);
}
else
{
_writer.Write(binary.Bytes.Length);
_writer.Write((byte)binary.Subtype);
}
_writer.Write(binary.Bytes);
}
/// <summary>
/// Writes the specified GUID.
/// </summary>
/// <param name = "guid">The GUID.</param>
private void Write(Guid guid)
{
_writer.Write(16);
_writer.Write((byte)3);
_writer.Write(guid.ToByteArray());
}
/// <summary>
/// Writes the specified bytes.
/// </summary>
/// <param name = "bytes">The bytes.</param>
private void Write(byte[] bytes)
{
Write(new Binary(bytes));
}
/// <summary>
/// Writes the specified code scope.
/// </summary>
/// <param name = "codeScope">The code scope.</param>
private void Write(CodeWScope codeScope)
{
_writer.Write(CalculateSize(codeScope));
WriteValue(BsonType.String, codeScope.Value);
WriteValue(BsonType.Obj, codeScope.Scope);
}
/// <summary>
/// Writes the specified code.
/// </summary>
/// <param name = "code">The code.</param>
private void Write(Code code)
{
WriteValue(BsonType.String, code.Value);
}
/// <summary>
/// Writes the specified regex.
/// </summary>
/// <param name = "regex">The regex.</param>
private void Write(MongoRegex regex)
{
Write(regex.Expression, false);
Write(regex.Options, false);
}
/// <summary>
/// Writes the specified reference.
/// </summary>
/// <param name = "reference">The reference.</param>
public void Write(DBRef reference)
{
WriteObject((Document)reference);
}
/// <summary>
/// Writes the specified data time.
/// </summary>
/// <param name = "dateTime">The data time.</param>
private void Write(DateTime dateTime)
{
var diff = dateTime.ToUniversalTime() - BsonInfo.Epoch;
var time = Math.Floor(diff.TotalMilliseconds);
_writer.Write((long)time);
}
/// <summary>
/// Writes the object.
/// </summary>
/// <param name = "obj">The obj.</param>
public void WriteObject(object obj)
{
obj = _descriptor.BeginObject(obj);
WriteElements(obj);
_descriptor.EndObject(obj);
}
/// <summary>
/// Writes the elements.
/// </summary>
/// <param name = "obj">The obj.</param>
private void WriteElements(object obj)
{
var properties = _descriptor.GetProperties(obj);
var size = CalculateSizeObject(obj, properties);
if(size >= BsonInfo.MaxDocumentSize)
throw new ArgumentException("Maximum document size exceeded.");
_writer.Write(size);
foreach(var property in properties)
{
_descriptor.BeginProperty(obj, property);
var bsonType = TranslateToBsonType(property.Value);
_writer.Write((byte)bsonType);
Write(property.Name, false);
WriteValue(bsonType, property.Value);
_descriptor.EndProperty(obj, property);
}
_writer.Write((byte)0);
}
/// <summary>
/// Writes the array.
/// </summary>
/// <param name = "enumerable">The enumerable.</param>
public void WriteArray(IEnumerable enumerable)
{
var obj = _descriptor.BeginArray(enumerable);
WriteElements(obj);
_descriptor.EndArray(obj);
}
/// <summary>
/// Writes the specified value.
/// </summary>
/// <param name = "value">The value.</param>
private void Write(string value)
{
Write(value, true);
}
/// <summary>
/// Writes the specified value.
/// </summary>
/// <param name = "value">The value.</param>
/// <param name = "includeLength">if set to <c>true</c> [include length].</param>
public void Write(string value, bool includeLength)
{
if(includeLength)
_writer.Write(CalculateSize(value, false));
var byteCount = Encoding.UTF8.GetByteCount(value);
if(byteCount < BufferLength)
{
Encoding.UTF8.GetBytes(value, 0, value.Length, _buffer, 0);
_writer.Write(_buffer, 0, byteCount);
}
else
{
int charCount;
var totalCharsWritten = 0;
for(var i = value.Length; i > 0; i -= charCount)
{
charCount = (i > _maxChars) ? _maxChars : i;
var count = Encoding.UTF8.GetBytes(value, totalCharsWritten, charCount, _buffer, 0);
_writer.Write(_buffer, 0, count);
totalCharsWritten += charCount;
}
}
_writer.Write((byte)0);
}
/// <summary>
/// Calculates the size.
/// </summary>
/// <param name = "obj">The obj.</param>
/// <returns></returns>
public int CalculateSize(Object obj)
{
if(obj == null)
return 0;
switch(TranslateToBsonType(obj))
{
case BsonType.MinKey:
case BsonType.MaxKey:
case BsonType.Null:
return 0;
case BsonType.Boolean:
return 1;
case BsonType.Integer:
return 4;
case BsonType.Long:
case BsonType.Date:
return 8;
case BsonType.Oid:
return 12;
case BsonType.Number:
return sizeof(Double);
case BsonType.String:
return CalculateSize((string)obj);
case BsonType.Obj:
{
if(obj.GetType() == typeof(DBRef))
return CalculateSize((DBRef)obj);
return CalculateSizeObject(obj);
}
case BsonType.Array:
return CalculateSize((IEnumerable)obj);
case BsonType.Regex:
{
return CalculateSize((MongoRegex)obj);
}
case BsonType.Code:
return CalculateSize((Code)obj);
case BsonType.CodeWScope:
{
return CalculateSize((CodeWScope)obj);
}
case BsonType.Binary:
{
if(obj is Guid)
return CalculateSize((Guid)obj);
if(obj is byte[])
return CalculateSize((byte[])obj);
return CalculateSize((Binary)obj);
}
case BsonType.Symbol:
{
return CalculateSize(((MongoSymbol)obj).Value, true);
}
}
throw new NotImplementedException(String.Format("Calculating size of {0} is not implemented.", obj.GetType().Name));
}
/// <summary>
/// Calculates the size.
/// </summary>
/// <param name = "code">The code.</param>
/// <returns></returns>
private int CalculateSize(Code code)
{
return CalculateSize(code.Value, true);
}
/// <summary>
/// Calculates the size.
/// </summary>
/// <param name = "regex">The regex.</param>
/// <returns></returns>
public int CalculateSize(MongoRegex regex)
{
var size = CalculateSize(regex.Expression, false);
size += CalculateSize(regex.Options, false);
return size;
}
/// <summary>
/// Calculates the size.
/// </summary>
/// <param name = "codeScope">The code scope.</param>
/// <returns></returns>
public int CalculateSize(CodeWScope codeScope)
{
var size = 4;
size += CalculateSize(codeScope.Value, true);
size += CalculateSizeObject(codeScope.Scope);
return size;
}
/// <summary>
/// Calculates the size.
/// </summary>
/// <param name = "binary">The binary.</param>
/// <returns></returns>
public int CalculateSize(Binary binary)
{
var size = 4; //size int
size += 1; //subtype
if(binary.Subtype == BinarySubtype.General)
size += 4; //embedded size int
size += binary.Bytes.Length;
return size;
}
/// <summary>
/// Calculates the size.
/// </summary>
/// <param name = "bytes">The bytes.</param>
/// <returns></returns>
public int CalculateSize(byte[] bytes)
{
return CalculateSize(new Binary(bytes));
}
/// <summary>
/// Calculates the size.
/// </summary>
/// <param name = "guid">The GUID.</param>
/// <returns></returns>
public int CalculateSize(Guid guid)
{
return 21;
}
/// <summary>
/// Calculates the size.
/// </summary>
/// <param name = "reference">The reference.</param>
/// <returns></returns>
public int CalculateSize(DBRef reference)
{
return CalculateSizeObject((Document)reference);
}
/// <summary>
/// Calculates the size object.
/// </summary>
/// <param name = "obj">The obj.</param>
/// <returns></returns>
public int CalculateSizeObject(object obj)
{
obj = _descriptor.BeginObject(obj);
var properties = _descriptor.GetProperties(obj);
var size = CalculateSizeObject(obj, properties);
_descriptor.EndObject(obj);
return size;
}
/// <summary>
/// Calculates the size object.
/// </summary>
/// <param name = "obj">The obj.</param>
/// <param name = "propertys">The propertys.</param>
/// <returns></returns>
private int CalculateSizeObject(object obj, IEnumerable<BsonProperty> propertys)
{
var size = 4;
foreach(var property in propertys)
{
var elsize = 1; //type
_descriptor.BeginProperty(obj, property);
elsize += CalculateSize(property.Name, false);
elsize += CalculateSize(property.Value);
_descriptor.EndProperty(obj, property);
size += elsize;
}
size += 1; //terminator
return size;
}
/// <summary>
/// Calculates the size.
/// </summary>
/// <param name = "enumerable">The enumerable.</param>
/// <returns></returns>
public int CalculateSize(IEnumerable enumerable)
{
var obj = _descriptor.BeginArray(enumerable);
var properties = _descriptor.GetProperties(obj);
var size = CalculateSizeObject(obj, properties);
_descriptor.EndArray(obj);
return size;
}
/// <summary>
/// Calculates the size.
/// </summary>
/// <param name = "value">The value.</param>
/// <returns></returns>
public int CalculateSize(String value)
{
return CalculateSize(value, true);
}
/// <summary>
/// Calculates the size.
/// </summary>
/// <param name = "value">The value.</param>
/// <param name = "includeLength">if set to <c>true</c> [include length].</param>
/// <returns></returns>
public int CalculateSize(String value, bool includeLength)
{
var size = 1; //terminator
if(includeLength)
size += 4;
if(value != null)
size += Encoding.UTF8.GetByteCount(value);
return size;
}
/// <summary>
/// Flushes this instance.
/// </summary>
public void Flush()
{
_writer.Flush();
}
/// <summary>
/// Translates the type of to bson.
/// </summary>
/// <param name = "obj">The obj.</param>
/// <returns></returns>
protected BsonType TranslateToBsonType(object obj)
{
//TODO:Convert to use a dictionary
if(obj == null)
return BsonType.Null;
var type = obj.GetType();
if(obj is Enum) //special case enums
type = Enum.GetUnderlyingType(type);
if(type == typeof(Double))
return BsonType.Number;
if(type == typeof(Single))
return BsonType.Number;
if(type == typeof(String))
return BsonType.String;
if(type == typeof(int))
return BsonType.Integer;
if(type == typeof(long))
return BsonType.Long;
if(type == typeof(bool))
return BsonType.Boolean;
if(type == typeof(Oid))
return BsonType.Oid;
if(type == typeof(DateTime))
return BsonType.Date;
if(type == typeof(TimeSpan))
return BsonType.Long;
if(type == typeof(MongoRegex))
return BsonType.Regex;
if(type == typeof(DBRef))
return BsonType.Obj;
if(type == typeof(Code))
return BsonType.Code;
if(type == typeof(CodeWScope))
return BsonType.CodeWScope;
if(type == typeof(DBNull))
return BsonType.Null;
if(type == typeof(Binary))
return BsonType.Binary;
if(type == typeof(Guid))
return BsonType.Binary;
if(type == typeof(MongoMinKey))
return BsonType.MinKey;
if(type == typeof(MongoMaxKey))
return BsonType.MaxKey;
if(type == typeof(MongoSymbol))
return BsonType.Symbol;
if(type == typeof(byte[]))
return BsonType.Binary;
if(_descriptor.IsArray(obj))
return BsonType.Array;
if(_descriptor.IsObject(obj))
return BsonType.Obj;
throw new ArgumentOutOfRangeException(String.Format("Type: {0} not recognized", type.FullName));
}
}
}