using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
-
+using System.Xml;
using Xunit;
namespace System.Runtime.Serialization.Tests
{
public static class DataContractSerializerHelper
{
- internal static T SerializeAndDeserialize<T>(T value, string baseline, DataContractSerializerSettings settings = null, Func<DataContractSerializer> serializerFactory = null, bool skipStringCompare = false)
+ internal static T SerializeAndDeserialize<T>(T value, string baseline, DataContractSerializerSettings settings = null, Func<DataContractSerializer> serializerFactory = null, bool skipStringCompare = false, bool verifyBinaryRoundTrip = true)
{
DataContractSerializer dcs;
if (serializerFactory != null)
dcs = (settings != null) ? new DataContractSerializer(typeof(T), settings) : new DataContractSerializer(typeof(T));
}
+ T deserialized;
using (MemoryStream ms = new MemoryStream())
{
dcs.WriteObject(ms, value);
}
ms.Position = 0;
- T deserialized = (T)dcs.ReadObject(ms);
+ deserialized = (T)dcs.ReadObject(ms);
+ }
+
+ if (verifyBinaryRoundTrip)
+ {
+ RoundTripBinarySerialization<T>(value, settings, serializerFactory);
+ }
- return deserialized;
+ return deserialized;
+ }
+
+ internal static T RoundTripBinarySerialization<T>(T value, DataContractSerializerSettings settings = null, Func<DataContractSerializer> serializerFactory = null)
+ {
+ DataContractSerializer dcs;
+ if (serializerFactory != null)
+ {
+ dcs = serializerFactory();
+ }
+ else
+ {
+ dcs = (settings != null) ? new DataContractSerializer(typeof(T), settings) : new DataContractSerializer(typeof(T));
+ }
+
+ using (MemoryStream ms = new MemoryStream())
+ using (XmlDictionaryWriter binWriter = XmlDictionaryWriter.CreateBinaryWriter(ms))
+ {
+ dcs.WriteObject(binWriter, value);
+ binWriter.Flush();
+ ms.Position = 0;
+ XmlDictionaryReader binReader = XmlDictionaryReader.CreateBinaryReader(ms, XmlDictionaryReaderQuotas.Max);
+ return (T)dcs.ReadObject(binReader);
}
}
}
=> BitConverter.IsLittleEndian ? ReadRawBytes<long>() : BinaryPrimitives.ReverseEndianness(ReadRawBytes<long>());
public float ReadSingle()
- => BinaryPrimitives.ReadSingleLittleEndian(GetBuffer(sizeof(float), out int offset).AsSpan(offset, sizeof(float)));
+ {
+ float f = BinaryPrimitives.ReadSingleLittleEndian(GetBuffer(sizeof(float), out int offset).AsSpan(offset, sizeof(float)));
+ Advance(sizeof(float));
+ return f;
+ }
public double ReadDouble()
- => BinaryPrimitives.ReadDoubleLittleEndian(GetBuffer(sizeof(double), out int offset).AsSpan(offset, sizeof(double)));
+ {
+ double d = BinaryPrimitives.ReadDoubleLittleEndian(GetBuffer(sizeof(double), out int offset).AsSpan(offset, sizeof(double)));
+ Advance(sizeof(double));
+ return d;
+ }
public decimal ReadDecimal()
{