BitArraySerializer.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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;
  17. using System.Text;
  18. using MongoDB.Bson.IO;
  19. namespace MongoDB.Bson.Serialization.Serializers
  20. {
  21. /// <summary>
  22. /// Represents a serializer for BitArrays.
  23. /// </summary>
  24. public class BitArraySerializer : SealedClassSerializerBase<BitArray>, IRepresentationConfigurable<BitArraySerializer>
  25. {
  26. // private constants
  27. private static class Flags
  28. {
  29. public const long Length = 1;
  30. public const long Bytes = 2;
  31. }
  32. // private fields
  33. private readonly SerializerHelper _helper;
  34. private readonly Int32Serializer _int32Serializer = new Int32Serializer();
  35. private readonly BsonType _representation;
  36. // constructors
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="BitArraySerializer"/> class.
  39. /// </summary>
  40. public BitArraySerializer()
  41. : this(BsonType.Binary)
  42. {
  43. }
  44. /// <summary>
  45. /// Initializes a new instance of the <see cref="BitArraySerializer"/> class.
  46. /// </summary>
  47. /// <param name="representation">The representation.</param>
  48. public BitArraySerializer(BsonType representation)
  49. {
  50. switch (representation)
  51. {
  52. case BsonType.Binary:
  53. case BsonType.String:
  54. break;
  55. default:
  56. var message = string.Format("{0} is not a valid representation for a BitArraySerializer.", representation);
  57. throw new ArgumentException(message);
  58. }
  59. _representation = representation;
  60. _helper = new SerializerHelper
  61. (
  62. new SerializerHelper.Member("Length", Flags.Length),
  63. new SerializerHelper.Member("Bytes", Flags.Bytes)
  64. );
  65. }
  66. // public properties
  67. /// <summary>
  68. /// Gets the representation.
  69. /// </summary>
  70. /// <value>
  71. /// The representation.
  72. /// </value>
  73. public BsonType Representation
  74. {
  75. get { return _representation; }
  76. }
  77. // public methods
  78. #pragma warning disable 618 // about obsolete BsonBinarySubType.OldBinary
  79. /// <summary>
  80. /// Deserializes a value.
  81. /// </summary>
  82. /// <param name="context">The deserialization context.</param>
  83. /// <param name="args">The deserialization args.</param>
  84. /// <returns>A deserialized value.</returns>
  85. protected override BitArray DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args)
  86. {
  87. var bsonReader = context.Reader;
  88. BitArray bitArray;
  89. BsonType bsonType = bsonReader.GetCurrentBsonType();
  90. switch (bsonType)
  91. {
  92. case BsonType.Binary:
  93. return new BitArray(bsonReader.ReadBytes());
  94. case BsonType.Document:
  95. int length = 0;
  96. byte[] bytes = null;
  97. _helper.DeserializeMembers(context, (elementName, flag) =>
  98. {
  99. switch (flag)
  100. {
  101. case Flags.Length: length = _int32Serializer.Deserialize(context); break;
  102. case Flags.Bytes: bytes = bsonReader.ReadBytes(); break;
  103. }
  104. });
  105. bitArray = new BitArray(bytes);
  106. bitArray.Length = length;
  107. return bitArray;
  108. case BsonType.String:
  109. var s = bsonReader.ReadString();
  110. bitArray = new BitArray(s.Length);
  111. for (int i = 0; i < s.Length; i++)
  112. {
  113. var c = s[i];
  114. switch (c)
  115. {
  116. case '0':
  117. break;
  118. case '1':
  119. bitArray[i] = true;
  120. break;
  121. default:
  122. throw new FormatException("String value is not a valid BitArray.");
  123. }
  124. }
  125. return bitArray;
  126. default:
  127. throw CreateCannotDeserializeFromBsonTypeException(bsonType);
  128. }
  129. }
  130. #pragma warning restore 618
  131. /// <summary>
  132. /// Serializes a value.
  133. /// </summary>
  134. /// <param name="context">The serialization context.</param>
  135. /// <param name="args">The serialization args.</param>
  136. /// <param name="value">The value.</param>
  137. protected override void SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, BitArray value)
  138. {
  139. var bsonWriter = context.Writer;
  140. switch (_representation)
  141. {
  142. case BsonType.Binary:
  143. if ((value.Length % 8) == 0)
  144. {
  145. bsonWriter.WriteBytes(GetBytes(value));
  146. }
  147. else
  148. {
  149. bsonWriter.WriteStartDocument();
  150. bsonWriter.WriteInt32("Length", value.Length);
  151. bsonWriter.WriteBytes("Bytes", GetBytes(value));
  152. bsonWriter.WriteEndDocument();
  153. }
  154. break;
  155. case BsonType.String:
  156. var sb = new StringBuilder(value.Length);
  157. for (int i = 0; i < value.Length; i++)
  158. {
  159. sb.Append(value[i] ? '1' : '0');
  160. }
  161. bsonWriter.WriteString(sb.ToString());
  162. break;
  163. default:
  164. var message = string.Format("'{0}' is not a valid BitArray representation.", _representation);
  165. throw new BsonSerializationException(message);
  166. }
  167. }
  168. /// <summary>
  169. /// Returns a serializer that has been reconfigured with the specified representation.
  170. /// </summary>
  171. /// <param name="representation">The representation.</param>
  172. /// <returns>The reconfigured serializer.</returns>
  173. public BitArraySerializer WithRepresentation(BsonType representation)
  174. {
  175. if (representation == _representation)
  176. {
  177. return this;
  178. }
  179. else
  180. {
  181. return new BitArraySerializer(representation);
  182. }
  183. }
  184. // private methods
  185. private byte[] GetBytes(BitArray bitArray)
  186. {
  187. // TODO: is there a more efficient way to do this?
  188. var bytes = new byte[(bitArray.Length + 7) / 8];
  189. var i = 0;
  190. foreach (bool value in bitArray)
  191. {
  192. if (value)
  193. {
  194. var index = i / 8;
  195. var bit = i % 8;
  196. bytes[index] |= (byte)(1 << bit);
  197. }
  198. i++;
  199. }
  200. return bytes;
  201. }
  202. // explicit interface implementations
  203. IBsonSerializer IRepresentationConfigurable.WithRepresentation(BsonType representation)
  204. {
  205. return WithRepresentation(representation);
  206. }
  207. }
  208. }