ByteSerializer.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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.Globalization;
  17. using System.IO;
  18. using MongoDB.Bson.IO;
  19. using MongoDB.Bson.Serialization.Attributes;
  20. using MongoDB.Bson.Serialization.Options;
  21. namespace MongoDB.Bson.Serialization.Serializers
  22. {
  23. /// <summary>
  24. /// Represents a serializer for Bytes.
  25. /// </summary>
  26. public class ByteSerializer : StructSerializerBase<byte>, IRepresentationConfigurable<ByteSerializer>
  27. {
  28. // private fields
  29. private readonly BsonType _representation;
  30. // constructors
  31. /// <summary>
  32. /// Initializes a new instance of the <see cref="ByteSerializer"/> class.
  33. /// </summary>
  34. public ByteSerializer()
  35. : this(BsonType.Int32)
  36. {
  37. }
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="ByteSerializer"/> class.
  40. /// </summary>
  41. /// <param name="representation">The representation.</param>
  42. public ByteSerializer(BsonType representation)
  43. {
  44. switch (representation)
  45. {
  46. case BsonType.Binary:
  47. case BsonType.Int32:
  48. case BsonType.Int64:
  49. case BsonType.String:
  50. break;
  51. default:
  52. var message = string.Format("{0} is not a valid representation for a ByteSerializer.", representation);
  53. throw new ArgumentException(message);
  54. }
  55. _representation = representation;
  56. }
  57. // public properties
  58. /// <summary>
  59. /// Gets the representation.
  60. /// </summary>
  61. /// <value>
  62. /// The representation.
  63. /// </value>
  64. public BsonType Representation
  65. {
  66. get { return _representation; }
  67. }
  68. // public methods
  69. /// <summary>
  70. /// Deserializes a value.
  71. /// </summary>
  72. /// <param name="context">The deserialization context.</param>
  73. /// <param name="args">The deserialization args.</param>
  74. /// <returns>A deserialized value.</returns>
  75. public override byte Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
  76. {
  77. var bsonReader = context.Reader;
  78. byte value;
  79. var lostData = false;
  80. var bsonType = bsonReader.GetCurrentBsonType();
  81. switch (bsonType)
  82. {
  83. case BsonType.Binary:
  84. var bytes = bsonReader.ReadBytes();
  85. if (bytes.Length != 1)
  86. {
  87. throw new FormatException("Binary data for Byte must be exactly one byte long.");
  88. }
  89. value = bytes[0];
  90. break;
  91. case BsonType.Int32:
  92. var int32Value = bsonReader.ReadInt32();
  93. value = (byte)int32Value;
  94. lostData = (int)value != int32Value;
  95. break;
  96. case BsonType.Int64:
  97. var int64Value = bsonReader.ReadInt64();
  98. value = (byte)int64Value;
  99. lostData = (int)value != int64Value;
  100. break;
  101. case BsonType.String:
  102. var s = bsonReader.ReadString();
  103. if (s.Length == 1)
  104. {
  105. s = "0" + s;
  106. }
  107. value = byte.Parse(s, NumberStyles.HexNumber);
  108. break;
  109. default:
  110. throw CreateCannotDeserializeFromBsonTypeException(bsonType);
  111. }
  112. if (lostData)
  113. {
  114. var message = string.Format("Data loss occurred when trying to convert from {0} to Byte.", bsonType);
  115. throw new FormatException(message);
  116. }
  117. return value;
  118. }
  119. /// <summary>
  120. /// Serializes a value.
  121. /// </summary>
  122. /// <param name="context">The serialization context.</param>
  123. /// <param name="args">The serialization args.</param>
  124. /// <param name="value">The object.</param>
  125. public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, byte value)
  126. {
  127. var bsonWriter = context.Writer;
  128. switch (_representation)
  129. {
  130. case BsonType.Binary:
  131. bsonWriter.WriteBytes(new byte[] { value });
  132. break;
  133. case BsonType.Int32:
  134. bsonWriter.WriteInt32(value);
  135. break;
  136. case BsonType.Int64:
  137. bsonWriter.WriteInt64(value);
  138. break;
  139. case BsonType.String:
  140. bsonWriter.WriteString(string.Format("{0:x2}", value));
  141. break;
  142. default:
  143. var message = string.Format("'{0}' is not a valid Byte representation.", _representation);
  144. throw new BsonSerializationException(message);
  145. }
  146. }
  147. /// <summary>
  148. /// Returns a serializer that has been reconfigured with the specified representation.
  149. /// </summary>
  150. /// <param name="representation">The representation.</param>
  151. /// <returns>The reconfigured serializer.</returns>
  152. public ByteSerializer WithRepresentation(BsonType representation)
  153. {
  154. if (representation == _representation)
  155. {
  156. return this;
  157. }
  158. else
  159. {
  160. return new ByteSerializer(representation);
  161. }
  162. }
  163. // explicit interface implementations
  164. IBsonSerializer IRepresentationConfigurable.WithRepresentation(BsonType representation)
  165. {
  166. return WithRepresentation(representation);
  167. }
  168. }
  169. }