-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathBsonClassMapSerializer.cs
719 lines (649 loc) · 28.1 KB
/
BsonClassMapSerializer.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
/* 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.ComponentModel;
using System.Reflection;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization.Serializers;
namespace MongoDB.Bson.Serialization
{
/// <summary>
/// Represents a serializer for a class map.
/// </summary>
/// <typeparam name="TClass">The type of the class.</typeparam>
public class BsonClassMapSerializer<TClass> : SerializerBase<TClass>, IBsonIdProvider, IBsonDocumentSerializer, IBsonPolymorphicSerializer
{
// private fields
private readonly BsonClassMap _classMap;
// constructors
/// <summary>
/// Initializes a new instance of the BsonClassMapSerializer class.
/// </summary>
/// <param name="classMap">The class map.</param>
public BsonClassMapSerializer(BsonClassMap classMap)
{
if (classMap == null)
{
throw new ArgumentNullException(nameof(classMap));
}
if (classMap.ClassType != typeof(TClass))
{
var message = string.Format("Must be a BsonClassMap for the type {0}.", typeof(TClass));
throw new ArgumentException(message, nameof(classMap));
}
if (!classMap.IsFrozen)
{
throw new ArgumentException("Class map is not frozen.", nameof(classMap));
}
_classMap = classMap;
}
// public properties
/// <summary>
/// Gets a value indicating whether this serializer's discriminator is compatible with the object serializer.
/// </summary>
/// <value>
/// <c>true</c> if this serializer's discriminator is compatible with the object serializer; otherwise, <c>false</c>.
/// </value>
public bool IsDiscriminatorCompatibleWithObjectSerializer
{
get { return true; }
}
// public methods
/// <summary>
/// Deserializes a value.
/// </summary>
/// <param name="context">The deserialization context.</param>
/// <param name="args">The deserialization args.</param>
/// <returns>A deserialized value.</returns>
public override TClass Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var bsonReader = context.Reader;
if (bsonReader.GetCurrentBsonType() == Bson.BsonType.Null)
{
bsonReader.ReadNull();
return default(TClass);
}
var discriminatorConvention = _classMap.GetDiscriminatorConvention();
var actualType = discriminatorConvention.GetActualType(bsonReader, args.NominalType);
if (actualType == typeof(TClass))
{
return DeserializeClass(context);
}
var serializer = BsonSerializer.LookupSerializer(actualType);
return (TClass)serializer.Deserialize(context);
}
/// <summary>
/// Deserializes a value.
/// </summary>
/// <param name="context">The deserialization context.</param>
/// <returns>A deserialized value.</returns>
public TClass DeserializeClass(BsonDeserializationContext context)
{
var bsonReader = context.Reader;
var bsonType = bsonReader.GetCurrentBsonType();
if (bsonType != BsonType.Document)
{
var message = string.Format(
"Expected a nested document representing the serialized form of a {0} value, but found a value of type {1} instead.",
typeof(TClass).FullName, bsonType);
throw new FormatException(message);
}
Dictionary<string, object> values = null;
// Important for struct support:
// should use object variable here, so created value should be boxed right away!
object document = null;
ISupportInitialize supportsInitialization = null;
if (_classMap.HasCreatorMaps)
{
// for creator-based deserialization we first gather the values in a dictionary and then call a matching creator
values = new Dictionary<string, object>();
}
else
{
// for mutable classes we deserialize the values directly into the result object
document = _classMap.CreateInstance();
if (document == null)
{
throw new BsonSerializationException($"{nameof(BsonClassMap)} did not provide an instance of {typeof(TClass).Name}.");
}
supportsInitialization = document as ISupportInitialize;
if (supportsInitialization != null)
{
supportsInitialization.BeginInit();
}
}
var discriminatorConvention = _classMap.GetDiscriminatorConvention();
var allMemberMaps = _classMap.AllMemberMaps;
var extraElementsMemberMapIndex = _classMap.ExtraElementsMemberMapIndex;
var memberMapBitArray = FastMemberMapHelper.GetBitArray(allMemberMaps.Count);
bsonReader.ReadStartDocument();
var elementTrie = _classMap.ElementTrie;
var trieDecoder = new TrieNameDecoder<int>(elementTrie);
while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
{
var elementName = bsonReader.ReadName(trieDecoder);
if (trieDecoder.Found)
{
var memberMapIndex = trieDecoder.Value;
var memberMap = allMemberMaps[memberMapIndex];
if (memberMapIndex != extraElementsMemberMapIndex)
{
if (document != null)
{
if (memberMap.IsReadOnly)
{
bsonReader.SkipValue();
}
else
{
var value = DeserializeMemberValue(context, memberMap);
memberMap.Setter(document, value);
}
}
else
{
var value = DeserializeMemberValue(context, memberMap);
values[elementName] = value;
}
}
else
{
if (document != null)
{
DeserializeExtraElementMember(context, document, elementName, memberMap);
}
else
{
DeserializeExtraElementValue(context, values, elementName, memberMap);
}
}
memberMapBitArray[memberMapIndex >> 5] |= 1U << (memberMapIndex & 31);
}
else
{
if (elementName == discriminatorConvention.ElementName)
{
bsonReader.SkipValue(); // skip over discriminator
continue;
}
// In QE server returns __safeContent__ fields, which should be skipped over.
if (elementName == "__safeContent__")
{
bsonReader.SkipValue(); // skip over unwanted element
continue;
}
if (extraElementsMemberMapIndex >= 0)
{
var extraElementsMemberMap = _classMap.ExtraElementsMemberMap;
if (document != null)
{
DeserializeExtraElementMember(context, document, elementName, extraElementsMemberMap);
}
else
{
DeserializeExtraElementValue(context, values, elementName, extraElementsMemberMap);
}
memberMapBitArray[extraElementsMemberMapIndex >> 5] |= 1U << (extraElementsMemberMapIndex & 31);
}
else if (_classMap.IgnoreExtraElements)
{
bsonReader.SkipValue();
}
else
{
var message = string.Format(
"Element '{0}' does not match any field or property of class {1}.",
elementName, _classMap.ClassType.FullName);
throw new FormatException(message);
}
}
}
bsonReader.ReadEndDocument();
// check any members left over that we didn't have elements for (in blocks of 32 elements at a time)
for (var bitArrayIndex = 0; bitArrayIndex < memberMapBitArray.Length; ++bitArrayIndex)
{
var memberMapIndex = bitArrayIndex << 5;
var memberMapBlock = ~memberMapBitArray[bitArrayIndex]; // notice that bits are flipped so 1's are now the missing elements
// work through this memberMapBlock of 32 elements
while (true)
{
// examine missing elements (memberMapBlock is shifted right as we work through the block)
for (; (memberMapBlock & 1) != 0; ++memberMapIndex, memberMapBlock >>= 1)
{
var memberMap = allMemberMaps[memberMapIndex];
if (memberMap.IsReadOnly)
{
continue;
}
if (memberMap.IsRequired)
{
var fieldOrProperty = (memberMap.MemberInfo is FieldInfo) ? "field" : "property";
var message = string.Format(
"Required element '{0}' for {1} '{2}' of class {3} is missing.",
memberMap.ElementName, fieldOrProperty, memberMap.MemberName, _classMap.ClassType.FullName);
throw new FormatException(message);
}
if (document != null)
{
memberMap.ApplyDefaultValue(document);
}
else if (memberMap.IsDefaultValueSpecified && !memberMap.IsReadOnly)
{
values[memberMap.ElementName] = memberMap.DefaultValue;
}
}
if (memberMapBlock == 0)
{
break;
}
// skip ahead to the next missing element
var leastSignificantBit = FastMemberMapHelper.GetLeastSignificantBit(memberMapBlock);
memberMapIndex += leastSignificantBit;
memberMapBlock >>= leastSignificantBit;
}
}
if (document != null)
{
if (supportsInitialization != null)
{
supportsInitialization.EndInit();
}
return (TClass)document;
}
return CreateInstanceUsingCreator(values);
}
/// <summary>
/// Gets the document Id.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="id">The Id.</param>
/// <param name="idNominalType">The nominal type of the Id.</param>
/// <param name="idGenerator">The IdGenerator for the Id type.</param>
/// <returns>True if the document has an Id.</returns>
public bool GetDocumentId(
object document,
out object id,
out Type idNominalType,
out IIdGenerator idGenerator)
{
var idMemberMap = _classMap.IdMemberMap;
if (idMemberMap != null)
{
id = idMemberMap.Getter(document);
idNominalType = idMemberMap.MemberType;
idGenerator = idMemberMap.IdGenerator;
return true;
}
else
{
id = null;
idNominalType = null;
idGenerator = null;
return false;
}
}
/// <summary>
/// Tries to get the serialization info for a member.
/// </summary>
/// <param name="memberName">Name of the member.</param>
/// <param name="serializationInfo">The serialization information.</param>
/// <returns>
/// <c>true</c> if the serialization info exists; otherwise <c>false</c>.
/// </returns>
public bool TryGetMemberSerializationInfo(string memberName, out BsonSerializationInfo serializationInfo)
{
foreach (var memberMap in _classMap.AllMemberMaps)
{
if (memberMap.MemberName == memberName)
{
var elementName = memberMap.ElementName;
var serializer = memberMap.GetSerializer();
serializationInfo = new BsonSerializationInfo(elementName, serializer, serializer.ValueType);
return true;
}
}
serializationInfo = null;
return false;
}
/// <summary>
/// Serializes a value.
/// </summary>
/// <param name="context">The serialization context.</param>
/// <param name="args">The serialization args.</param>
/// <param name="value">The object.</param>
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TClass value)
{
var bsonWriter = context.Writer;
if (value == null)
{
bsonWriter.WriteNull();
return;
}
var actualType = value.GetType();
if (actualType == typeof(TClass))
{
SerializeClass(context, args, value);
return;
}
var serializer = BsonSerializer.LookupSerializer(actualType);
serializer.Serialize(context, args, value);
}
/// <summary>
/// Sets the document Id.
/// </summary>
/// <param name="document">The document.</param>
/// <param name="id">The Id.</param>
public void SetDocumentId(object document, object id)
{
var documentType = document.GetType();
var documentTypeInfo = documentType.GetTypeInfo();
if (documentTypeInfo.IsValueType)
{
var message = string.Format("SetDocumentId cannot be used with value type {0}.", documentType.FullName);
throw new BsonSerializationException(message);
}
var idMemberMap = _classMap.IdMemberMap;
if (idMemberMap != null)
{
idMemberMap.Setter(document, id);
}
else
{
var message = string.Format("Class {0} has no Id member.", document.GetType().FullName);
throw new InvalidOperationException(message);
}
}
// private methods
private BsonCreatorMap ChooseBestCreator(Dictionary<string, object> values)
{
// there's only one selector for now, but there might be more in the future (possibly even user provided)
var selector = new MostArgumentsCreatorSelector();
var creatorMap = selector.SelectCreator(_classMap, values);
if (creatorMap == null)
{
throw new BsonSerializationException("No matching creator found.");
}
return creatorMap;
}
private TClass CreateInstanceUsingCreator(Dictionary<string, object> values)
{
var creatorMap = ChooseBestCreator(values);
object document = creatorMap.CreateInstance(values); // removes values consumed
var supportsInitialization = document as ISupportInitialize;
if (supportsInitialization != null)
{
supportsInitialization.BeginInit();
}
// process any left over values that weren't passed to the creator
foreach (var keyValuePair in values)
{
var elementName = keyValuePair.Key;
var value = keyValuePair.Value;
var memberMap = _classMap.GetMemberMapForElement(elementName);
if (!memberMap.IsReadOnly)
{
memberMap.Setter.Invoke(document, value);
}
}
if (supportsInitialization != null)
{
supportsInitialization.EndInit();
}
return (TClass)document;
}
private void DeserializeExtraElementMember(
BsonDeserializationContext context,
object obj,
string elementName,
BsonMemberMap extraElementsMemberMap)
{
if (extraElementsMemberMap.MemberType == typeof(BsonDocument))
{
var extraElements = (BsonDocument)extraElementsMemberMap.Getter(obj);
if (extraElements == null)
{
extraElements = new BsonDocument();
extraElementsMemberMap.Setter(obj, extraElements);
}
var bsonValue = BsonValueSerializer.Instance.Deserialize(context);
extraElements[elementName] = bsonValue;
}
else
{
var extraElements = (IDictionary<string, object>)extraElementsMemberMap.Getter(obj);
if (extraElements == null)
{
if (extraElementsMemberMap.MemberType == typeof(IDictionary<string, object>))
{
extraElements = new Dictionary<string, object>();
}
else
{
extraElements = (IDictionary<string, object>)Activator.CreateInstance(extraElementsMemberMap.MemberType);
}
extraElementsMemberMap.Setter(obj, extraElements);
}
var bsonValue = BsonValueSerializer.Instance.Deserialize(context);
extraElements[elementName] = BsonTypeMapper.MapToDotNetValue(bsonValue);
}
}
private void DeserializeExtraElementValue(
BsonDeserializationContext context,
Dictionary<string, object> values,
string elementName,
BsonMemberMap extraElementsMemberMap)
{
if (extraElementsMemberMap.MemberType == typeof(BsonDocument))
{
BsonDocument extraElements;
object obj;
if (values.TryGetValue(extraElementsMemberMap.ElementName, out obj))
{
extraElements = (BsonDocument)obj;
}
else
{
extraElements = new BsonDocument();
values.Add(extraElementsMemberMap.ElementName, extraElements);
}
var bsonValue = BsonValueSerializer.Instance.Deserialize(context);
extraElements[elementName] = bsonValue;
}
else
{
IDictionary<string, object> extraElements;
object obj;
if (values.TryGetValue(extraElementsMemberMap.ElementName, out obj))
{
extraElements = (IDictionary<string, object>)obj;
}
else
{
if (extraElementsMemberMap.MemberType == typeof(IDictionary<string, object>))
{
extraElements = new Dictionary<string, object>();
}
else
{
extraElements = (IDictionary<string, object>)Activator.CreateInstance(extraElementsMemberMap.MemberType);
}
values.Add(extraElementsMemberMap.ElementName, extraElements);
}
var bsonValue = BsonValueSerializer.Instance.Deserialize(context);
extraElements[elementName] = BsonTypeMapper.MapToDotNetValue(bsonValue);
}
}
private object DeserializeMemberValue(BsonDeserializationContext context, BsonMemberMap memberMap)
{
try
{
return memberMap.GetSerializer().Deserialize(context);
}
catch (Exception ex)
{
var message = string.Format(
"An error occurred while deserializing the {0} {1} of class {2}: {3}", // terminating period provided by nested message
memberMap.MemberName, (memberMap.MemberInfo is FieldInfo) ? "field" : "property", memberMap.ClassMap.ClassType.FullName, ex.Message);
throw new FormatException(message, ex);
}
}
private void SerializeClass(BsonSerializationContext context, BsonSerializationArgs args, TClass document)
{
var bsonWriter = context.Writer;
bsonWriter.WriteStartDocument();
var idMemberMap = _classMap.IdMemberMap;
if (idMemberMap != null && args.SerializeIdFirst)
{
SerializeMember(context, document, idMemberMap);
}
if (ShouldSerializeDiscriminator(args.NominalType))
{
SerializeDiscriminator(context, args.NominalType, document, args.DiscriminatorConvention);
}
foreach (var memberMap in _classMap.AllMemberMaps)
{
if (memberMap != idMemberMap || !args.SerializeIdFirst)
{
SerializeMember(context, document, memberMap);
}
}
bsonWriter.WriteEndDocument();
}
private void SerializeExtraElements(BsonSerializationContext context, object obj, BsonMemberMap extraElementsMemberMap)
{
var bsonWriter = context.Writer;
var extraElements = extraElementsMemberMap.Getter(obj);
if (extraElements != null)
{
if (extraElementsMemberMap.MemberType == typeof(BsonDocument))
{
var bsonDocument = (BsonDocument)extraElements;
foreach (var element in bsonDocument)
{
bsonWriter.WriteName(element.Name);
BsonValueSerializer.Instance.Serialize(context, element.Value);
}
}
else
{
var dictionary = (IDictionary<string, object>)extraElements;
foreach (var key in dictionary.Keys)
{
bsonWriter.WriteName(key);
var value = dictionary[key];
var bsonValue = BsonTypeMapper.MapToBsonValue(value);
BsonValueSerializer.Instance.Serialize(context, bsonValue);
}
}
}
}
private void SerializeDiscriminator(BsonSerializationContext context, Type nominalType, object obj, IDiscriminatorConvention discriminatorConvention)
{
discriminatorConvention ??= _classMap.GetDiscriminatorConvention();
if (discriminatorConvention != null)
{
var actualType = obj.GetType();
var discriminator = discriminatorConvention.GetDiscriminator(nominalType, actualType);
if (discriminator != null)
{
context.Writer.WriteName(discriminatorConvention.ElementName);
BsonValueSerializer.Instance.Serialize(context, discriminator);
}
}
}
private void SerializeMember(BsonSerializationContext context, object obj, BsonMemberMap memberMap)
{
try
{
if (memberMap != _classMap.ExtraElementsMemberMap)
{
SerializeNormalMember(context, obj, memberMap);
}
else
{
SerializeExtraElements(context, obj, memberMap);
}
}
catch (Exception ex)
{
var message = string.Format(
"An error occurred while serializing the {0} {1} of class {2}: {3}", // terminating period provided by nested message
memberMap.MemberName, (memberMap.MemberInfo is FieldInfo) ? "field" : "property", memberMap.ClassMap.ClassType.FullName, ex.Message);
throw new BsonSerializationException(message, ex);
}
}
private void SerializeNormalMember(BsonSerializationContext context, object obj, BsonMemberMap memberMap)
{
var bsonWriter = context.Writer;
var value = memberMap.Getter(obj);
if (!memberMap.ShouldSerialize(obj, value))
{
return; // don't serialize member
}
bsonWriter.WriteName(memberMap.ElementName);
memberMap.GetSerializer().Serialize(context, value);
}
private bool ShouldSerializeDiscriminator(Type nominalType)
{
return (nominalType != _classMap.ClassType || _classMap.DiscriminatorIsRequired || _classMap.HasRootClass) && !_classMap.IsAnonymous;
}
// nested classes
// helper class that implements member map bit array helper functions
private static class FastMemberMapHelper
{
public static uint[] GetBitArray(int memberCount)
{
var bitArrayOffset = memberCount & 31;
var bitArrayLength = memberCount >> 5;
if (bitArrayOffset == 0)
{
return new uint[bitArrayLength];
}
var bitArray = new uint[bitArrayLength + 1];
bitArray[bitArrayLength] = ~0U << bitArrayOffset; // set unused bits to 1
return bitArray;
}
// see http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightBinSearch
// also returns 31 if no bits are set; caller must check this case
public static int GetLeastSignificantBit(uint bitBlock)
{
var leastSignificantBit = 1;
if ((bitBlock & 65535) == 0)
{
bitBlock >>= 16;
leastSignificantBit |= 16;
}
if ((bitBlock & 255) == 0)
{
bitBlock >>= 8;
leastSignificantBit |= 8;
}
if ((bitBlock & 15) == 0)
{
bitBlock >>= 4;
leastSignificantBit |= 4;
}
if ((bitBlock & 3) == 0)
{
bitBlock >>= 2;
leastSignificantBit |= 2;
}
return leastSignificantBit - (int)(bitBlock & 1);
}
}
}
}