public override object Deserialize(
BsonReader bsonReader,
Type nominalType,
Type actualType,
IBsonSerializationOptions options)
{
VerifyTypes(nominalType, actualType, typeof(byte));
var bsonType = bsonReader.GetCurrentBsonType();
byte value;
var lostData = false;
switch (bsonType)
{
case BsonType.Binary:
var bytes = bsonReader.ReadBytes();
if (bytes.Length != 1)
{
throw new Exception("Binary data for Byte must be exactly one byte long.");
}
value = bytes[0];
break;
case BsonType.Int32:
var int32Value = bsonReader.ReadInt32();
value = (byte)int32Value;
lostData = (int)value != int32Value;
break;
case BsonType.Int64:
var int64Value = bsonReader.ReadInt64();
value = (byte)int64Value;
lostData = (int)value != int64Value;
break;
case BsonType.String:
var s = bsonReader.ReadString();
if (s.Length == 1)
{
s = "0" + s;
}
value = byte.Parse(s, NumberStyles.HexNumber);
break;
default:
var message = string.Format("Cannot deserialize Byte from BsonType {0}.", bsonType);
throw new Exception(message);
}
if (lostData)
{
var message = string.Format("Data loss occurred when trying to convert from {0} to Byte.", bsonType);
throw new Exception(message);
}
return value;
}