BsonClassMapSerializer.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. /* Copyright 2010-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Collections.Generic;
  17. using System.ComponentModel;
  18. using System.Linq;
  19. using System.Reflection;
  20. using MongoDB.Bson.IO;
  21. using MongoDB.Bson.Serialization.Serializers;
  22. namespace MongoDB.Bson.Serialization
  23. {
  24. /// <summary>
  25. /// Represents a serializer for a class map.
  26. /// </summary>
  27. /// <typeparam name="TClass">The type of the class.</typeparam>
  28. public class BsonClassMapSerializer<TClass> : SerializerBase<TClass>, IBsonIdProvider, IBsonDocumentSerializer, IBsonPolymorphicSerializer
  29. {
  30. // private fields
  31. private BsonClassMap _classMap;
  32. // constructors
  33. /// <summary>
  34. /// Initializes a new instance of the BsonClassMapSerializer class.
  35. /// </summary>
  36. /// <param name="classMap">The class map.</param>
  37. public BsonClassMapSerializer(BsonClassMap classMap)
  38. {
  39. if (classMap == null)
  40. {
  41. throw new ArgumentNullException("classMap");
  42. }
  43. if (classMap.ClassType != typeof(TClass))
  44. {
  45. var message = string.Format("Must be a BsonClassMap for the type {0}.", typeof(TClass));
  46. throw new ArgumentException(message, "classMap");
  47. }
  48. if (!classMap.IsFrozen)
  49. {
  50. throw new ArgumentException("Class map is not frozen.", nameof(classMap));
  51. }
  52. _classMap = classMap;
  53. }
  54. // public properties
  55. /// <summary>
  56. /// Gets a value indicating whether this serializer's discriminator is compatible with the object serializer.
  57. /// </summary>
  58. /// <value>
  59. /// <c>true</c> if this serializer's discriminator is compatible with the object serializer; otherwise, <c>false</c>.
  60. /// </value>
  61. public bool IsDiscriminatorCompatibleWithObjectSerializer
  62. {
  63. get { return true; }
  64. }
  65. // public methods
  66. /// <summary>
  67. /// Deserializes a value.
  68. /// </summary>
  69. /// <param name="context">The deserialization context.</param>
  70. /// <param name="args">The deserialization args.</param>
  71. /// <returns>A deserialized value.</returns>
  72. public override TClass Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
  73. {
  74. var bsonReader = context.Reader;
  75. if (_classMap.ClassType.GetTypeInfo().IsValueType)
  76. {
  77. var message = string.Format("Value class {0} cannot be deserialized.", _classMap.ClassType.FullName);
  78. throw new BsonSerializationException(message);
  79. }
  80. if (bsonReader.GetCurrentBsonType() == Bson.BsonType.Null)
  81. {
  82. bsonReader.ReadNull();
  83. return default(TClass);
  84. }
  85. else
  86. {
  87. var discriminatorConvention = _classMap.GetDiscriminatorConvention();
  88. var actualType = discriminatorConvention.GetActualType(bsonReader, args.NominalType);
  89. if (actualType == typeof(TClass))
  90. {
  91. return DeserializeClass(context);
  92. }
  93. else
  94. {
  95. var serializer = BsonSerializer.LookupSerializer(actualType);
  96. return (TClass)serializer.Deserialize(context);
  97. }
  98. }
  99. }
  100. /// <summary>
  101. /// Deserializes a value.
  102. /// </summary>
  103. /// <param name="context">The deserialization context.</param>
  104. /// <returns>A deserialized value.</returns>
  105. public TClass DeserializeClass(BsonDeserializationContext context)
  106. {
  107. var bsonReader = context.Reader;
  108. var bsonType = bsonReader.GetCurrentBsonType();
  109. if (bsonType != BsonType.Document)
  110. {
  111. var message = string.Format(
  112. "Expected a nested document representing the serialized form of a {0} value, but found a value of type {1} instead.",
  113. typeof(TClass).FullName, bsonType);
  114. throw new FormatException(message);
  115. }
  116. Dictionary<string, object> values = null;
  117. var document = default(TClass);
  118. ISupportInitialize supportsInitialization = null;
  119. if (_classMap.HasCreatorMaps)
  120. {
  121. // for creator-based deserialization we first gather the values in a dictionary and then call a matching creator
  122. values = new Dictionary<string, object>();
  123. }
  124. else
  125. {
  126. // for mutable classes we deserialize the values directly into the result object
  127. document = (TClass)_classMap.CreateInstance();
  128. supportsInitialization = document as ISupportInitialize;
  129. if (supportsInitialization != null)
  130. {
  131. supportsInitialization.BeginInit();
  132. }
  133. }
  134. var discriminatorConvention = _classMap.GetDiscriminatorConvention();
  135. var allMemberMaps = _classMap.AllMemberMaps;
  136. var extraElementsMemberMapIndex = _classMap.ExtraElementsMemberMapIndex;
  137. var memberMapBitArray = FastMemberMapHelper.GetBitArray(allMemberMaps.Count);
  138. bsonReader.ReadStartDocument();
  139. var elementTrie = _classMap.ElementTrie;
  140. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  141. {
  142. var trieDecoder = new TrieNameDecoder<int>(elementTrie);
  143. var elementName = bsonReader.ReadName(trieDecoder);
  144. if (trieDecoder.Found)
  145. {
  146. var memberMapIndex = trieDecoder.Value;
  147. var memberMap = allMemberMaps[memberMapIndex];
  148. if (memberMapIndex != extraElementsMemberMapIndex)
  149. {
  150. if (document != null)
  151. {
  152. if (memberMap.IsReadOnly)
  153. {
  154. bsonReader.SkipValue();
  155. }
  156. else
  157. {
  158. var value = DeserializeMemberValue(context, memberMap);
  159. memberMap.Setter(document, value);
  160. }
  161. }
  162. else
  163. {
  164. var value = DeserializeMemberValue(context, memberMap);
  165. values[elementName] = value;
  166. }
  167. }
  168. else
  169. {
  170. if (document != null)
  171. {
  172. DeserializeExtraElementMember(context, document, elementName, memberMap);
  173. }
  174. else
  175. {
  176. DeserializeExtraElementValue(context, values, elementName, memberMap);
  177. }
  178. }
  179. memberMapBitArray[memberMapIndex >> 5] |= 1U << (memberMapIndex & 31);
  180. }
  181. else
  182. {
  183. if (elementName == discriminatorConvention.ElementName)
  184. {
  185. bsonReader.SkipValue(); // skip over discriminator
  186. continue;
  187. }
  188. if (extraElementsMemberMapIndex >= 0)
  189. {
  190. var extraElementsMemberMap = _classMap.ExtraElementsMemberMap;
  191. if (document != null)
  192. {
  193. DeserializeExtraElementMember(context, document, elementName, extraElementsMemberMap);
  194. }
  195. else
  196. {
  197. DeserializeExtraElementValue(context, values, elementName, extraElementsMemberMap);
  198. }
  199. memberMapBitArray[extraElementsMemberMapIndex >> 5] |= 1U << (extraElementsMemberMapIndex & 31);
  200. }
  201. else if (_classMap.IgnoreExtraElements)
  202. {
  203. bsonReader.SkipValue();
  204. }
  205. else
  206. {
  207. var message = string.Format(
  208. "Element '{0}' does not match any field or property of class {1}.",
  209. elementName, _classMap.ClassType.FullName);
  210. throw new FormatException(message);
  211. }
  212. }
  213. }
  214. bsonReader.ReadEndDocument();
  215. // check any members left over that we didn't have elements for (in blocks of 32 elements at a time)
  216. for (var bitArrayIndex = 0; bitArrayIndex < memberMapBitArray.Length; ++bitArrayIndex)
  217. {
  218. var memberMapIndex = bitArrayIndex << 5;
  219. var memberMapBlock = ~memberMapBitArray[bitArrayIndex]; // notice that bits are flipped so 1's are now the missing elements
  220. // work through this memberMapBlock of 32 elements
  221. while (true)
  222. {
  223. // examine missing elements (memberMapBlock is shifted right as we work through the block)
  224. for (; (memberMapBlock & 1) != 0; ++memberMapIndex, memberMapBlock >>= 1)
  225. {
  226. var memberMap = allMemberMaps[memberMapIndex];
  227. if (memberMap.IsReadOnly)
  228. {
  229. continue;
  230. }
  231. if (memberMap.IsRequired)
  232. {
  233. var fieldOrProperty = (memberMap.MemberInfo is FieldInfo) ? "field" : "property";
  234. var message = string.Format(
  235. "Required element '{0}' for {1} '{2}' of class {3} is missing.",
  236. memberMap.ElementName, fieldOrProperty, memberMap.MemberName, _classMap.ClassType.FullName);
  237. throw new FormatException(message);
  238. }
  239. if (document != null)
  240. {
  241. memberMap.ApplyDefaultValue(document);
  242. }
  243. else if (memberMap.IsDefaultValueSpecified && !memberMap.IsReadOnly)
  244. {
  245. values[memberMap.ElementName] = memberMap.DefaultValue;
  246. }
  247. }
  248. if (memberMapBlock == 0)
  249. {
  250. break;
  251. }
  252. // skip ahead to the next missing element
  253. var leastSignificantBit = FastMemberMapHelper.GetLeastSignificantBit(memberMapBlock);
  254. memberMapIndex += leastSignificantBit;
  255. memberMapBlock >>= leastSignificantBit;
  256. }
  257. }
  258. if (document != null)
  259. {
  260. if (supportsInitialization != null)
  261. {
  262. supportsInitialization.EndInit();
  263. }
  264. return document;
  265. }
  266. else
  267. {
  268. return CreateInstanceUsingCreator(values);
  269. }
  270. }
  271. /// <summary>
  272. /// Gets the document Id.
  273. /// </summary>
  274. /// <param name="document">The document.</param>
  275. /// <param name="id">The Id.</param>
  276. /// <param name="idNominalType">The nominal type of the Id.</param>
  277. /// <param name="idGenerator">The IdGenerator for the Id type.</param>
  278. /// <returns>True if the document has an Id.</returns>
  279. public bool GetDocumentId(
  280. object document,
  281. out object id,
  282. out Type idNominalType,
  283. out IIdGenerator idGenerator)
  284. {
  285. var idMemberMap = _classMap.IdMemberMap;
  286. if (idMemberMap != null)
  287. {
  288. id = idMemberMap.Getter(document);
  289. idNominalType = idMemberMap.MemberType;
  290. idGenerator = idMemberMap.IdGenerator;
  291. return true;
  292. }
  293. else
  294. {
  295. id = null;
  296. idNominalType = null;
  297. idGenerator = null;
  298. return false;
  299. }
  300. }
  301. /// <summary>
  302. /// Tries to get the serialization info for a member.
  303. /// </summary>
  304. /// <param name="memberName">Name of the member.</param>
  305. /// <param name="serializationInfo">The serialization information.</param>
  306. /// <returns>
  307. /// <c>true</c> if the serialization info exists; otherwise <c>false</c>.
  308. /// </returns>
  309. public bool TryGetMemberSerializationInfo(string memberName, out BsonSerializationInfo serializationInfo)
  310. {
  311. foreach (var memberMap in _classMap.AllMemberMaps)
  312. {
  313. if (memberMap.MemberName == memberName)
  314. {
  315. var elementName = memberMap.ElementName;
  316. var serializer = memberMap.GetSerializer();
  317. serializationInfo = new BsonSerializationInfo(elementName, serializer, serializer.ValueType);
  318. return true;
  319. }
  320. }
  321. serializationInfo = null;
  322. return false;
  323. }
  324. /// <summary>
  325. /// Serializes a value.
  326. /// </summary>
  327. /// <param name="context">The serialization context.</param>
  328. /// <param name="args">The serialization args.</param>
  329. /// <param name="value">The object.</param>
  330. public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TClass value)
  331. {
  332. var bsonWriter = context.Writer;
  333. if (value == null)
  334. {
  335. bsonWriter.WriteNull();
  336. }
  337. else
  338. {
  339. var actualType = value.GetType();
  340. if (actualType == typeof(TClass))
  341. {
  342. SerializeClass(context, args, value);
  343. }
  344. else
  345. {
  346. var serializer = BsonSerializer.LookupSerializer(actualType);
  347. serializer.Serialize(context, args, value);
  348. }
  349. }
  350. }
  351. /// <summary>
  352. /// Sets the document Id.
  353. /// </summary>
  354. /// <param name="document">The document.</param>
  355. /// <param name="id">The Id.</param>
  356. public void SetDocumentId(object document, object id)
  357. {
  358. var documentType = document.GetType();
  359. var documentTypeInfo = documentType.GetTypeInfo();
  360. if (documentTypeInfo.IsValueType)
  361. {
  362. var message = string.Format("SetDocumentId cannot be used with value type {0}.", documentType.FullName);
  363. throw new BsonSerializationException(message);
  364. }
  365. var idMemberMap = _classMap.IdMemberMap;
  366. if (idMemberMap != null)
  367. {
  368. idMemberMap.Setter(document, id);
  369. }
  370. else
  371. {
  372. var message = string.Format("Class {0} has no Id member.", document.GetType().FullName);
  373. throw new InvalidOperationException(message);
  374. }
  375. }
  376. // private methods
  377. private BsonCreatorMap ChooseBestCreator(Dictionary<string, object> values)
  378. {
  379. // there's only one selector for now, but there might be more in the future (possibly even user provided)
  380. var selector = new MostArgumentsCreatorSelector();
  381. var creatorMap = selector.SelectCreator(_classMap, values);
  382. if (creatorMap == null)
  383. {
  384. throw new BsonSerializationException("No matching creator found.");
  385. }
  386. return creatorMap;
  387. }
  388. private TClass CreateInstanceUsingCreator(Dictionary<string, object> values)
  389. {
  390. var creatorMap = ChooseBestCreator(values);
  391. var document = creatorMap.CreateInstance(values); // removes values consumed
  392. var supportsInitialization = document as ISupportInitialize;
  393. if (supportsInitialization != null)
  394. {
  395. supportsInitialization.BeginInit();
  396. }
  397. // process any left over values that weren't passed to the creator
  398. foreach (var keyValuePair in values)
  399. {
  400. var elementName = keyValuePair.Key;
  401. var value = keyValuePair.Value;
  402. var memberMap = _classMap.GetMemberMapForElement(elementName);
  403. if (!memberMap.IsReadOnly)
  404. {
  405. memberMap.Setter.Invoke(document, value);
  406. }
  407. }
  408. if (supportsInitialization != null)
  409. {
  410. supportsInitialization.EndInit();
  411. }
  412. return (TClass)document;
  413. }
  414. private void DeserializeExtraElementMember(
  415. BsonDeserializationContext context,
  416. object obj,
  417. string elementName,
  418. BsonMemberMap extraElementsMemberMap)
  419. {
  420. var bsonReader = context.Reader;
  421. if (extraElementsMemberMap.MemberType == typeof(BsonDocument))
  422. {
  423. var extraElements = (BsonDocument)extraElementsMemberMap.Getter(obj);
  424. if (extraElements == null)
  425. {
  426. extraElements = new BsonDocument();
  427. extraElementsMemberMap.Setter(obj, extraElements);
  428. }
  429. var bsonValue = BsonValueSerializer.Instance.Deserialize(context);
  430. extraElements[elementName] = bsonValue;
  431. }
  432. else
  433. {
  434. var extraElements = (IDictionary<string, object>)extraElementsMemberMap.Getter(obj);
  435. if (extraElements == null)
  436. {
  437. if (extraElementsMemberMap.MemberType == typeof(IDictionary<string, object>))
  438. {
  439. extraElements = new Dictionary<string, object>();
  440. }
  441. else
  442. {
  443. extraElements = (IDictionary<string, object>)Activator.CreateInstance(extraElementsMemberMap.MemberType);
  444. }
  445. extraElementsMemberMap.Setter(obj, extraElements);
  446. }
  447. var bsonValue = BsonValueSerializer.Instance.Deserialize(context);
  448. extraElements[elementName] = BsonTypeMapper.MapToDotNetValue(bsonValue);
  449. }
  450. }
  451. private void DeserializeExtraElementValue(
  452. BsonDeserializationContext context,
  453. Dictionary<string, object> values,
  454. string elementName,
  455. BsonMemberMap extraElementsMemberMap)
  456. {
  457. var bsonReader = context.Reader;
  458. if (extraElementsMemberMap.MemberType == typeof(BsonDocument))
  459. {
  460. BsonDocument extraElements;
  461. object obj;
  462. if (values.TryGetValue(extraElementsMemberMap.ElementName, out obj))
  463. {
  464. extraElements = (BsonDocument)obj;
  465. }
  466. else
  467. {
  468. extraElements = new BsonDocument();
  469. values.Add(extraElementsMemberMap.ElementName, extraElements);
  470. }
  471. var bsonValue = BsonValueSerializer.Instance.Deserialize(context);
  472. extraElements[elementName] = bsonValue;
  473. }
  474. else
  475. {
  476. IDictionary<string, object> extraElements;
  477. object obj;
  478. if (values.TryGetValue(extraElementsMemberMap.ElementName, out obj))
  479. {
  480. extraElements = (IDictionary<string, object>)obj;
  481. }
  482. else
  483. {
  484. if (extraElementsMemberMap.MemberType == typeof(IDictionary<string, object>))
  485. {
  486. extraElements = new Dictionary<string, object>();
  487. }
  488. else
  489. {
  490. extraElements = (IDictionary<string, object>)Activator.CreateInstance(extraElementsMemberMap.MemberType);
  491. }
  492. values.Add(extraElementsMemberMap.ElementName, extraElements);
  493. }
  494. var bsonValue = BsonValueSerializer.Instance.Deserialize(context);
  495. extraElements[elementName] = BsonTypeMapper.MapToDotNetValue(bsonValue);
  496. }
  497. }
  498. private object DeserializeMemberValue(BsonDeserializationContext context, BsonMemberMap memberMap)
  499. {
  500. var bsonReader = context.Reader;
  501. try
  502. {
  503. return memberMap.GetSerializer().Deserialize(context);
  504. }
  505. catch (Exception ex)
  506. {
  507. var message = string.Format(
  508. "An error occurred while deserializing the {0} {1} of class {2}: {3}", // terminating period provided by nested message
  509. memberMap.MemberName, (memberMap.MemberInfo is FieldInfo) ? "field" : "property", memberMap.ClassMap.ClassType.FullName, ex.Message);
  510. throw new FormatException(message, ex);
  511. }
  512. }
  513. private void SerializeClass(BsonSerializationContext context, BsonSerializationArgs args, TClass document)
  514. {
  515. var bsonWriter = context.Writer;
  516. var remainingMemberMaps = _classMap.AllMemberMaps.ToList();
  517. bsonWriter.WriteStartDocument();
  518. var idMemberMap = _classMap.IdMemberMap;
  519. if (idMemberMap != null && args.SerializeIdFirst)
  520. {
  521. SerializeMember(context, document, idMemberMap);
  522. remainingMemberMaps.Remove(idMemberMap);
  523. }
  524. //var autoTimeStampMemberMap = _classMap.AutoTimeStampMemberMap;
  525. //if (autoTimeStampMemberMap != null)
  526. //{
  527. // SerializeNormalMember(context, document, autoTimeStampMemberMap);
  528. // remainingMemberMaps.Remove(autoTimeStampMemberMap);
  529. //}
  530. if (ShouldSerializeDiscriminator(args.NominalType))
  531. {
  532. SerializeDiscriminator(context, args.NominalType, document);
  533. }
  534. foreach (var memberMap in remainingMemberMaps)
  535. {
  536. SerializeMember(context, document, memberMap);
  537. }
  538. bsonWriter.WriteEndDocument();
  539. }
  540. private void SerializeExtraElements(BsonSerializationContext context, object obj, BsonMemberMap extraElementsMemberMap)
  541. {
  542. var bsonWriter = context.Writer;
  543. var extraElements = extraElementsMemberMap.Getter(obj);
  544. if (extraElements != null)
  545. {
  546. if (extraElementsMemberMap.MemberType == typeof(BsonDocument))
  547. {
  548. var bsonDocument = (BsonDocument)extraElements;
  549. foreach (var element in bsonDocument)
  550. {
  551. bsonWriter.WriteName(element.Name);
  552. BsonValueSerializer.Instance.Serialize(context, element.Value);
  553. }
  554. }
  555. else
  556. {
  557. var dictionary = (IDictionary<string, object>)extraElements;
  558. foreach (var key in dictionary.Keys)
  559. {
  560. bsonWriter.WriteName(key);
  561. var value = dictionary[key];
  562. var bsonValue = BsonTypeMapper.MapToBsonValue(value);
  563. BsonValueSerializer.Instance.Serialize(context, bsonValue);
  564. }
  565. }
  566. }
  567. }
  568. private void SerializeDiscriminator(BsonSerializationContext context, Type nominalType, object obj)
  569. {
  570. var discriminatorConvention = _classMap.GetDiscriminatorConvention();
  571. if (discriminatorConvention != null)
  572. {
  573. var actualType = obj.GetType();
  574. var discriminator = discriminatorConvention.GetDiscriminator(nominalType, actualType);
  575. if (discriminator != null)
  576. {
  577. context.Writer.WriteName(discriminatorConvention.ElementName);
  578. BsonValueSerializer.Instance.Serialize(context, discriminator);
  579. }
  580. }
  581. }
  582. private void SerializeMember(BsonSerializationContext context, object obj, BsonMemberMap memberMap)
  583. {
  584. if (memberMap != _classMap.ExtraElementsMemberMap)
  585. {
  586. SerializeNormalMember(context, obj, memberMap);
  587. }
  588. else
  589. {
  590. SerializeExtraElements(context, obj, memberMap);
  591. }
  592. }
  593. private void SerializeNormalMember(BsonSerializationContext context, object obj, BsonMemberMap memberMap)
  594. {
  595. var bsonWriter = context.Writer;
  596. var value = memberMap.Getter(obj);
  597. if (!memberMap.ShouldSerialize(obj, value))
  598. {
  599. return; // don't serialize member
  600. }
  601. bsonWriter.WriteName(memberMap.ElementName);
  602. memberMap.GetSerializer().Serialize(context, value);
  603. }
  604. private bool ShouldSerializeDiscriminator(Type nominalType)
  605. {
  606. return (nominalType != _classMap.ClassType || _classMap.DiscriminatorIsRequired || _classMap.HasRootClass) && !_classMap.IsAnonymous;
  607. }
  608. // nested classes
  609. // helper class that implements member map bit array helper functions
  610. private static class FastMemberMapHelper
  611. {
  612. public static uint[] GetBitArray(int memberCount)
  613. {
  614. var bitArrayOffset = memberCount & 31;
  615. var bitArrayLength = memberCount >> 5;
  616. if (bitArrayOffset == 0)
  617. {
  618. return new uint[bitArrayLength];
  619. }
  620. var bitArray = new uint[bitArrayLength + 1];
  621. bitArray[bitArrayLength] = ~0U << bitArrayOffset; // set unused bits to 1
  622. return bitArray;
  623. }
  624. // see http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightBinSearch
  625. // also returns 31 if no bits are set; caller must check this case
  626. public static int GetLeastSignificantBit(uint bitBlock)
  627. {
  628. var leastSignificantBit = 1;
  629. if ((bitBlock & 65535) == 0)
  630. {
  631. bitBlock >>= 16;
  632. leastSignificantBit |= 16;
  633. }
  634. if ((bitBlock & 255) == 0)
  635. {
  636. bitBlock >>= 8;
  637. leastSignificantBit |= 8;
  638. }
  639. if ((bitBlock & 15) == 0)
  640. {
  641. bitBlock >>= 4;
  642. leastSignificantBit |= 4;
  643. }
  644. if ((bitBlock & 3) == 0)
  645. {
  646. bitBlock >>= 2;
  647. leastSignificantBit |= 2;
  648. }
  649. return leastSignificantBit - (int)(bitBlock & 1);
  650. }
  651. }
  652. }
  653. }