protected System.Runtime.Serialization.ObjectIDGenerator m_idGenerator;
protected System.Collections.Queue m_objectQueue;
protected Formatter() { }
- public abstract System.Runtime.Serialization.SerializationBinder Binder { get; set; }
+ public abstract System.Runtime.Serialization.SerializationBinder? Binder { get; set; }
public abstract System.Runtime.Serialization.StreamingContext Context { get; set; }
- public abstract System.Runtime.Serialization.ISurrogateSelector SurrogateSelector { get; set; }
+ public abstract System.Runtime.Serialization.ISurrogateSelector? SurrogateSelector { get; set; }
public abstract object Deserialize(System.IO.Stream serializationStream);
- protected virtual object GetNext(out long objID) { throw null; }
- protected virtual long Schedule(object obj) { throw null; }
+ protected virtual object? GetNext(out long objID) { throw null; }
+ protected virtual long Schedule(object? obj) { throw null; }
public abstract void Serialize(System.IO.Stream serializationStream, object graph);
protected abstract void WriteArray(object obj, string name, System.Type memberType);
protected abstract void WriteBoolean(bool val, string name);
protected abstract void WriteInt16(short val, string name);
protected abstract void WriteInt32(int val, string name);
protected abstract void WriteInt64(long val, string name);
- protected virtual void WriteMember(string memberName, object data) { }
- protected abstract void WriteObjectRef(object obj, string name, System.Type memberType);
+ protected virtual void WriteMember(string memberName, object? data) { }
+ protected abstract void WriteObjectRef(object? obj, string name, System.Type memberType);
[System.CLSCompliantAttribute(false)]
protected abstract void WriteSByte(sbyte val, string name);
protected abstract void WriteSingle(float val, string name);
[System.CLSCompliantAttribute(false)]
public sbyte ToSByte(object value) { throw null; }
public float ToSingle(object value) { throw null; }
- public string ToString(object value) { throw null; }
+ public string? ToString(object value) { throw null; }
[System.CLSCompliantAttribute(false)]
public ushort ToUInt16(object value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static partial class FormatterServices
{
public static void CheckTypeSecurity(System.Type t, System.Runtime.Serialization.Formatters.TypeFilterLevel securityLevel) { }
- public static object[] GetObjectData(object obj, System.Reflection.MemberInfo[] members) { throw null; }
+ public static object?[] GetObjectData(object obj, System.Reflection.MemberInfo[] members) { throw null; }
public static object GetSafeUninitializedObject(System.Type type) { throw null; }
public static System.Reflection.MemberInfo[] GetSerializableMembers(System.Type type) { throw null; }
public static System.Reflection.MemberInfo[] GetSerializableMembers(System.Type type, System.Runtime.Serialization.StreamingContext context) { throw null; }
public static System.Runtime.Serialization.ISerializationSurrogate GetSurrogateForCyclicalReference(System.Runtime.Serialization.ISerializationSurrogate innerSurrogate) { throw null; }
- public static System.Type GetTypeFromAssembly(System.Reflection.Assembly assem, string name) { throw null; }
+ public static System.Type? GetTypeFromAssembly(System.Reflection.Assembly assem, string name) { throw null; }
public static object GetUninitializedObject(System.Type type) { throw null; }
- public static object PopulateObjectMembers(object obj, System.Reflection.MemberInfo[] members, object[] data) { throw null; }
+ public static object PopulateObjectMembers(object obj, System.Reflection.MemberInfo[] members, object?[] data) { throw null; }
}
public partial interface IFormatter
{
- System.Runtime.Serialization.SerializationBinder Binder { get; set; }
+ System.Runtime.Serialization.SerializationBinder? Binder { get; set; }
System.Runtime.Serialization.StreamingContext Context { get; set; }
- System.Runtime.Serialization.ISurrogateSelector SurrogateSelector { get; set; }
+ System.Runtime.Serialization.ISurrogateSelector? SurrogateSelector { get; set; }
object Deserialize(System.IO.Stream serializationStream);
void Serialize(System.IO.Stream serializationStream, object graph);
}
public partial interface ISerializationSurrogate
{
void GetObjectData(object obj, System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
- object SetObjectData(object obj, System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.ISurrogateSelector selector);
+ object SetObjectData(object obj, System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.ISurrogateSelector? selector);
}
public partial interface ISurrogateSelector
{
void ChainSelector(System.Runtime.Serialization.ISurrogateSelector selector);
- System.Runtime.Serialization.ISurrogateSelector GetNextSelector();
- System.Runtime.Serialization.ISerializationSurrogate GetSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, out System.Runtime.Serialization.ISurrogateSelector selector);
+ System.Runtime.Serialization.ISurrogateSelector? GetNextSelector();
+ System.Runtime.Serialization.ISerializationSurrogate? GetSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, out System.Runtime.Serialization.ISurrogateSelector selector);
}
public partial class ObjectIDGenerator
{
}
public partial class ObjectManager
{
- public ObjectManager(System.Runtime.Serialization.ISurrogateSelector selector, System.Runtime.Serialization.StreamingContext context) { }
+ public ObjectManager(System.Runtime.Serialization.ISurrogateSelector? selector, System.Runtime.Serialization.StreamingContext context) { }
public virtual void DoFixups() { }
- public virtual object GetObject(long objectID) { throw null; }
+ public virtual object? GetObject(long objectID) { throw null; }
public virtual void RaiseDeserializationEvent() { }
public void RaiseOnDeserializingEvent(object obj) { }
public virtual void RecordArrayElementFixup(long arrayToBeFixed, int index, long objectRequired) { }
public virtual void RecordFixup(long objectToBeFixed, System.Reflection.MemberInfo member, long objectRequired) { }
public virtual void RegisterObject(object obj, long objectID) { }
public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo info) { }
- public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo info, long idOfContainingObj, System.Reflection.MemberInfo member) { }
- public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo info, long idOfContainingObj, System.Reflection.MemberInfo member, int[] arrayIndex) { }
+ public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo? info, long idOfContainingObj, System.Reflection.MemberInfo? member) { }
+ public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo? info, long idOfContainingObj, System.Reflection.MemberInfo? member, int[]? arrayIndex) { }
}
public abstract partial class SerializationBinder
{
protected SerializationBinder() { }
- public virtual void BindToName(System.Type serializedType, out string assemblyName, out string typeName) { throw null; }
- public abstract System.Type BindToType(string assemblyName, string typeName);
+ public virtual void BindToName(System.Type serializedType, out string? assemblyName, out string? typeName) { throw null; }
+ public abstract System.Type? BindToType(string assemblyName, string typeName);
}
public sealed partial class SerializationObjectManager
{
public SurrogateSelector() { }
public virtual void AddSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, System.Runtime.Serialization.ISerializationSurrogate surrogate) { }
public virtual void ChainSelector(System.Runtime.Serialization.ISurrogateSelector selector) { }
- public virtual System.Runtime.Serialization.ISurrogateSelector GetNextSelector() { throw null; }
- public virtual System.Runtime.Serialization.ISerializationSurrogate GetSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, out System.Runtime.Serialization.ISurrogateSelector selector) { throw null; }
+ public virtual System.Runtime.Serialization.ISurrogateSelector? GetNextSelector() { throw null; }
+ public virtual System.Runtime.Serialization.ISerializationSurrogate? GetSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context, out System.Runtime.Serialization.ISurrogateSelector selector) { throw null; }
public virtual void RemoveSurrogate(System.Type type, System.Runtime.Serialization.StreamingContext context) { }
}
}
}
public partial interface IFieldInfo
{
- string[] FieldNames { get; set; }
- System.Type[] FieldTypes { get; set; }
+ string[]? FieldNames { get; set; }
+ System.Type[]? FieldTypes { get; set; }
}
public enum TypeFilterLevel
{
public sealed partial class BinaryFormatter : System.Runtime.Serialization.IFormatter
{
public BinaryFormatter() { }
- public BinaryFormatter(System.Runtime.Serialization.ISurrogateSelector selector, System.Runtime.Serialization.StreamingContext context) { }
+ public BinaryFormatter(System.Runtime.Serialization.ISurrogateSelector? selector, System.Runtime.Serialization.StreamingContext context) { }
public System.Runtime.Serialization.Formatters.FormatterAssemblyStyle AssemblyFormat { get { throw null; } set { } }
- public System.Runtime.Serialization.SerializationBinder Binder { get { throw null; } set { } }
+ public System.Runtime.Serialization.SerializationBinder? Binder { get { throw null; } set { } }
public System.Runtime.Serialization.StreamingContext Context { get { throw null; } set { } }
public System.Runtime.Serialization.Formatters.TypeFilterLevel FilterLevel { get { throw null; } set { } }
- public System.Runtime.Serialization.ISurrogateSelector SurrogateSelector { get { throw null; } set { } }
+ public System.Runtime.Serialization.ISurrogateSelector? SurrogateSelector { get { throw null; } set { } }
public System.Runtime.Serialization.Formatters.FormatterTypeStyle TypeFormat { get { throw null; } set { } }
public object Deserialize(System.IO.Stream serializationStream) { throw null; }
public void Serialize(System.IO.Stream serializationStream, object graph) { }
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Configurations>netcoreapp-Debug;netcoreapp-Release</Configurations>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System.Runtime.Serialization.Formatters.cs" />
<RootNamespace>System.Runtime.Serialization.Formatters</RootNamespace>
<NoWarn>$(NoWarn);CS1573</NoWarn>
<Configurations>netcoreapp-Unix-Debug;netcoreapp-Unix-Release;netcoreapp-Windows_NT-Debug;netcoreapp-Windows_NT-Release</Configurations>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System.Runtime.Serialization.Formatters.TypeForwards.cs" />
namespace System.Runtime.Serialization
{
- internal delegate void DeserializationEventHandler(object sender);
+ internal delegate void DeserializationEventHandler(object? sender);
public delegate void SerializationEventHandler(StreamingContext context);
}
public abstract object Deserialize(Stream serializationStream);
- protected virtual object GetNext(out long objID)
+ protected virtual object? GetNext(out long objID)
{
if (m_objectQueue.Count == 0)
{
return null;
}
- object obj = m_objectQueue.Dequeue();
+ object obj = m_objectQueue.Dequeue()!;
bool isNew;
objID = m_idGenerator.HasId(obj, out isNew);
return obj;
}
- protected virtual long Schedule(object obj)
+ protected virtual long Schedule(object? obj)
{
if (obj == null)
{
protected abstract void WriteInt64(long val, string name);
- protected abstract void WriteObjectRef(object obj, string name, Type memberType);
+ protected abstract void WriteObjectRef(object? obj, string name, Type memberType);
- protected virtual void WriteMember(string memberName, object data)
+ protected virtual void WriteMember(string memberName, object? data)
{
if (data == null)
{
protected abstract void WriteValueType(object obj, string name, Type memberType);
- public abstract ISurrogateSelector SurrogateSelector { get; set; }
+ public abstract ISurrogateSelector? SurrogateSelector { get; set; }
- public abstract SerializationBinder Binder { get; set; }
+ public abstract SerializationBinder? Binder { get; set; }
public abstract StreamingContext Context { get; set; }
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
return System.Convert.ToDateTime(value, CultureInfo.InvariantCulture);
}
- public string ToString(object value)
+ public string? ToString(object value)
{
if (value == null) ThrowValueNullException();
return System.Convert.ToString(value, CultureInfo.InvariantCulture);
}
+ [DoesNotReturn]
private static void ThrowValueNullException()
{
throw new ArgumentNullException("value");
// If this class doesn't extend directly from object, walk its hierarchy and
// get all of the private and assembly-access fields (e.g. all fields that aren't
// virtual) and include them in the list of things to be serialized.
- Type parentType = type.BaseType;
+ Type? parentType = type.BaseType;
if (parentType != null && parentType != typeof(object))
{
- Type[] parentTypes;
- int parentTypeCount;
- bool classNamesUnique = GetParentTypes(parentType, out parentTypes, out parentTypeCount);
+ bool classNamesUnique = GetParentTypes(parentType, out Type[]? parentTypes, out int parentTypeCount);
if (parentTypeCount > 0)
{
var allMembers = new List<FieldInfo>();
for (int i = 0; i < parentTypeCount; i++)
{
- parentType = parentTypes[i];
+ parentType = parentTypes![i];
if (!parentType.IsSerializable)
{
throw new SerializationException(SR.Format(SR.Serialization_NonSerType, parentType.FullName, parentType.Module.Assembly.FullName));
}
FieldInfo[] typeFields = parentType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
- string typeName = classNamesUnique ? parentType.Name : parentType.FullName;
+ string typeName = classNamesUnique ? parentType.Name : parentType.FullName!;
foreach (FieldInfo field in typeFields)
{
// Family and Assembly fields will be gathered by the type itself.
}
}
- private static bool GetParentTypes(Type parentType, out Type[] parentTypes, out int parentTypeCount)
+ private static bool GetParentTypes(Type parentType, out Type[]? parentTypes, out int parentTypeCount)
{
parentTypes = null;
parentTypeCount = 0;
// typeName to prefix the Field names in SerializationFieldInfo
bool unique = true;
Type objectType = typeof(object);
- for (Type t1 = parentType; t1 != objectType; t1 = t1.BaseType)
+ for (Type t1 = parentType; t1 != objectType; t1 = t1.BaseType!)
{
if (t1.IsInterface)
{
string t1Name = t1.Name;
for (int i = 0; unique && i < parentTypeCount; i++)
{
- string t2Name = parentTypes[i].Name;
+ string t2Name = parentTypes![i].Name;
if (t2Name.Length == t1Name.Length && t2Name[0] == t1Name[0] && t1Name == t2Name)
{
unique = false;
public static object GetSafeUninitializedObject(Type type) => RuntimeHelpers.GetUninitializedObject(type);
- internal static void SerializationSetValue(MemberInfo fi, object target, object value)
+ internal static void SerializationSetValue(MemberInfo fi, object? target, object? value)
{
Debug.Assert(fi != null);
- var serField = fi as FieldInfo;
- if (serField != null)
+ if (fi is FieldInfo serField)
{
serField.SetValue(target, value);
return;
throw new ArgumentException(SR.Argument_InvalidFieldInfo);
}
- public static object PopulateObjectMembers(object obj, MemberInfo[] members, object[] data)
+ public static object PopulateObjectMembers(object obj, MemberInfo[] members, object?[] data)
{
if (obj == null)
{
// If we find an empty, it means that the value was never set during deserialization.
// This is either a forward reference or a null. In either case, this may break some of the
// invariants mantained by the setter, so we'll do nothing with it for right now.
- object value = data[i];
+ object? value = data[i];
if (value == null)
{
continue;
}
// If it's a field, set its value.
- FieldInfo field = member as FieldInfo;
- if (field != null)
+ if (member is FieldInfo field)
{
field.SetValue(obj, data[i]);
continue;
return obj;
}
- public static object[] GetObjectData(object obj, MemberInfo[] members)
+ public static object?[] GetObjectData(object obj, MemberInfo[] members)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(members));
}
- object[] data = new object[members.Length];
+ object?[] data = new object[members.Length];
for (int i = 0; i < members.Length; i++)
{
MemberInfo member = members[i];
throw new ArgumentNullException(nameof(members), SR.Format(SR.ArgumentNull_NullMember, i));
}
- FieldInfo field = member as FieldInfo;
+ FieldInfo? field = member as FieldInfo;
if (field == null)
{
throw new SerializationException(SR.Serialization_UnknownMemberInfo);
return new SurrogateForCyclicalReference(innerSurrogate);
}
- public static Type GetTypeFromAssembly(Assembly assem, string name)
+ public static Type? GetTypeFromAssembly(Assembly assem, string name)
{
if (assem == null)
{
return Assembly.Load(new AssemblyName(assemblyName));
}
- internal static Assembly LoadAssemblyFromStringNoThrow(string assemblyName)
+ internal static Assembly? LoadAssemblyFromStringNoThrow(string assemblyName)
{
try
{
Type attributedType = type;
while (attributedType.HasElementType)
{
- attributedType = attributedType.GetElementType();
+ attributedType = attributedType.GetElementType()!;
}
foreach (Attribute first in attributedType.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false))
}
hasTypeForwardedFrom = false;
- return type.Assembly.FullName;
+ return type.Assembly.FullName!;
}
internal static string GetClrTypeFullName(Type type)
{
int rank = type.GetArrayRank();
Debug.Assert(rank >= 1);
- string typeName = GetClrTypeFullName(type.GetElementType());
+ string typeName = GetClrTypeFullName(type.GetElementType()!);
return rank == 1 ?
typeName + "[]" :
typeName + "[" + new string(',', rank - 1) + "]";
{
if (!type.IsGenericType)
{
- return type.FullName;
+ return type.FullName!;
}
var builder = new StringBuilder(type.GetGenericTypeDefinition().FullName).Append("[");
_innerSurrogate.GetObjectData(obj, info, context);
}
- public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
+ public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector? selector)
{
return _innerSurrogate.SetObjectData(obj, info, context, selector);
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
+
namespace System.Runtime.Serialization.Formatters.Binary
{
internal sealed class BinaryArray : IStreamable
{
internal int _objectId;
internal int _rank;
- internal int[] _lengthA;
- internal int[] _lowerBoundA;
+ internal int[]? _lengthA;
+ internal int[]? _lowerBoundA;
internal BinaryTypeEnum _binaryTypeEnum;
- internal object _typeInformation;
+ internal object? _typeInformation;
internal int _assemId = 0;
private BinaryHeaderEnum _binaryHeaderEnum;
internal BinaryArrayTypeEnum _binaryArrayTypeEnum;
_binaryHeaderEnum = binaryHeaderEnum;
}
- internal void Set(int objectId, int rank, int[] lengthA, int[] lowerBoundA, BinaryTypeEnum binaryTypeEnum, object typeInformation, BinaryArrayTypeEnum binaryArrayTypeEnum, int assemId)
+ internal void Set(int objectId, int rank, int[] lengthA, int[]? lowerBoundA, BinaryTypeEnum binaryTypeEnum, object? typeInformation, BinaryArrayTypeEnum binaryArrayTypeEnum, int assemId)
{
_objectId = objectId;
_binaryArrayTypeEnum = binaryArrayTypeEnum;
public void Write(BinaryFormatterWriter output)
{
+ Debug.Assert(_lengthA != null);
switch (_binaryHeaderEnum)
{
case BinaryHeaderEnum.ArraySinglePrimitive:
output.WriteByte((byte)_binaryHeaderEnum);
output.WriteInt32(_objectId);
output.WriteInt32(_lengthA[0]);
- output.WriteByte((byte)((InternalPrimitiveTypeE)_typeInformation));
+ output.WriteByte((byte)((InternalPrimitiveTypeE)_typeInformation!));
break;
case BinaryHeaderEnum.ArraySingleString:
output.WriteByte((byte)_binaryHeaderEnum);
(_binaryArrayTypeEnum == BinaryArrayTypeEnum.JaggedOffset) ||
(_binaryArrayTypeEnum == BinaryArrayTypeEnum.RectangularOffset))
{
+ Debug.Assert(_lowerBoundA != null);
for (int i = 0; i < _rank; i++)
{
output.WriteInt32(_lowerBoundA[i]);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
+
namespace System.Runtime.Serialization.Formatters.Binary
{
internal sealed class BinaryAssembly : IStreamable
{
internal int _assemId;
- internal string _assemblyString;
+ internal string? _assemblyString;
internal BinaryAssembly() { }
{
output.WriteByte((byte)BinaryHeaderEnum.Assembly);
output.WriteInt32(_assemId);
+ Debug.Assert(_assemblyString != null);
output.WriteString(_assemblyString);
}
internal sealed class BinaryAssemblyInfo
{
internal string _assemblyString;
- private Assembly _assembly;
+ private Assembly? _assembly;
internal BinaryAssemblyInfo(string assemblyString)
{
_assemblyString = assemblyString;
}
- internal BinaryAssemblyInfo(string assemblyString, Assembly assembly) : this(assemblyString)
+ internal BinaryAssemblyInfo(string assemblyString, Assembly? assembly) : this(assemblyString)
{
_assembly = assembly;
}
{
private static readonly ConcurrentDictionary<Type, TypeInformation> s_typeNameCache = new ConcurrentDictionary<Type, TypeInformation>();
- internal ISurrogateSelector _surrogates;
+ internal ISurrogateSelector? _surrogates;
internal StreamingContext _context;
- internal SerializationBinder _binder;
+ internal SerializationBinder? _binder;
internal FormatterTypeStyle _typeFormat = FormatterTypeStyle.TypesAlways; // For version resiliency, always put out types
internal FormatterAssemblyStyle _assemblyFormat = FormatterAssemblyStyle.Simple;
internal TypeFilterLevel _securityLevel = TypeFilterLevel.Full;
- internal object[] _crossAppDomainArray = null;
+ internal object[]? _crossAppDomainArray = null;
public FormatterTypeStyle TypeFormat { get { return _typeFormat; } set { _typeFormat = value; } }
public FormatterAssemblyStyle AssemblyFormat { get { return _assemblyFormat; } set { _assemblyFormat = value; } }
public TypeFilterLevel FilterLevel { get { return _securityLevel; } set { _securityLevel = value; } }
- public ISurrogateSelector SurrogateSelector { get { return _surrogates; } set { _surrogates = value; } }
- public SerializationBinder Binder { get { return _binder; } set { _binder = value; } }
+ public ISurrogateSelector? SurrogateSelector { get { return _surrogates; } set { _surrogates = value; } }
+ public SerializationBinder? Binder { get { return _binder; } set { _binder = value; } }
public StreamingContext Context { get { return _context; } set { _context = value; } }
public BinaryFormatter() : this(null, new StreamingContext(StreamingContextStates.All))
{
}
- public BinaryFormatter(ISurrogateSelector selector, StreamingContext context)
+ public BinaryFormatter(ISurrogateSelector? selector, StreamingContext context)
{
_surrogates = selector;
_context = context;
private readonly Stream _outputStream;
private readonly FormatterTypeStyle _formatterTypeStyle;
- private readonly ObjectWriter _objectWriter = null;
- private readonly BinaryWriter _dataWriter = null;
+ private readonly ObjectWriter _objectWriter;
+ private readonly BinaryWriter _dataWriter;
private int _consecutiveNullArrayEntryCount = 0;
- private Dictionary<string, ObjectMapInfo> _objectMapTable;
-
- private BinaryObject _binaryObject;
- private BinaryObjectWithMap _binaryObjectWithMap;
- private BinaryObjectWithMapTyped _binaryObjectWithMapTyped;
- private BinaryObjectString _binaryObjectString;
- private BinaryArray _binaryArray;
- private byte[] _byteBuffer = null;
- private MemberPrimitiveUnTyped _memberPrimitiveUnTyped;
- private MemberPrimitiveTyped _memberPrimitiveTyped;
- private ObjectNull _objectNull;
- private MemberReference _memberReference;
- private BinaryAssembly _binaryAssembly;
+ private Dictionary<string, ObjectMapInfo>? _objectMapTable;
+
+ private BinaryObject? _binaryObject;
+ private BinaryObjectWithMap? _binaryObjectWithMap;
+ private BinaryObjectWithMapTyped? _binaryObjectWithMapTyped;
+ private BinaryObjectString? _binaryObjectString;
+ private BinaryArray? _binaryArray;
+ private byte[]? _byteBuffer = null;
+ private MemberPrimitiveUnTyped? _memberPrimitiveUnTyped;
+ private MemberPrimitiveTyped? _memberPrimitiveTyped;
+ private ObjectNull? _objectNull;
+ private MemberReference? _memberReference;
+ private BinaryAssembly? _binaryAssembly;
internal BinaryFormatterWriter(Stream outputStream, ObjectWriter objectWriter, FormatterTypeStyle formatterTypeStyle)
{
record.Write(this);
}
- internal void WriteObject(NameInfo nameInfo, NameInfo typeNameInfo, int numMembers, string[] memberNames, Type[] memberTypes, WriteObjectInfo[] memberObjectInfos)
+ internal void WriteObject(NameInfo nameInfo, NameInfo? typeNameInfo, int numMembers, string[] memberNames, Type[] memberTypes, WriteObjectInfo[] memberObjectInfos)
{
InternalWriteItemNull();
int assemId;
int objectId = (int)nameInfo._objectId;
- string objectName = objectId < 0 ?
- objectName = typeNameInfo.NIname : // Nested Object
- objectName = nameInfo.NIname; // Non-Nested
+ Debug.Assert(typeNameInfo != null); // Explicitly called with null, asserting for now https://github.com/dotnet/corefx/issues/42393
+ string? objectName = objectId < 0 ?
+ typeNameInfo.NIname : // Nested Object
+ nameInfo.NIname; // Non-Nested
if (_objectMapTable == null)
{
_objectMapTable = new Dictionary<string, ObjectMapInfo>();
}
- ObjectMapInfo objectMapInfo;
- if (_objectMapTable.TryGetValue(objectName, out objectMapInfo) &&
+ Debug.Assert(objectName != null);
+ if (_objectMapTable.TryGetValue(objectName, out ObjectMapInfo? objectMapInfo) &&
objectMapInfo.IsCompatible(numMembers, memberNames, memberTypes))
{
// Object
{
// ObjectWithMapTyped
var binaryTypeEnumA = new BinaryTypeEnum[numMembers];
- var typeInformationA = new object[numMembers];
+ var typeInformationA = new object?[numMembers];
var assemIdA = new int[numMembers];
for (int i = 0; i < numMembers; i++)
{
- object typeInformation = null;
+ object? typeInformation = null;
binaryTypeEnumA[i] = BinaryTypeConverter.GetBinaryTypeInfo(memberTypes[i], memberObjectInfos[i], null, _objectWriter, out typeInformation, out assemId);
typeInformationA[i] = typeInformation;
assemIdA[i] = assemId;
}
}
- internal void WriteObjectString(int objectId, string value)
+ internal void WriteObjectString(int objectId, string? value)
{
InternalWriteItemNull();
_binaryObjectString.Write(this);
}
- internal void WriteSingleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, Array array)
+ internal void WriteSingleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo? objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, Array array)
{
InternalWriteItemNull();
BinaryArrayTypeEnum binaryArrayTypeEnum;
var lengthA = new int[1];
lengthA[0] = length;
- int[] lowerBoundA = null;
- object typeInformation = null;
+ int[]? lowerBoundA = null;
+ object? typeInformation = null;
if (lowerBound == 0)
{
int assemId;
BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(
- arrayElemTypeNameInfo._type, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId);
+ arrayElemTypeNameInfo._type!, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId);
if (_binaryArray == null)
{
private void WriteArrayAsBytes(Array array, int typeLength)
{
InternalWriteItemNull();
- int byteLength = array.Length * typeLength;
int arrayOffset = 0;
if (_byteBuffer == null)
{
}
}
- internal void WriteJaggedArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound)
+ internal void WriteJaggedArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo? objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound)
{
InternalWriteItemNull();
BinaryArrayTypeEnum binaryArrayTypeEnum;
var lengthA = new int[1];
lengthA[0] = length;
- int[] lowerBoundA = null;
- object typeInformation = null;
+ int[]? lowerBoundA = null;
+ object? typeInformation = null;
int assemId = 0;
if (lowerBound == 0)
lowerBoundA[0] = lowerBound;
}
- BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId);
+ BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type!, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId);
if (_binaryArray == null)
{
_binaryArray.Write(this);
}
- internal void WriteRectangleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int rank, int[] lengthA, int[] lowerBoundA)
+ internal void WriteRectangleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo? objectInfo, NameInfo arrayElemTypeNameInfo, int rank, int[] lengthA, int[] lowerBoundA)
{
InternalWriteItemNull();
BinaryArrayTypeEnum binaryArrayTypeEnum = BinaryArrayTypeEnum.Rectangular;
- object typeInformation = null;
+ object? typeInformation = null;
int assemId = 0;
- BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId);
+ BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type!, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId);
if (_binaryArray == null)
{
_binaryArray.Write(this);
}
- internal void WriteObjectByteArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, byte[] byteA)
+ internal void WriteObjectByteArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo? objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, byte[] byteA)
{
InternalWriteItemNull();
WriteSingleArray(memberNameInfo, arrayNameInfo, objectInfo, arrayElemTypeNameInfo, length, lowerBound, byteA);
InternalWriteItemNull();
}
- internal void WriteMemberString(NameInfo memberNameInfo, NameInfo typeNameInfo, string value)
+ internal void WriteMemberString(NameInfo memberNameInfo, NameInfo typeNameInfo, string? value)
{
InternalWriteItemNull();
WriteObjectString((int)typeNameInfo._objectId, value);
WriteMemberObjectRef(nameInfo, idRef);
}
- internal void WriteAssembly(Type type, string assemblyString, int assemId, bool isNew)
+ internal void WriteAssembly(Type? type, string assemblyString, int assemId, bool isNew)
{
//If the file being tested wasn't built as an assembly, then we're going to get null back
//for the assembly name. This is very unfortunate.
}
// Method to write a value onto a stream given its primitive type code
- internal void WriteValue(InternalPrimitiveTypeE code, object value)
+ internal void WriteValue(InternalPrimitiveTypeE code, object? value)
{
switch (code)
{
case InternalPrimitiveTypeE.UInt32: WriteUInt32(Convert.ToUInt32(value, CultureInfo.InvariantCulture)); break;
case InternalPrimitiveTypeE.UInt64: WriteUInt64(Convert.ToUInt64(value, CultureInfo.InvariantCulture)); break;
case InternalPrimitiveTypeE.Decimal: WriteDecimal(Convert.ToDecimal(value, CultureInfo.InvariantCulture)); break;
- case InternalPrimitiveTypeE.TimeSpan: WriteTimeSpan((TimeSpan)value); break;
- case InternalPrimitiveTypeE.DateTime: WriteDateTime((DateTime)value); break;
+ case InternalPrimitiveTypeE.TimeSpan: WriteTimeSpan((TimeSpan)value!); break;
+ case InternalPrimitiveTypeE.DateTime: WriteDateTime((DateTime)value!); break;
default: throw new SerializationException(SR.Format(SR.Serialization_TypeCode, code.ToString()));
}
}
_memberTypes = memberTypes;
}
- internal bool IsCompatible(int numMembers, string[] memberNames, Type[] memberTypes)
+ internal bool IsCompatible(int numMembers, string[] memberNames, Type[]? memberTypes)
{
if (_numMembers != numMembers)
{
using System.Threading;
using System.Collections.Generic;
using System.Reflection;
+using System.Diagnostics;
namespace System.Runtime.Serialization.Formatters.Binary
{
internal sealed class WriteObjectInfo
{
internal int _objectInfoId;
- internal object _obj;
- internal Type _objectType;
+ internal object? _obj;
+ internal Type? _objectType;
internal bool _isSi = false;
internal bool _isNamed = false;
internal bool _isArray = false;
- internal SerializationInfo _si = null;
- internal SerObjectInfoCache _cache = null;
+ internal SerializationInfo? _si = null;
+ internal SerObjectInfoCache _cache = null!; // Initiated before use
- internal object[] _memberData = null;
- internal ISerializationSurrogate _serializationSurrogate = null;
+ internal object?[]? _memberData = null;
+ internal ISerializationSurrogate? _serializationSurrogate = null;
internal StreamingContext _context;
- internal SerObjectInfoInit _serObjectInfoInit = null;
+ internal SerObjectInfoInit? _serObjectInfoInit = null;
// Writing and Parsing information
internal long _objectId;
internal long _assemId;
// Binder information
- private string _binderTypeName;
- private string _binderAssemblyString;
+ private string? _binderTypeName;
+ private string? _binderAssemblyString;
internal WriteObjectInfo() { }
internal void ObjectEnd()
{
+ Debug.Assert(_serObjectInfoInit != null);
PutObjectInfo(_serObjectInfoInit, this);
}
_isNamed = false;
_isArray = false;
_si = null;
- _cache = null;
+ _cache = null!;
_memberData = null;
// Writing and Parsing information
_binderAssemblyString = null;
}
- internal static WriteObjectInfo Serialize(object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
+ internal static WriteObjectInfo Serialize(object obj, ISurrogateSelector? surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder? binder)
{
WriteObjectInfo woi = GetObjectInfo(serObjectInfoInit);
woi.InitSerialize(obj, surrogateSelector, context, serObjectInfoInit, converter, objectWriter, binder);
}
// Write constructor
- internal void InitSerialize(object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
+ internal void InitSerialize(object obj, ISurrogateSelector? surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder? binder)
{
_context = context;
_obj = obj;
}
}
- internal static WriteObjectInfo Serialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder)
+ internal static WriteObjectInfo Serialize(Type objectType, ISurrogateSelector? surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder? binder)
{
WriteObjectInfo woi = GetObjectInfo(serObjectInfoInit);
woi.InitSerialize(objectType, surrogateSelector, context, serObjectInfoInit, converter, binder);
}
// Write Constructor used for array types or null members
- internal void InitSerialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder)
+ internal void InitSerialize(Type objectType, ISurrogateSelector? surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder? binder)
{
_objectType = objectType;
_context = context;
InvokeSerializationBinder(binder);
- ISurrogateSelector surrogateSelectorTemp = null;
if (surrogateSelector != null)
{
- _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp);
+ _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out ISurrogateSelector surrogateSelectorTemp);
}
if (_serializationSurrogate != null)
private void InitSiWrite()
{
- SerializationInfoEnumerator siEnum = null;
+ SerializationInfoEnumerator? siEnum = null;
_isSi = true;
+ Debug.Assert(_si != null);
siEnum = _si.GetEnumerator();
int infoLength = 0;
// For ISerializable cache cannot be saved because each object instance can have different values
// BinaryWriter only puts the map on the wire if the ISerializable map cannot be reused.
- TypeInformation typeInformation = null;
+ TypeInformation? typeInformation = null;
string fullTypeName = _si.FullTypeName;
string assemblyString = _si.AssemblyName;
bool hasTypeForwardedFrom = false;
_isNamed = true;
}
- private static void CheckTypeForwardedFrom(SerObjectInfoCache cache, Type objectType, string binderAssemblyString)
+ private static void CheckTypeForwardedFrom(SerObjectInfoCache? cache, Type objectType, string? binderAssemblyString)
{
// nop
}
private void InitNoMembers()
{
- if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache))
+ Debug.Assert(_serObjectInfoInit != null && _objectType != null);
+ if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache!))
{
_cache = new SerObjectInfoCache(_objectType);
_serObjectInfoInit._seenBeforeTable.Add(_objectType, _cache);
private void InitMemberInfo()
{
- if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache))
+ Debug.Assert(_serObjectInfoInit != null && _objectType != null);
+ if (!_serObjectInfoInit._seenBeforeTable.TryGetValue(_objectType, out _cache!))
{
_cache = new SerObjectInfoCache(_objectType);
if (_obj != null)
{
- _memberData = FormatterServices.GetObjectData(_obj, _cache._memberInfos);
+ _memberData = FormatterServices.GetObjectData(_obj, _cache._memberInfos!);
}
_isNamed = true;
internal string GetAssemblyString() => _binderAssemblyString ?? _cache._assemblyString;
- private void InvokeSerializationBinder(SerializationBinder binder) =>
- binder?.BindToName(_objectType, out _binderAssemblyString, out _binderTypeName);
+ private void InvokeSerializationBinder(SerializationBinder? binder) =>
+ binder?.BindToName(_objectType!, out _binderAssemblyString, out _binderTypeName);
- internal void GetMemberInfo(out string[] outMemberNames, out Type[] outMemberTypes, out object[] outMemberData)
+ internal void GetMemberInfo(out string[]? outMemberNames, out Type[]? outMemberTypes, out object?[]? outMemberData)
{
outMemberNames = _cache._memberNames;
outMemberTypes = _cache._memberTypes;
if (!serObjectInfoInit._oiPool.IsEmpty())
{
- objectInfo = (WriteObjectInfo)serObjectInfoInit._oiPool.Pop();
+ objectInfo = (WriteObjectInfo)serObjectInfoInit._oiPool.Pop()!;
objectInfo.InternalInit();
}
else
internal int _objectInfoId;
internal static int _readObjectInfoCounter;
- internal Type _objectType;
+ internal Type? _objectType = null;
- internal ObjectManager _objectManager;
+ internal ObjectManager? _objectManager;
internal int _count;
internal bool _isTyped = false;
internal bool _isSimpleAssembly = false;
- internal SerObjectInfoCache _cache;
+ internal SerObjectInfoCache? _cache;
- internal string[] _wireMemberNames;
- internal Type[] _wireMemberTypes;
+ internal string[]? _wireMemberNames;
+ internal Type[]? _wireMemberTypes;
private int _lastPosition = 0;
- internal ISerializationSurrogate _serializationSurrogate = null;
+ internal ISerializationSurrogate? _serializationSurrogate = null;
internal StreamingContext _context;
// Si Read
- internal List<Type> _memberTypesList;
- internal SerObjectInfoInit _serObjectInfoInit = null;
- internal IFormatterConverter _formatterConverter;
+ internal List<Type>? _memberTypesList;
+ internal SerObjectInfoInit? _serObjectInfoInit = null;
+ internal IFormatterConverter? _formatterConverter = null;
internal ReadObjectInfo() { }
_lastPosition = 0;
}
- internal static ReadObjectInfo Create(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly)
+ internal static ReadObjectInfo Create(Type objectType, ISurrogateSelector? surrogateSelector, StreamingContext context, ObjectManager? objectManager, SerObjectInfoInit? serObjectInfoInit, IFormatterConverter? converter, bool bSimpleAssembly)
{
ReadObjectInfo roi = GetObjectInfo(serObjectInfoInit);
roi.Init(objectType, surrogateSelector, context, objectManager, serObjectInfoInit, converter, bSimpleAssembly);
return roi;
}
- internal void Init(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly)
+ internal void Init(Type objectType, ISurrogateSelector? surrogateSelector, StreamingContext context, ObjectManager? objectManager, SerObjectInfoInit? serObjectInfoInit, IFormatterConverter? converter, bool bSimpleAssembly)
{
_objectType = objectType;
_objectManager = objectManager;
InitReadConstructor(objectType, surrogateSelector, context);
}
- internal static ReadObjectInfo Create(Type objectType, string[] memberNames, Type[] memberTypes, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly)
+ internal static ReadObjectInfo Create(Type? objectType, string[] memberNames, Type[]? memberTypes, ISurrogateSelector? surrogateSelector, StreamingContext context, ObjectManager? objectManager, SerObjectInfoInit? serObjectInfoInit, IFormatterConverter? converter, bool bSimpleAssembly)
{
ReadObjectInfo roi = GetObjectInfo(serObjectInfoInit);
roi.Init(objectType, memberNames, memberTypes, surrogateSelector, context, objectManager, serObjectInfoInit, converter, bSimpleAssembly);
return roi;
}
- internal void Init(Type objectType, string[] memberNames, Type[] memberTypes, ISurrogateSelector surrogateSelector, StreamingContext context, ObjectManager objectManager, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, bool bSimpleAssembly)
+ internal void Init(Type? objectType, string[] memberNames, Type[]? memberTypes, ISurrogateSelector? surrogateSelector, StreamingContext context, ObjectManager? objectManager, SerObjectInfoInit? serObjectInfoInit, IFormatterConverter? converter, bool bSimpleAssembly)
{
_objectType = objectType;
_objectManager = objectManager;
}
}
- private void InitReadConstructor(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context)
+ private void InitReadConstructor(Type objectType, ISurrogateSelector? surrogateSelector, StreamingContext context)
{
if (objectType.IsArray)
{
return;
}
- ISurrogateSelector surrogateSelectorTemp = null;
+ ISurrogateSelector? surrogateSelectorTemp = null;
if (surrogateSelector != null)
{
_serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp);
private void InitNoMembers()
{
- _cache = new SerObjectInfoCache(_objectType);
+ _cache = new SerObjectInfoCache(_objectType!);
}
private void InitMemberInfo()
{
- _cache = new SerObjectInfoCache(_objectType);
- _cache._memberInfos = FormatterServices.GetSerializableMembers(_objectType, _context);
+ _cache = new SerObjectInfoCache(_objectType!);
+ _cache._memberInfos = FormatterServices.GetSerializableMembers(_objectType!, _context);
_count = _cache._memberInfos.Length;
_cache._memberNames = new string[_count];
_cache._memberTypes = new Type[_count];
}
// Get the memberInfo for a memberName
- internal MemberInfo GetMemberInfo(string name)
+ internal MemberInfo? GetMemberInfo(string? name)
{
if (_cache == null)
{
}
// Get the ObjectType for a memberName
- internal Type GetType(string name)
+ internal Type? GetType(string name)
{
int position = Position(name);
if (position == -1)
return null;
}
- Type type = _isTyped ? _cache._memberTypes[position] : _memberTypesList[position];
+ Type type = _isTyped ? _cache!._memberTypes![position] : _memberTypesList![position];
if (type == null)
{
throw new SerializationException(SR.Format(SR.Serialization_ISerializableTypes, _objectType + " " + name));
}
// Adds the value for a memberName
- internal void AddValue(string name, object value, ref SerializationInfo si, ref object[] memberData)
+ internal void AddValue(string name, object? value, ref SerializationInfo? si, ref object?[]? memberData)
{
if (_isSi)
{
+ Debug.Assert(si != null);
si.AddValue(name, value);
}
else
int position = Position(name);
if (position != -1)
{
+ Debug.Assert(memberData != null);
memberData[position] = value;
}
}
}
- internal void InitDataStore(ref SerializationInfo si, ref object[] memberData)
+ internal void InitDataStore(ref SerializationInfo? si, ref object?[]? memberData)
{
if (_isSi)
{
if (si == null)
{
- si = new SerializationInfo(_objectType, _formatterConverter);
+ Debug.Assert(_objectType != null);
+ si = new SerializationInfo(_objectType, _formatterConverter!);
}
}
else
{
if (memberData == null && _cache != null)
{
+ Debug.Assert(_cache._memberNames != null);
memberData = new object[_cache._memberNames.Length];
}
}
throw new SerializationException(SR.Serialization_CorruptedStream);
}
+ Debug.Assert(_cache != null && _cache._memberInfos != null);
_objectManager.RecordFixup(objectId, _cache._memberInfos[position], idRef);
}
}
}
// Fills in the values for an object
- internal void PopulateObjectMembers(object obj, object[] memberData)
+ internal void PopulateObjectMembers(object obj, object?[]? memberData)
{
if (!_isSi && memberData != null)
{
+ Debug.Assert(_cache != null && _cache._memberInfos != null);
FormatterServices.PopulateObjectMembers(obj, _cache._memberInfos, memberData);
}
}
// Specifies the position in the memberNames array of this name
- private int Position(string name)
+ private int Position(string? name)
{
if (_cache == null)
{
return -1;
}
+ Debug.Assert(_cache._memberNames != null);
if (_cache._memberNames.Length > 0 && _cache._memberNames[_lastPosition].Equals(name))
{
return _lastPosition;
}
// Return the member Types in order of memberNames
- internal Type[] GetMemberTypes(string[] inMemberNames, Type objectType)
+ internal Type[]? GetMemberTypes(string[] inMemberNames, Type? objectType)
{
if (_isSi)
{
return null;
}
+ Debug.Assert(_cache._memberInfos != null);
if (_cache._memberTypes == null)
{
_cache._memberTypes = new Type[_count];
if (!_isSimpleAssembly &&
_cache._memberInfos[i].GetCustomAttribute(typeof(OptionalFieldAttribute), inherit: false) == null)
{
+ Debug.Assert(_cache._memberNames != null);
throw new SerializationException(SR.Format(SR.Serialization_MissingMember, _cache._memberNames[i], objectType, typeof(OptionalFieldAttribute).FullName));
}
}
}
- private static ReadObjectInfo GetObjectInfo(SerObjectInfoInit serObjectInfoInit)
+ private static ReadObjectInfo GetObjectInfo(SerObjectInfoInit? serObjectInfoInit)
{
ReadObjectInfo roi = new ReadObjectInfo();
roi._objectInfoId = Interlocked.Increment(ref _readObjectInfoCounter);
internal readonly string _assemblyString;
internal readonly bool _hasTypeForwardedFrom;
- internal MemberInfo[] _memberInfos;
- internal string[] _memberNames;
- internal Type[] _memberTypes;
+ internal MemberInfo[]? _memberInfos;
+ internal string[]? _memberNames;
+ internal Type[]? _memberTypes;
internal SerObjectInfoCache(string typeName, string assemblyName, bool hasTypeForwardedFrom)
{
using System.IO;
using System.Reflection;
using System.Diagnostics;
+using System.Collections;
namespace System.Runtime.Serialization.Formatters.Binary
{
{
// System.Serializer information
internal Stream _stream;
- internal ISurrogateSelector _surrogates;
+ internal ISurrogateSelector? _surrogates;
internal StreamingContext _context;
- internal ObjectManager _objectManager;
+ internal ObjectManager? _objectManager;
internal InternalFE _formatterEnums;
- internal SerializationBinder _binder;
+ internal SerializationBinder? _binder;
// Top object and headers
internal long _topId;
internal bool _isSimpleAssembly = false;
- internal object _topObject;
- internal SerObjectInfoInit _serObjectInfoInit;
- internal IFormatterConverter _formatterConverter;
+ internal object? _topObject;
+ internal SerObjectInfoInit? _serObjectInfoInit;
+ internal IFormatterConverter? _formatterConverter;
// Stack of Object ParseRecords
- internal SerStack _stack;
+ internal SerStack? _stack;
// ValueType Fixup Stack
- private SerStack _valueFixupStack;
+ private SerStack? _valueFixupStack;
// Cross AppDomain
- internal object[] _crossAppDomainArray; //Set by the BinaryFormatter
+ internal object[]? _crossAppDomainArray; //Set by the BinaryFormatter
//MethodCall and MethodReturn are handled special for perf reasons
private bool _fullDeserialization;
// a single counter, only value types have a negative value. Need a way to handle older formats.
private const int ThresholdForValueTypeIds = int.MaxValue;
private bool _oldFormatDetected = false;
- private IntSizedArray _valTypeObjectIdTable;
+ private IntSizedArray? _valTypeObjectIdTable;
private readonly NameCache _typeCache = new NameCache();
- internal object TopObject
+ internal object? TopObject
{
get { return _topObject; }
set
}
}
- internal ObjectReader(Stream stream, ISurrogateSelector selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder binder)
+ internal ObjectReader(Stream stream, ISurrogateSelector? selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder? binder)
{
if (stream == null)
{
if (_fullDeserialization)
{
- _objectManager.DoFixups();
+ _objectManager!.DoFixups();
}
if (TopObject == null)
//So refresh it using topID.
if (HasSurrogate(TopObject.GetType()) && _topId != 0)//Not yet resolved
{
+ Debug.Assert(_objectManager != null);
TopObject = _objectManager.GetObject(_topId);
}
if (_fullDeserialization)
{
- _objectManager.RaiseDeserializationEvent(); // This will raise both IDeserialization and [OnDeserialized] events
+ _objectManager!.RaiseDeserializationEvent(); // This will raise both IDeserialization and [OnDeserialized] events
}
- return TopObject;
+ return TopObject!;
}
}
private bool HasSurrogate(Type t)
internal object CrossAppDomainArray(int index)
{
+ Debug.Assert(_crossAppDomainArray != null);
Debug.Assert(index < _crossAppDomainArray.Length, "[System.Runtime.Serialization.Formatters.BinaryObjectReader index out of range for CrossAppDomainArray]");
return _crossAppDomainArray[index];
}
return ReadObjectInfo.Create(objectType, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly);
}
- internal ReadObjectInfo CreateReadObjectInfo(Type objectType, string[] memberNames, Type[] memberTypes)
+ internal ReadObjectInfo CreateReadObjectInfo(Type? objectType, string[] memberNames, Type[]? memberTypes)
{
return ReadObjectInfo.Create(objectType, memberNames, memberTypes, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly);
}
}
// Parse the SerializedStreamHeader element. This is the first element in the stream if present
- private void ParseSerializedStreamHeader(ParseRecord pr) => _stack.Push(pr);
+ private void ParseSerializedStreamHeader(ParseRecord pr) => _stack!.Push(pr);
// Parse the SerializedStreamHeader end element. This is the last element in the stream if present
- private void ParseSerializedStreamHeaderEnd(ParseRecord pr) => _stack.Pop();
+ private void ParseSerializedStreamHeaderEnd(ParseRecord pr) => _stack!.Pop();
// New object encountered in stream
private void ParseObject(ParseRecord pr)
if (pr._parseTypeEnum == InternalParseTypeE.Object)
{
- _stack.Push(pr); // Nested objects member names are already on stack
+ _stack!.Push(pr); // Nested objects member names are already on stack
}
if (pr._objectTypeEnum == InternalObjectTypeE.Array)
}
else
{
- _stack.Pop();
- RegisterObject(pr._newObj, pr, (ParseRecord)_stack.Peek());
+ _stack!.Pop();
+ RegisterObject(pr._newObj, pr, (ParseRecord?)_stack.Peek());
return;
}
}
CheckSerializable(pr._dtType);
pr._newObj = FormatterServices.GetUninitializedObject(pr._dtType);
+ Debug.Assert(_objectManager != null);
// Run the OnDeserializing methods
_objectManager.RaiseOnDeserializingEvent(pr._newObj);
}
// End of object encountered in stream
private void ParseObjectEnd(ParseRecord pr)
{
- ParseRecord objectPr = (ParseRecord)_stack.Peek() ?? pr;
+ Debug.Assert(_stack != null);
+ ParseRecord objectPr = (ParseRecord?)_stack.Peek() ?? pr;
if (objectPr._objectPositionEnum == InternalObjectPositionE.Top)
{
}
_stack.Pop();
- ParseRecord parentPr = (ParseRecord)_stack.Peek();
+ ParseRecord? parentPr = (ParseRecord?)_stack.Peek();
if (objectPr._newObj == null)
{
return;
}
+ Debug.Assert(objectPr._objectInfo != null);
objectPr._objectInfo.PopulateObjectMembers(objectPr._newObj, objectPr._memberData);
// Registration is after object is populated
if (objectPr._isValueTypeFixup)
{
- ValueFixup fixup = (ValueFixup)ValueFixupStack.Pop(); //Value fixup
+ ValueFixup? fixup = (ValueFixup?)ValueFixupStack.Pop(); //Value fixup
+ Debug.Assert(fixup != null && parentPr != null);
fixup.Fixup(objectPr, parentPr); // Value fixup
}
{
long genId = pr._objectId;
+ Debug.Assert(_stack != null);
if (pr._arrayTypeEnum == InternalArrayTypeE.Base64)
{
+ Debug.Assert(pr._value != null);
// ByteArray
pr._newObj = pr._value.Length > 0 ?
Convert.FromBase64String(pr._value) :
TopObject = pr._newObj;
}
- ParseRecord parentPr = (ParseRecord)_stack.Peek();
+ ParseRecord? parentPr = (ParseRecord?)_stack.Peek();
// Base64 can be registered at this point because it is populated
RegisterObject(pr._newObj, pr, parentPr);
TopObject = pr._newObj;
}
- ParseRecord parentPr = (ParseRecord)_stack.Peek();
+ ParseRecord? parentPr = (ParseRecord?)_stack.Peek();
// Primitive typed array can be registered at this point because it is populated
RegisterObject(pr._newObj, pr, parentPr);
}
else if ((pr._arrayTypeEnum == InternalArrayTypeE.Jagged) || (pr._arrayTypeEnum == InternalArrayTypeE.Single))
{
+ Debug.Assert(pr._lengthA != null);
// Multidimensional jagged array or single array
bool couldBeValueType = true;
if ((pr._lowerBoundA == null) || (pr._lowerBoundA[0] == 0))
{
if (!pr._isLowerBound && (Converter.IsWriteAsByteArray(pr._arrayElementTypeCode)))
{
+ Debug.Assert(pr._newObj != null);
pr._primitiveArray = new PrimitiveArray(pr._arrayElementTypeCode, (Array)pr._newObj);
}
else if (couldBeValueType && pr._arrayElementType != null)
{
if (!pr._arrayElementType.IsValueType && !pr._isLowerBound)
{
- pr._objectA = (object[])pr._newObj;
+ pr._objectA = (object[]?)pr._newObj;
}
}
}
}
}
+ Debug.Assert(pr._lengthA != null);
if (pr._arrayElementType != null)
{
+ Debug.Assert(pr._lowerBoundA != null);
pr._newObj = !pr._isLowerBound ?
Array.CreateInstance(pr._arrayElementType, pr._lengthA) :
Array.CreateInstance(pr._arrayElementType, pr._lengthA, pr._lowerBoundA);
// Builds a map for each item in an incoming rectangle array. The map specifies where the item is placed in the output Array Object
private void NextRectangleMap(ParseRecord pr)
{
+ Debug.Assert(pr._rectangularMap != null && pr._lengthA != null && pr._indexMap != null);
// For each invocation, calculate the next rectangular array position
// example
// indexMap 0 [0,0,0]
// Array object item encountered in stream
private void ParseArrayMember(ParseRecord pr)
{
- ParseRecord objectPr = (ParseRecord)_stack.Peek();
+ Debug.Assert(_stack != null);
+ ParseRecord? objectPr = (ParseRecord?)_stack.Peek();
+ Debug.Assert(objectPr != null && objectPr._indexMap != null && objectPr._lowerBoundA != null);
// Set up for inserting value into correct array position
if (objectPr._arrayTypeEnum == InternalArrayTypeE.Rectangular)
{
}
if (objectPr._isLowerBound)
{
+ Debug.Assert(objectPr._rectangularMap != null);
for (int i = 0; i < objectPr._rank; i++)
{
objectPr._indexMap[i] = objectPr._rectangularMap[i] + objectPr._lowerBoundA[i];
{
// Object Reference
+ Debug.Assert(_objectManager != null);
// See if object has already been instantiated
- object refObj = _objectManager.GetObject(pr._idRef);
+ object? refObj = _objectManager.GetObject(pr._idRef);
if (refObj == null)
{
// Object not instantiated
}
else
{
+ Debug.Assert(objectPr._newObj != null);
((Array)objectPr._newObj).SetValue(refObj, objectPr._indexMap); // Object has been instantiated
}
}
if (objectPr._arrayElementType != null)
{
+ Debug.Assert(objectPr._newObj != null);
if ((objectPr._arrayElementType.IsValueType) && (pr._arrayElementTypeCode == InternalPrimitiveTypeE.Invalid))
{
pr._isValueTypeFixup = true; //Valuefixup
}
else
{
+ Debug.Assert(objectPr._newObj != null);
((Array)objectPr._newObj).SetValue(pr._value, objectPr._indexMap);
}
}
throw new SerializationException(SR.Serialization_ArrayTypeObject);
}
- object var = null;
+ object? var = null;
if (ReferenceEquals(pr._dtType, Converter.s_typeofString))
{
}
else if (ReferenceEquals(pr._dtTypeCode, InternalPrimitiveTypeE.Invalid))
{
+ Debug.Assert(pr._dtType != null);
CheckSerializable(pr._dtType);
// Not nested and invalid, so it is an empty object
var = FormatterServices.GetUninitializedObject(pr._dtType);
}
else
{
+ Debug.Assert(objectPr._newObj != null);
((Array)objectPr._newObj).SetValue(var, objectPr._indexMap); // Primitive type
}
}
// Primitive type
if (objectPr._primitiveArray != null)
{
+ Debug.Assert(pr._value != null);
// Fast path for Soap primitive arrays. Binary was handled in the BinaryParser
objectPr._primitiveArray.SetValue(pr._value, objectPr._indexMap[0]);
}
else
{
- object var = pr._varValue != null ?
+ object? var = pr._varValue != null ?
pr._varValue :
Converter.FromString(pr._value, objectPr._arrayElementTypeCode);
if (objectPr._objectA != null)
}
else
{
+ Debug.Assert(objectPr._newObj != null);
((Array)objectPr._newObj).SetValue(var, objectPr._indexMap); // Primitive type
}
}
// Object member encountered in stream
private void ParseMember(ParseRecord pr)
{
- ParseRecord objectPr = (ParseRecord)_stack.Peek();
- string objName = objectPr?._name;
+ Debug.Assert(_stack != null);
+ ParseRecord? objectPr = (ParseRecord?)_stack.Peek();
switch (pr._memberTypeEnum)
{
break;
}
+ Debug.Assert(objectPr!= null && objectPr._objectInfo != null && pr._name != null);
//if ((pr.PRdtType == null) && !objectPr.PRobjectInfo.isSi)
if (pr._dtType == null && objectPr._objectInfo._isTyped)
{
}
else if (pr._memberValueEnum == InternalMemberValueE.Reference)
{
+ Debug.Assert(_objectManager != null);
// See if object has already been instantiated
- object refObj = _objectManager.GetObject(pr._idRef);
+ object? refObj = _objectManager.GetObject(pr._idRef);
if (refObj == null)
{
objectPr._objectInfo.AddValue(pr._name, null, ref objectPr._si, ref objectPr._memberData);
// The member field was an object put the value is Inline either bin.Base64 or invalid
if (pr._arrayTypeEnum == InternalArrayTypeE.Base64)
{
+ Debug.Assert(pr._value != null);
objectPr._objectInfo.AddValue(pr._name, Convert.FromBase64String(pr._value), ref objectPr._si, ref objectPr._memberData);
}
else if (ReferenceEquals(pr._dtType, Converter.s_typeofObject))
}
else
{
- object var = pr._varValue != null ?
+ object? var = pr._varValue != null ?
pr._varValue :
Converter.FromString(pr._value, pr._dtTypeCode);
objectPr._objectInfo.AddValue(pr._name, var, ref objectPr._si, ref objectPr._memberData);
}
break;
default:
- ParseError(pr, (ParseRecord)_stack.Peek());
+ Debug.Assert(_stack != null);
+ ParseError(pr, (ParseRecord)_stack.Peek()!);
break;
}
}
}
}
- private void RegisterObject(object obj, ParseRecord pr, ParseRecord objectPr)
+ private void RegisterObject(object obj, ParseRecord pr, ParseRecord? objectPr)
{
RegisterObject(obj, pr, objectPr, false);
}
- private void RegisterObject(object obj, ParseRecord pr, ParseRecord objectPr, bool bIsString)
+ private void RegisterObject(object? obj, ParseRecord pr, ParseRecord? objectPr, bool bIsString)
{
if (!pr._isRegistered)
{
pr._isRegistered = true;
- SerializationInfo si = null;
+ SerializationInfo? si = null;
long parentId = 0;
- MemberInfo memberInfo = null;
- int[] indexMap = null;
+ MemberInfo? memberInfo = null;
+ int[]? indexMap = null;
if (objectPr != null)
{
// SerializationInfo is always needed for ISerialization
si = pr._si;
+ Debug.Assert(_objectManager != null);
if (bIsString)
{
- _objectManager.RegisterString((string)obj, pr._objectId, si, parentId, memberInfo);
+ _objectManager.RegisterString((string?)obj, pr._objectId, si, parentId, memberInfo);
}
else
{
+ Debug.Assert(obj != null);
_objectManager.RegisterObject(obj, pr._objectId, si, parentId, memberInfo, indexMap);
}
}
return -1 * objectId;
}
- internal Type Bind(string assemblyString, string typeString)
+ internal Type? Bind(string assemblyString, string typeString)
{
- Type type = null;
+ Type? type = null;
if (_binder != null)
{
type = _binder.BindToType(assemblyString, typeString);
internal sealed class TypeNAssembly
{
- public Type Type;
- public string AssemblyName;
+ public Type? Type;
+ public string? AssemblyName;
}
- internal Type FastBindToType(string assemblyName, string typeName)
+ internal Type? FastBindToType(string? assemblyName, string typeName)
{
- Type type = null;
+ Type? type = null;
- TypeNAssembly entry = (TypeNAssembly)_typeCache.GetCachedValue(typeName);
+ TypeNAssembly? entry = (TypeNAssembly?)_typeCache.GetCachedValue(typeName);
if (entry == null || entry.AssemblyName != assemblyName)
{
return null;
}
- Assembly assm = null;
- AssemblyName assmName = null;
+ Assembly? assm = null;
+ AssemblyName? assmName = null;
try
{
return entry.Type;
}
- private static Assembly ResolveSimpleAssemblyName(AssemblyName assemblyName)
+ private static Assembly? ResolveSimpleAssemblyName(AssemblyName assemblyName)
{
try
{
{
try
{
- return Assembly.Load(assemblyName.Name);
+ return Assembly.Load(assemblyName.Name!);
}
catch { }
}
return null;
}
- private static void GetSimplyNamedTypeFromAssembly(Assembly assm, string typeName, ref Type type)
+ private static void GetSimplyNamedTypeFromAssembly(Assembly assm, string typeName, ref Type? type)
{
// Catching any exceptions that could be thrown from a failure on assembly load
// This is necessary, for example, if there are generic parameters that are qualified with a version of the assembly that predates the one available
}
}
- private string _previousAssemblyString;
- private string _previousName;
- private Type _previousType;
+ private string? _previousAssemblyString;
+ private string? _previousName;
+ private Type? _previousType;
- internal Type GetType(BinaryAssemblyInfo assemblyInfo, string name)
+ internal Type? GetType(BinaryAssemblyInfo assemblyInfo, string name)
{
- Type objectType = null;
+ Type? objectType;
if (((_previousName != null) && (_previousName.Length == name.Length) && (_previousName.Equals(name))) &&
((_previousAssemblyString != null) && (_previousAssemblyString.Length == assemblyInfo._assemblyString.Length) && (_previousAssemblyString.Equals(assemblyInfo._assemblyString))))
_topLevelAssembly = topLevelAssembly;
}
- public Type ResolveType(Assembly assembly, string simpleTypeName, bool ignoreCase)
+ public Type? ResolveType(Assembly? assembly, string simpleTypeName, bool ignoreCase)
{
if (assembly == null)
{
internal sealed class BinaryObjectString : IStreamable
{
internal int _objectId;
- internal string _value;
+ internal string? _value;
internal BinaryObjectString() { }
- internal void Set(int objectId, string value)
+ internal void Set(int objectId, string? value)
{
_objectId = objectId;
_value = value;
{
output.WriteByte((byte)BinaryHeaderEnum.ObjectString);
output.WriteInt32(_objectId);
- output.WriteString(_value);
+ output.WriteString(_value!);
}
public void Read(BinaryParser input)
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
+
namespace System.Runtime.Serialization.Formatters.Binary
{
internal sealed class BinaryObjectWithMap : IStreamable
{
internal BinaryHeaderEnum _binaryHeaderEnum;
internal int _objectId;
- internal string _name;
+ internal string? _name;
internal int _numMembers;
- internal string[] _memberNames;
+ internal string[]? _memberNames;
internal int _assemId;
internal BinaryObjectWithMap() { }
public void Write(BinaryFormatterWriter output)
{
+ Debug.Assert(_name != null && _memberNames != null);
output.WriteByte((byte)_binaryHeaderEnum);
output.WriteInt32(_objectId);
output.WriteString(_name);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
+
namespace System.Runtime.Serialization.Formatters.Binary
{
internal sealed class BinaryObjectWithMapTyped : IStreamable
{
internal BinaryHeaderEnum _binaryHeaderEnum;
internal int _objectId;
- internal string _name;
+ internal string? _name;
internal int _numMembers;
- internal string[] _memberNames;
- internal BinaryTypeEnum[] _binaryTypeEnumA;
- internal object[] _typeInformationA;
- internal int[] _memberAssemIds;
+ internal string[]? _memberNames;
+ internal BinaryTypeEnum[]? _binaryTypeEnumA;
+ internal object?[]? _typeInformationA;
+ internal int[]? _memberAssemIds;
internal int _assemId;
internal BinaryObjectWithMapTyped() { }
_binaryHeaderEnum = binaryHeaderEnum;
}
- internal void Set(int objectId, string name, int numMembers, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object[] typeInformationA, int[] memberAssemIds, int assemId)
+ internal void Set(int objectId, string name, int numMembers, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object?[] typeInformationA, int[] memberAssemIds, int assemId)
{
_objectId = objectId;
_assemId = assemId;
public void Write(BinaryFormatterWriter output)
{
+ Debug.Assert(_name != null && _memberNames != null && _binaryTypeEnumA != null && _typeInformationA != null && _memberAssemIds != null);
output.WriteByte((byte)_binaryHeaderEnum);
output.WriteInt32(_objectId);
output.WriteString(_name);
using System.Reflection;
using System.Collections.Generic;
+using System.Diagnostics;
namespace System.Runtime.Serialization.Formatters.Binary
{
internal sealed class ObjectWriter
{
- private Queue<object> _objectQueue;
- private ObjectIDGenerator _idGenerator;
+ private Queue<object>? _objectQueue;
+ private ObjectIDGenerator? _idGenerator;
private int _currentId;
- private readonly ISurrogateSelector _surrogates;
+ private readonly ISurrogateSelector? _surrogates;
private readonly StreamingContext _context;
- private BinaryFormatterWriter _serWriter;
+ private BinaryFormatterWriter? _serWriter;
private readonly SerializationObjectManager _objectManager;
private long _topId;
- private readonly string _topName = null;
+ private readonly string? _topName = null;
private readonly InternalFE _formatterEnums;
- private readonly SerializationBinder _binder;
+ private readonly SerializationBinder? _binder;
- private SerObjectInfoInit _serObjectInfoInit;
+ private SerObjectInfoInit? _serObjectInfoInit;
- private IFormatterConverter _formatterConverter;
+ private IFormatterConverter? _formatterConverter;
- internal object[] _crossAppDomainArray = null;
- internal List<object> _internalCrossAppDomainArray = null;
+ internal object[]? _crossAppDomainArray = null;
+ internal List<object>? _internalCrossAppDomainArray = null;
- private object _previousObj = null;
+ private object? _previousObj = null;
private long _previousId = 0;
- private Type _previousType = null;
+ private Type? _previousType = null;
private InternalPrimitiveTypeE _previousCode = InternalPrimitiveTypeE.Invalid;
- internal ObjectWriter(ISurrogateSelector selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder binder)
+ internal ObjectWriter(ISurrogateSelector? selector, StreamingContext context, InternalFE formatterEnums, SerializationBinder? binder)
{
_currentId = 1;
_surrogates = selector;
serWriter.WriteBegin();
long headerId = 0;
- object obj;
- long objectId;
+ object? obj;
bool isNew;
// allocations if methodCall or methodResponse and no graph
WriteSerializedStreamHeader(_topId, headerId);
_objectQueue.Enqueue(graph);
- while ((obj = GetNext(out objectId)) != null)
+ while ((obj = GetNext(out long objectId)) != null)
{
- WriteObjectInfo objectInfo = null;
+ WriteObjectInfo? objectInfo = null;
// GetNext will return either an object or a WriteObjectInfo.
// A WriteObjectInfo is returned if this object was member of another object
// Writes a given object to the stream.
private void Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)
{
- object obj = objectInfo._obj;
+ object? obj = objectInfo._obj;
if (obj == null)
{
throw new ArgumentNullException(nameof(objectInfo) + "." + nameof(objectInfo._obj));
}
- Type objType = objectInfo._objectType;
+ Type? objType = objectInfo._objectType;
long objectId = objectInfo._objectId;
if (ReferenceEquals(objType, Converter.s_typeofString))
{
+ Debug.Assert(_serWriter != null);
// Top level String
memberNameInfo._objectId = objectId;
_serWriter.WriteObjectString((int)objectId, obj.ToString());
}
else
{
- string[] memberNames;
- Type[] memberTypes;
- object[] memberData;
-
- objectInfo.GetMemberInfo(out memberNames, out memberTypes, out memberData);
+ objectInfo.GetMemberInfo(out string[]? memberNames, out Type[]? memberTypes, out object?[]? memberData);
// Only Binary needs to transmit types for ISerializable because the binary formatter transmits the types in URT format.
// Soap transmits all types as strings, so it is up to the ISerializable object to convert the string back to its URT type
typeNameInfo._isParentTypeOnObject = true;
}
+ Debug.Assert(memberNames != null && memberTypes != null && memberData != null);
var memberObjectInfos = new WriteObjectInfo[memberNames.Length];
// Get assembly information
{
Type type =
memberTypes[i] != null ? memberTypes[i] :
- memberData[i] != null ? GetType(memberData[i]) :
+ memberData[i] != null ? GetType(memberData[i]!) : // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644
Converter.s_typeofObject;
InternalPrimitiveTypeE code = ToCode(type);
if ((code == InternalPrimitiveTypeE.Invalid) &&
(!ReferenceEquals(type, Converter.s_typeofString)))
{
+ Debug.Assert(_serObjectInfoInit != null && _formatterConverter != null);
if (memberData[i] != null)
{
memberObjectInfos[i] = WriteObjectInfo.Serialize(
- memberData[i],
+ memberData[i]!, // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644
_surrogates,
_context,
_serObjectInfoInit,
// Writes a given object to the stream.
private void Write(WriteObjectInfo objectInfo,
- NameInfo memberNameInfo,
+ NameInfo? memberNameInfo,
NameInfo typeNameInfo,
string[] memberNames,
Type[] memberTypes,
- object[] memberData,
+ object?[] memberData,
WriteObjectInfo[] memberObjectInfos)
{
int numItems = memberNames.Length;
- NameInfo topNameInfo = null;
+ NameInfo? topNameInfo = null;
+ Debug.Assert(_serWriter != null);
if (memberNameInfo != null)
{
memberNameInfo._objectId = objectInfo._objectId;
}
}
+ Debug.Assert(memberNameInfo != null);
if (memberNameInfo._isParentTypeOnObject)
{
memberNameInfo._transmitTypeOnObject = true;
}
else if ((objectInfo._objectId == _topId) && (_topName != null))
{
- _serWriter.WriteObjectEnd(topNameInfo, typeNameInfo);
- PutNameInfo(topNameInfo);
+ _serWriter.WriteObjectEnd(topNameInfo!, typeNameInfo);
+ PutNameInfo(topNameInfo!);
}
else if (!ReferenceEquals(objectInfo._objectType, Converter.s_typeofString))
{
NameInfo typeNameInfo,
string memberName,
Type memberType,
- object memberData,
- WriteObjectInfo memberObjectInfo)
+ object? memberData,
+ WriteObjectInfo? memberObjectInfo)
{
NameInfo newMemberNameInfo = MemberToNameInfo(memberName); // newMemberNameInfo contains the member type
newMemberNameInfo._type = memberType;
// newTypeNameInfo contains the data type
- NameInfo newTypeNameInfo = null;
+ NameInfo newTypeNameInfo;
if (memberObjectInfo == null)
{
newTypeNameInfo = TypeToNameInfo(memberType);
// Writes the members of an object
private void WriteMembers(NameInfo memberNameInfo,
NameInfo memberTypeNameInfo,
- object memberData,
+ object? memberData,
WriteObjectInfo objectInfo,
NameInfo typeNameInfo,
- WriteObjectInfo memberObjectInfo)
+ WriteObjectInfo? memberObjectInfo)
{
- Type memberType = memberNameInfo._type;
+ Type? memberType = memberNameInfo._type;
bool assignUniqueIdToValueType = false;
// Types are transmitted for a member as follows:
// The member object of type is ISerializable and
// Binary - Types always transmitted.
- if (ReferenceEquals(memberType, Converter.s_typeofObject) || Nullable.GetUnderlyingType(memberType) != null)
+ if (ReferenceEquals(memberType, Converter.s_typeofObject) || Nullable.GetUnderlyingType(memberType!) != null)
{
memberTypeNameInfo._transmitTypeOnMember = true;
memberNameInfo._transmitTypeOnMember = true;
return;
}
- object outObj = memberData;
- Type outType = null;
+ object outObj = memberData!;
+ Type? outType = null;
// If member type does not equal data type, transmit type on object.
if (memberTypeNameInfo._primitiveTypeEnum == InternalPrimitiveTypeE.Invalid)
if (ReferenceEquals(memberType, Converter.s_typeofObject))
{
assignUniqueIdToValueType = true;
- memberType = GetType(memberData);
+ memberType = GetType(memberData!);
if (memberObjectInfo == null)
{
TypeToNameInfo(memberType, memberTypeNameInfo);
if (memberObjectInfo != null && memberObjectInfo._isArray)
{
- // Array
- long arrayId = 0;
- if (outType == null)
- {
- outType = GetType(outObj);
- }
-
- // outObj is an array. It can never be a value type..
- arrayId = Schedule(outObj, false, null, memberObjectInfo);
+ // outObj is an array. It can never be a value type.
+ long arrayId = Schedule(outObj, false, null, memberObjectInfo);
if (arrayId > 0)
{
// Array as object
}
else
{
+ Debug.Assert(_serWriter != null);
// Nested Array
_serWriter.WriteMemberNested(memberNameInfo);
return;
}
- if (!WriteKnownValueClass(memberNameInfo, memberTypeNameInfo, memberData))
+ if (!WriteKnownValueClass(memberNameInfo, memberTypeNameInfo, memberData!))
{
if (outType == null)
{
long memberObjectId = Schedule(outObj, assignUniqueIdToValueType, outType, memberObjectInfo);
if (memberObjectId < 0)
{
+ Debug.Assert(memberObjectInfo != null);
// Nested object
memberObjectInfo._objectId = memberObjectId;
NameInfo newTypeNameInfo = TypeToNameInfo(memberObjectInfo);
}
// Writes out an array
- private void WriteArray(WriteObjectInfo objectInfo, NameInfo memberNameInfo, WriteObjectInfo memberObjectInfo)
+ private void WriteArray(WriteObjectInfo objectInfo, NameInfo? memberNameInfo, WriteObjectInfo? memberObjectInfo)
{
bool isAllocatedMemberNameInfo = false;
if (memberNameInfo == null)
memberNameInfo._objectId = objectInfo._objectId;
// Get array type
- Array array = (Array)objectInfo._obj;
+ Array array = (Array)objectInfo._obj!;
//Type arrayType = array.GetType();
- Type arrayType = objectInfo._objectType;
+ Type arrayType = objectInfo._objectType!;
// Get type of array element
- Type arrayElemType = arrayType.GetElementType();
- WriteObjectInfo arrayElemObjectInfo = null;
+ Type arrayElemType = arrayType.GetElementType()!;
+ WriteObjectInfo? arrayElemObjectInfo = null;
if (!arrayElemType.IsPrimitive)
{
+ Debug.Assert(_serObjectInfoInit != null && _formatterConverter != null);
arrayElemObjectInfo = WriteObjectInfo.Serialize(arrayElemType, _surrogates, _context, _serObjectInfoInit, _formatterConverter, _binder);
arrayElemObjectInfo._assemId = GetAssemblyId(arrayElemObjectInfo);
}
NameInfo arrayElemTypeNameInfo = arrayElemObjectInfo == null ?
TypeToNameInfo(arrayElemType) :
TypeToNameInfo(arrayElemObjectInfo);
- arrayElemTypeNameInfo._isArray = arrayElemTypeNameInfo._type.IsArray;
+ arrayElemTypeNameInfo._isArray = arrayElemTypeNameInfo._type!.IsArray;
NameInfo arrayNameInfo = memberNameInfo;
arrayNameInfo._objectId = objectId;
}
arrayElemTypeNameInfo._arrayEnum = arrayEnum;
+ Debug.Assert(_serWriter != null);
// Byte array
if ((ReferenceEquals(arrayElemType, Converter.s_typeofByte)) && (rank == 1) && (lowerBoundA[0] == 0))
{
if (!(Converter.IsWriteAsByteArray(arrayElemTypeNameInfo._primitiveTypeEnum) && (lowerBoundA[0] == 0)))
{
- object[] objectA = null;
+ object[]? objectA = null;
if (!arrayElemType.IsValueType)
{
// Non-primitive type array
}
// Writes out an array element
- private void WriteArrayMember(WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, object data)
+ private void WriteArrayMember(WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, object? data)
{
arrayElemTypeNameInfo._isArrayItem = true;
return;
}
- NameInfo actualTypeInfo = null;
- Type dataType = null;
+ NameInfo? actualTypeInfo = null;
+ Type? dataType = null;
bool isObjectOnMember = false;
if (arrayElemTypeNameInfo._transmitTypeOnMember)
if (!isObjectOnMember && !arrayElemTypeNameInfo.IsSealed)
{
- dataType = GetType(data);
+ dataType = GetType(data!);
if (!ReferenceEquals(arrayElemTypeNameInfo._type, dataType))
{
isObjectOnMember = true;
// Object array, need type of member
if (dataType == null)
{
- dataType = GetType(data);
+ dataType = GetType(data!);
}
actualTypeInfo = TypeToNameInfo(dataType);
actualTypeInfo._transmitTypeOnMember = true;
actualTypeInfo._isArrayItem = true;
}
- if (!WriteKnownValueClass(arrayElemTypeNameInfo, actualTypeInfo, data))
+ if (!WriteKnownValueClass(arrayElemTypeNameInfo, actualTypeInfo, data!))
{
- object obj = data;
+ object obj = data!;
bool assignUniqueIdForValueTypes = false;
if (ReferenceEquals(arrayElemTypeNameInfo._type, Converter.s_typeofObject))
{
actualTypeInfo._objectId = arrayId;
if (arrayId < 1)
{
+ Debug.Assert(_serObjectInfoInit != null && _formatterConverter != null);
WriteObjectInfo newObjectInfo = WriteObjectInfo.Serialize(obj, _surrogates, _context, _serObjectInfoInit, _formatterConverter, this, _binder);
newObjectInfo._objectId = arrayId;
- newObjectInfo._assemId = !ReferenceEquals(arrayElemTypeNameInfo._type, Converter.s_typeofObject) && Nullable.GetUnderlyingType(arrayElemTypeNameInfo._type) == null ?
+ newObjectInfo._assemId = !ReferenceEquals(arrayElemTypeNameInfo._type, Converter.s_typeofObject) && Nullable.GetUnderlyingType(arrayElemTypeNameInfo._type!) == null ?
actualTypeInfo._assemId :
GetAssemblyId(newObjectInfo);
NameInfo typeNameInfo = TypeToNameInfo(newObjectInfo);
}
else
{
+ Debug.Assert(_serWriter != null);
_serWriter.WriteItemObjectRef(arrayElemTypeNameInfo, (int)arrayId);
}
}
}
// Iterates over a Rectangle array, for each element of the array invokes WriteArrayMember
- private void WriteRectangle(WriteObjectInfo objectInfo, int rank, int[] maxA, Array array, NameInfo arrayElemNameTypeInfo, int[] lowerBoundA)
+ private void WriteRectangle(WriteObjectInfo objectInfo, int rank, int[] maxA, Array array, NameInfo arrayElemNameTypeInfo, int[]? lowerBoundA)
{
int[] currentA = new int[rank];
- int[] indexMap = null;
+ int[]? indexMap = null;
bool isLowerBound = false;
if (lowerBoundA != null)
{
{
for (int i = 0; i < rank; i++)
{
- indexMap[i] = currentA[i] + lowerBoundA[i];
+ indexMap![i] = currentA[i] + lowerBoundA![i];
}
- WriteArrayMember(objectInfo, arrayElemNameTypeInfo, array.GetValue(indexMap));
+ WriteArrayMember(objectInfo, arrayElemNameTypeInfo, array.GetValue(indexMap!));
}
else
{
// are returned in a FIFO order based on how they were passed
// to Schedule. The id of the object is put into the objID parameter
// and the Object itself is returned from the function.
- private object GetNext(out long objID)
+ private object? GetNext(out long objID)
{
bool isNew;
//The Queue is empty here. We'll throw if we try to dequeue the empty queue.
- if (_objectQueue.Count == 0)
+ if (_objectQueue!.Count == 0)
{
objID = 0;
return null;
object obj = _objectQueue.Dequeue();
// A WriteObjectInfo is queued if this object was a member of another object
- object realObj = obj is WriteObjectInfo ? ((WriteObjectInfo)obj)._obj : obj;
- objID = _idGenerator.HasId(realObj, out isNew);
+ object? realObj = obj is WriteObjectInfo ? ((WriteObjectInfo)obj)._obj : obj;
+ Debug.Assert(realObj != null);
+ objID = _idGenerator!.HasId(realObj, out isNew);
if (isNew)
{
throw new SerializationException(SR.Format(SR.Serialization_ObjNoID, realObj));
// If the type is a value type, we dont attempt to generate a unique id, unless its a boxed entity
// (in which case, there might be 2 references to the same boxed obj. in a graph.)
// "assignUniqueIdToValueType" is true, if the field type holding reference to "obj" is Object.
- private long InternalGetId(object obj, bool assignUniqueIdToValueType, Type type, out bool isNew)
+ private long InternalGetId(object obj, bool assignUniqueIdToValueType, Type? type, out bool isNew)
{
if (obj == _previousObj)
{
isNew = false;
return _previousId;
}
+ Debug.Assert(_idGenerator != null);
_idGenerator._currentCount = _currentId;
if (type != null && type.IsValueType)
{
// We get an ID for obj and put it on the queue for later serialization
// if this is a new object id.
- private long Schedule(object obj, bool assignUniqueIdToValueType, Type type) =>
+ private long Schedule(object obj, bool assignUniqueIdToValueType, Type? type) =>
Schedule(obj, assignUniqueIdToValueType, type, null);
- private long Schedule(object obj, bool assignUniqueIdToValueType, Type type, WriteObjectInfo objectInfo)
+ private long Schedule(object obj, bool assignUniqueIdToValueType, Type? type, WriteObjectInfo? objectInfo)
{
long id = 0;
if (obj != null)
id = InternalGetId(obj, assignUniqueIdToValueType, type, out isNew);
if (isNew && id > 0)
{
+ Debug.Assert(_objectQueue != null);
_objectQueue.Enqueue(objectInfo ?? obj);
}
}
}
else
{
+ Debug.Assert(_serWriter != null);
if (typeNameInfo._isArray) // null if an array
{
_serWriter.WriteItem(memberNameInfo, typeNameInfo, data);
// Writes an object reference to the stream.
private void WriteObjectRef(NameInfo nameInfo, long objectId) =>
- _serWriter.WriteMemberObjectRef(nameInfo, (int)objectId);
+ _serWriter!.WriteMemberObjectRef(nameInfo, (int)objectId);
// Writes a string into the XML stream
private void WriteString(NameInfo memberNameInfo, NameInfo typeNameInfo, object stringObject)
if ((isFirstTime) || (stringId < 0))
{
+ Debug.Assert(_serWriter != null);
_serWriter.WriteMemberString(memberNameInfo, typeNameInfo, (string)stringObject);
}
else
}
// Writes a null member into the stream
- private bool CheckForNull(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo, object data)
+ private bool CheckForNull(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo, object? data)
{
bool isNull = data == null;
objectInfo._isSi ||
(CheckTypeFormat(_formatterEnums._typeFormat, FormatterTypeStyle.TypesAlways))))
{
+ Debug.Assert(_serWriter != null);
if (typeNameInfo._isArrayItem)
{
if (typeNameInfo._arrayEnum == InternalArrayTypeE.Single)
// Writes the SerializedStreamHeader
private void WriteSerializedStreamHeader(long topId, long headerId) =>
- _serWriter.WriteSerializationHeader((int)topId, (int)headerId, 1, 0);
+ _serWriter!.WriteSerializationHeader((int)topId, (int)headerId, 1, 0);
// Transforms a type to the serialized string form. URT Primitive types are converted to XMLData Types
- private NameInfo TypeToNameInfo(Type type, WriteObjectInfo objectInfo, InternalPrimitiveTypeE code, NameInfo nameInfo)
+ private NameInfo TypeToNameInfo(Type? type, WriteObjectInfo? objectInfo, InternalPrimitiveTypeE code, NameInfo? nameInfo)
{
if (nameInfo == null)
{
return memberNameInfo;
}
- internal InternalPrimitiveTypeE ToCode(Type type)
+ internal InternalPrimitiveTypeE ToCode(Type? type)
{
if (ReferenceEquals(_previousType, type))
{
}
}
- private Dictionary<string, long> _assemblyToIdTable = null;
+ private Dictionary<string, long>? _assemblyToIdTable = null;
private long GetAssemblyId(WriteObjectInfo objectInfo)
{
//use objectInfo to get assembly string with new criteria
_assemblyToIdTable[assemblyString] = assemId;
}
+ Debug.Assert(_serWriter != null);
_serWriter.WriteAssembly(objectInfo._objectType, serializedAssemblyString, (int)assemId, isNew);
}
return assemId;
private NameInfo GetNameInfo()
{
- NameInfo nameInfo = null;
+ NameInfo nameInfo;
if (!_niPool.IsEmpty())
{
- nameInfo = (NameInfo)_niPool.Pop();
+ nameInfo = (NameInfo)_niPool.Pop()!;
nameInfo.Init();
}
else
internal Stream _input;
internal long _topId;
internal long _headerId;
- internal SizedArray _objectMapIdTable;
- internal SizedArray _assemIdToAssemblyTable; // Used to hold assembly information
+ internal SizedArray? _objectMapIdTable;
+ internal SizedArray? _assemIdToAssemblyTable; // Used to hold assembly information
internal SerStack _stack = new SerStack("ObjectProgressStack");
internal BinaryTypeEnum _expectedType = BinaryTypeEnum.ObjectUrt;
- internal object _expectedTypeInformation;
- internal ParseRecord _prs;
+ internal object? _expectedTypeInformation;
+ internal ParseRecord? _prs;
- private BinaryAssemblyInfo _systemAssemblyInfo;
+ private BinaryAssemblyInfo? _systemAssemblyInfo;
private readonly BinaryReader _dataReader;
- private SerStack _opPool;
+ private SerStack? _opPool;
- private BinaryObject _binaryObject;
- private BinaryObjectWithMap _bowm;
- private BinaryObjectWithMapTyped _bowmt;
+ private BinaryObject? _binaryObject;
+ private BinaryObjectWithMap? _bowm;
+ private BinaryObjectWithMapTyped? _bowmt;
- internal BinaryObjectString _objectString;
- internal BinaryCrossAppDomainString _crossAppDomainString;
- internal MemberPrimitiveTyped _memberPrimitiveTyped;
- private byte[] _byteBuffer;
- internal MemberPrimitiveUnTyped memberPrimitiveUnTyped;
- internal MemberReference _memberReference;
- internal ObjectNull _objectNull;
- internal static volatile MessageEnd _messageEnd;
+ internal BinaryObjectString? _objectString;
+ internal BinaryCrossAppDomainString? _crossAppDomainString;
+ internal MemberPrimitiveTyped? _memberPrimitiveTyped;
+ private byte[]? _byteBuffer;
+ internal MemberPrimitiveUnTyped? memberPrimitiveUnTyped;
+ internal MemberReference? _memberReference;
+ internal ObjectNull? _objectNull;
+ internal static volatile MessageEnd? _messageEnd;
internal BinaryParser(Stream stream, ObjectReader objectReader)
{
// If this is an object, and the end of object has been reached, then parse object end.
while (!isData)
{
- ObjectProgress op = (ObjectProgress)_stack.Peek();
+ ObjectProgress? op = (ObjectProgress?)_stack.Peek();
if (op == null)
{
// No more object on stack, then the next record is a top level object
record.Read(this);
}
- AssemIdToAssemblyTable[record._assemId] = new BinaryAssemblyInfo(record._assemblyString);
+ AssemIdToAssemblyTable[record._assemId] = new BinaryAssemblyInfo(record._assemblyString!);
}
private void ReadObject()
}
_binaryObject.Read(this);
- ObjectMap objectMap = (ObjectMap)ObjectMapIdTable[_binaryObject._mapId];
+ ObjectMap? objectMap = (ObjectMap?)ObjectMapIdTable[_binaryObject._mapId];
if (objectMap == null)
{
throw new SerializationException(SR.Format(SR.Serialization_Map, _binaryObject._mapId));
op._memberTypes = objectMap._memberTypes;
op._typeInformationA = objectMap._typeInformationA;
op._memberLength = op._binaryTypeEnumA.Length;
- ObjectProgress objectOp = (ObjectProgress)_stack.PeekPeek();
+ ObjectProgress? objectOp = (ObjectProgress?)_stack.PeekPeek();
if ((objectOp == null) || (objectOp._isInitial))
{
// Non-Nested Object
BinaryCrossAppDomainMap record = new BinaryCrossAppDomainMap();
record.Read(this);
object mapObject = _objectReader.CrossAppDomainArray(record._crossAppDomainArrayIndex);
- BinaryObjectWithMap binaryObjectWithMap = mapObject as BinaryObjectWithMap;
- if (binaryObjectWithMap != null)
+ if (mapObject is BinaryObjectWithMap binaryObjectWithMap)
{
ReadObjectWithMap(binaryObjectWithMap);
}
else
{
- BinaryObjectWithMapTyped binaryObjectWithMapTyped = mapObject as BinaryObjectWithMapTyped;
- if (binaryObjectWithMapTyped != null)
+ if (mapObject is BinaryObjectWithMapTyped binaryObjectWithMapTyped)
{
ReadObjectWithMapTyped(binaryObjectWithMapTyped);
}
private void ReadObjectWithMap(BinaryObjectWithMap record)
{
- BinaryAssemblyInfo assemblyInfo = null;
+ BinaryAssemblyInfo? assemblyInfo = null;
ObjectProgress op = GetOp();
ParseRecord pr = op._pr;
_stack.Push(op);
throw new SerializationException(SR.Format(SR.Serialization_Assembly, record._name));
}
- assemblyInfo = ((BinaryAssemblyInfo)AssemIdToAssemblyTable[record._assemId]);
+ assemblyInfo = ((BinaryAssemblyInfo?)AssemIdToAssemblyTable[record._assemId]);
if (assemblyInfo == null)
{
assemblyInfo = SystemAssemblyInfo; //Urt assembly
}
- Type objectType = _objectReader.GetType(assemblyInfo, record._name);
+ Debug.Assert(record._name != null && record._memberNames != null);
+ Type? objectType = _objectReader.GetType(assemblyInfo!, record._name);
- ObjectMap objectMap = ObjectMap.Create(record._name, objectType, record._memberNames, _objectReader, record._objectId, assemblyInfo);
+ Debug.Assert(objectType != null);
+ ObjectMap objectMap = ObjectMap.Create(record._name, objectType, record._memberNames, _objectReader, record._objectId, assemblyInfo!);
ObjectMapIdTable[record._objectId] = objectMap;
op._objectTypeEnum = InternalObjectTypeE.Object;
op._memberNames = objectMap._memberNames;
op._memberTypes = objectMap._memberTypes;
- ObjectProgress objectOp = (ObjectProgress)_stack.PeekPeek();
+ ObjectProgress? objectOp = (ObjectProgress?)_stack.PeekPeek();
if ((objectOp == null) || (objectOp._isInitial))
{
private void ReadObjectWithMapTyped(BinaryObjectWithMapTyped record)
{
- BinaryAssemblyInfo assemblyInfo = null;
+ BinaryAssemblyInfo? assemblyInfo = null;
ObjectProgress op = GetOp();
ParseRecord pr = op._pr;
_stack.Push(op);
throw new SerializationException(SR.Format(SR.Serialization_AssemblyId, record._name));
}
- assemblyInfo = (BinaryAssemblyInfo)AssemIdToAssemblyTable[record._assemId];
+ assemblyInfo = (BinaryAssemblyInfo?)AssemIdToAssemblyTable[record._assemId];
if (assemblyInfo == null)
{
throw new SerializationException(SR.Format(SR.Serialization_AssemblyId, record._assemId + " " + record._name));
assemblyInfo = SystemAssemblyInfo; // Urt assembly
}
- ObjectMap objectMap = ObjectMap.Create(record._name, record._memberNames, record._binaryTypeEnumA, record._typeInformationA, record._memberAssemIds, _objectReader, record._objectId, assemblyInfo, AssemIdToAssemblyTable);
+ Debug.Assert(record._name != null && record._memberNames != null && record._binaryTypeEnumA != null && record._typeInformationA != null && record._memberAssemIds != null);
+ ObjectMap objectMap = ObjectMap.Create(record._name, record._memberNames, record._binaryTypeEnumA, record._typeInformationA, record._memberAssemIds, _objectReader, record._objectId, assemblyInfo!, AssemIdToAssemblyTable);
ObjectMapIdTable[record._objectId] = objectMap;
op._objectTypeEnum = InternalObjectTypeE.Object;
op._binaryTypeEnumA = objectMap._binaryTypeEnumA;
op._memberNames = objectMap._memberNames;
op._memberTypes = objectMap._memberTypes;
- ObjectProgress objectOp = (ObjectProgress)_stack.PeekPeek();
+ ObjectProgress? objectOp = (ObjectProgress?)_stack.PeekPeek();
if ((objectOp == null) || (objectOp._isInitial))
{
PRs._objectTypeEnum = InternalObjectTypeE.Object;
- ObjectProgress objectOp = (ObjectProgress)_stack.Peek();
+ ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek();
PRs._value = _objectString._value;
PRs._keyDt = "System.String";
_memberPrimitiveTyped.Read(this);
PRs._objectTypeEnum = InternalObjectTypeE.Object; //Get rid of
- ObjectProgress objectOp = (ObjectProgress)_stack.Peek();
+ ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek();
PRs.Init();
PRs._varValue = _memberPrimitiveTyped._value;
private void ReadArray(BinaryHeaderEnum binaryHeaderEnum)
{
- BinaryAssemblyInfo assemblyInfo = null;
+ BinaryAssemblyInfo? assemblyInfo = null;
BinaryArray record = new BinaryArray(binaryHeaderEnum);
record.Read(this);
{
throw new SerializationException(SR.Format(SR.Serialization_AssemblyId, record._typeInformation));
}
- assemblyInfo = (BinaryAssemblyInfo)AssemIdToAssemblyTable[record._assemId];
+ assemblyInfo = (BinaryAssemblyInfo?)AssemIdToAssemblyTable[record._assemId];
}
else
{
op._binaryTypeEnum = record._binaryTypeEnum;
op._typeInformation = record._typeInformation;
- ObjectProgress objectOp = (ObjectProgress)_stack.PeekPeek();
+ ObjectProgress? objectOp = (ObjectProgress?)_stack.PeekPeek();
if ((objectOp == null) || (record._objectId > 0))
{
// Non-Nested Object
pr._lowerBoundA = record._lowerBoundA;
bool isPrimitiveArray = false;
+ Debug.Assert(record._lengthA != null);
switch (record._binaryArrayTypeEnum)
{
case BinaryArrayTypeEnum.Single:
case BinaryArrayTypeEnum.SingleOffset:
op._numItems = record._lengthA[0];
pr._arrayTypeEnum = InternalArrayTypeE.Single;
+ Debug.Assert(record._lowerBoundA != null);
if (Converter.IsWriteAsByteArray(pr._arrayElementTypeCode) &&
(record._lowerBoundA[0] == 0))
{
private void ReadArrayAsBytes(ParseRecord pr)
{
+ Debug.Assert(pr._lengthA != null);
if (pr._arrayElementTypeCode == InternalPrimitiveTypeE.Byte)
{
pr._newObj = ReadBytes(pr._lengthA[0]);
private void ReadMemberPrimitiveUnTyped()
{
- ObjectProgress objectOp = (ObjectProgress)_stack.Peek();
+ ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek();
if (memberPrimitiveUnTyped == null)
{
memberPrimitiveUnTyped = new MemberPrimitiveUnTyped();
}
- memberPrimitiveUnTyped.Set((InternalPrimitiveTypeE)_expectedTypeInformation);
+ memberPrimitiveUnTyped.Set((InternalPrimitiveTypeE)_expectedTypeInformation!);
memberPrimitiveUnTyped.Read(this);
PRs.Init();
PRs._varValue = memberPrimitiveUnTyped._value;
- PRs._dtTypeCode = (InternalPrimitiveTypeE)_expectedTypeInformation;
+ PRs._dtTypeCode = (InternalPrimitiveTypeE)_expectedTypeInformation!;
PRs._dtType = Converter.ToType(PRs._dtTypeCode);
PRs._parseTypeEnum = InternalParseTypeE.Member;
PRs._memberValueEnum = InternalMemberValueE.InlineValue;
+ Debug.Assert(objectOp != null);
if (objectOp._objectTypeEnum == InternalObjectTypeE.Object)
{
PRs._memberTypeEnum = InternalMemberTypeE.Field;
}
_memberReference.Read(this);
- ObjectProgress objectOp = (ObjectProgress)_stack.Peek();
+ ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek();
PRs.Init();
PRs._idRef = _objectReader.GetId(_memberReference._idRef);
PRs._parseTypeEnum = InternalParseTypeE.Member;
PRs._memberValueEnum = InternalMemberValueE.Reference;
+ Debug.Assert(objectOp != null);
if (objectOp._objectTypeEnum == InternalObjectTypeE.Object)
{
PRs._memberTypeEnum = InternalMemberTypeE.Field;
}
_objectNull.Read(this, binaryHeaderEnum);
- ObjectProgress objectOp = (ObjectProgress)_stack.Peek();
+ ObjectProgress? objectOp = (ObjectProgress?)_stack.Peek();
PRs.Init();
PRs._parseTypeEnum = InternalParseTypeE.Member;
PRs._memberValueEnum = InternalMemberValueE.Null;
+ Debug.Assert(objectOp != null);
if (objectOp._objectTypeEnum == InternalObjectTypeE.Object)
{
PRs._memberTypeEnum = InternalMemberTypeE.Field;
private ObjectProgress GetOp()
{
- ObjectProgress op = null;
+ ObjectProgress op;
if (_opPool != null && !_opPool.IsEmpty())
{
- op = (ObjectProgress)_opPool.Pop();
+ op = (ObjectProgress)_opPool.Pop()!;
op.Init();
}
else
internal static class BinaryTypeConverter
{
// From the type create the BinaryTypeEnum and typeInformation which describes the type on the wire
- internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo objectInfo, string typeName, ObjectWriter objectWriter, out object typeInformation, out int assemId)
+ internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo? objectInfo, string? typeName, ObjectWriter objectWriter, out object? typeInformation, out int assemId)
{
BinaryTypeEnum binaryTypeEnum;
switch (primitiveTypeEnum)
{
case InternalPrimitiveTypeE.Invalid:
- string assembly = null;
+ string? assembly = null;
if (objectInfo == null)
{
assembly = type.Assembly.FullName;
typeInformation = objectInfo.GetTypeFullName();
}
+ Debug.Assert(assembly != null);
if (assembly.Equals(Converter.s_urtAssemblyString) || assembly.Equals(Converter.s_urtAlternativeAssemblyString))
{
binaryTypeEnum = BinaryTypeEnum.ObjectUrt;
}
// Used for non Si types when Parsing
- internal static BinaryTypeEnum GetParserBinaryTypeInfo(Type type, out object typeInformation)
+ internal static BinaryTypeEnum GetParserBinaryTypeInfo(Type type, out object? typeInformation)
{
BinaryTypeEnum binaryTypeEnum;
typeInformation = null;
}
// Writes the type information on the wire
- internal static void WriteTypeInfo(BinaryTypeEnum binaryTypeEnum, object typeInformation, int assemId, BinaryFormatterWriter output)
+ internal static void WriteTypeInfo(BinaryTypeEnum binaryTypeEnum, object? typeInformation, int assemId, BinaryFormatterWriter output)
{
switch (binaryTypeEnum)
{
break;
case BinaryTypeEnum.ObjectUrt:
Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null");
- output.WriteString(typeInformation.ToString());
+ output.WriteString(typeInformation.ToString()!);
break;
case BinaryTypeEnum.ObjectUser:
Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null");
- output.WriteString(typeInformation.ToString());
+ output.WriteString(typeInformation.ToString()!);
output.WriteInt32(assemId);
break;
default:
// Reads the type information from the wire
internal static object ReadTypeInfo(BinaryTypeEnum binaryTypeEnum, BinaryParser input, out int assemId)
{
- object var = null;
+ object var = null!;
int readAssemId = 0;
switch (binaryTypeEnum)
// Given the wire type information, returns the actual type and additional information
internal static void TypeFromInfo(BinaryTypeEnum binaryTypeEnum,
- object typeInformation,
+ object? typeInformation,
ObjectReader objectReader,
- BinaryAssemblyInfo assemblyInfo,
+ BinaryAssemblyInfo? assemblyInfo,
out InternalPrimitiveTypeE primitiveTypeEnum,
- out string typeString,
- out Type type,
+ out string? typeString,
+ out Type? type,
out bool isVariant)
{
isVariant = false;
switch (binaryTypeEnum)
{
case BinaryTypeEnum.Primitive:
- primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation;
+ primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation!;
typeString = Converter.ToComType(primitiveTypeEnum);
type = Converter.ToType(primitiveTypeEnum);
break;
type = Converter.s_typeofStringArray;
break;
case BinaryTypeEnum.PrimitiveArray:
- primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation;
+ primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation!;
type = Converter.ToArrayType(primitiveTypeEnum);
break;
case BinaryTypeEnum.ObjectUser:
if (typeInformation != null)
{
typeString = typeInformation.ToString();
- type = objectReader.GetType(assemblyInfo, typeString);
+ type = objectReader.GetType(assemblyInfo!, typeString!);
if (ReferenceEquals(type, Converter.s_typeofObject))
{
isVariant = true;
// See the LICENSE file in the project root for more information.
using System.Collections.Concurrent;
+using System.Diagnostics;
using System.Globalization;
using System.Reflection;
internal InternalObjectPositionE _objectPositionEnum = InternalObjectPositionE.Empty;
// Object
- internal string _name;
+ internal string? _name;
// Value
- internal string _value;
- internal object _varValue;
+ internal string? _value;
+ internal object? _varValue;
// dt attribute
- internal string _keyDt;
- internal Type _dtType;
+ internal string? _keyDt;
+ internal Type? _dtType;
internal InternalPrimitiveTypeE _dtTypeCode;
// Object ID
// Array
// Array Element Type
- internal string _arrayElementTypeString;
- internal Type _arrayElementType;
+ internal string? _arrayElementTypeString;
+ internal Type? _arrayElementType;
internal bool _isArrayVariant = false;
internal InternalPrimitiveTypeE _arrayElementTypeCode;
// Parsed array information
internal int _rank;
- internal int[] _lengthA;
- internal int[] _lowerBoundA;
+ internal int[]? _lengthA;
+ internal int[]? _lowerBoundA;
// Array map for placing array elements in array
- internal int[] _indexMap;
+ internal int[]? _indexMap;
internal int _memberIndex;
internal int _linearlength;
- internal int[] _rectangularMap;
+ internal int[]? _rectangularMap;
internal bool _isLowerBound;
// MemberInfo accumulated during parsing of members
- internal ReadObjectInfo _objectInfo;
+ internal ReadObjectInfo? _objectInfo;
// ValueType Fixup needed
internal bool _isValueTypeFixup = false;
// Created object
- internal object _newObj;
- internal object[] _objectA; //optimization, will contain object[]
- internal PrimitiveArray _primitiveArray; // for Primitive Soap arrays, optimization
+ internal object? _newObj;
+ internal object?[]? _objectA; //optimization, will contain object[]
+ internal PrimitiveArray? _primitiveArray; // for Primitive Soap arrays, optimization
internal bool _isRegistered; // Used when registering nested classes
- internal object[] _memberData; // member data is collected here before populating
- internal SerializationInfo _si;
+ internal object?[]? _memberData; // member data is collected here before populating
+ internal SerializationInfo? _si;
internal int _consecutiveNullArrayEntryCount;
// Implements a stack used for parsing
internal sealed class SerStack
{
- internal object[] _objects = new object[5];
+ internal object?[] _objects = new object?[5];
internal string _stackId;
internal int _top = -1;
}
// Pop the object from the stack
- internal object Pop()
+ internal object? Pop()
{
if (_top < 0)
{
return null;
}
- object obj = _objects[_top];
+ object? obj = _objects[_top];
_objects[_top--] = null;
return obj;
}
}
// Gets the object on the top of the stack
- internal object Peek() => _top < 0 ? null : _objects[_top];
+ internal object? Peek() => _top < 0 ? null : _objects[_top];
// Gets the second entry in the stack.
- internal object PeekPeek() => _top < 1 ? null : _objects[_top - 1];
+ internal object? PeekPeek() => _top < 1 ? null : _objects[_top - 1];
// The number of entries in the stack
internal bool IsEmpty() => _top <= 0;
// Implements a Growable array
internal sealed class SizedArray : ICloneable
{
- internal object[] _objects = null;
- internal object[] _negObjects = null;
+ internal object?[] _objects;
+ internal object?[] _negObjects;
internal SizedArray()
{
public object Clone() => new SizedArray(this);
- internal object this[int index]
+ internal object? this[int index]
{
get
{
internal sealed class NameCache
{
private static readonly ConcurrentDictionary<string, object> s_ht = new ConcurrentDictionary<string, object>();
- private string _name = null;
+ private string? _name = null;
- internal object GetCachedValue(string name)
+ internal object? GetCachedValue(string name)
{
_name = name;
- object value;
- return s_ht.TryGetValue(name, out value) ? value : null;
+ return s_ht.TryGetValue(name, out object? value) ? value : null;
}
- internal void SetCachedValue(object value) => s_ht[_name] = value;
+ internal void SetCachedValue(object value) => s_ht[_name!] = value;
}
internal sealed class ValueFixup
{
internal ValueFixupEnum _valueFixupEnum = ValueFixupEnum.Empty;
- internal Array _arrayObj;
- internal int[] _indexMap;
- internal object _header = null;
- internal object _memberObject;
- internal ReadObjectInfo _objectInfo;
- internal string _memberName;
+ internal Array? _arrayObj;
+ internal int[]? _indexMap;
+ internal object? _header = null;
+ internal object? _memberObject;
+ internal ReadObjectInfo? _objectInfo;
+ internal string? _memberName;
internal ValueFixup(Array arrayObj, int[] indexMap)
{
_indexMap = indexMap;
}
- internal ValueFixup(object memberObject, string memberName, ReadObjectInfo objectInfo)
+ internal ValueFixup(object? memberObject, string memberName, ReadObjectInfo objectInfo)
{
_valueFixupEnum = ValueFixupEnum.Member;
_memberObject = memberObject;
internal void Fixup(ParseRecord record, ParseRecord parent)
{
- object obj = record._newObj;
+ object? obj = record._newObj;
switch (_valueFixupEnum)
{
case ValueFixupEnum.Array:
- _arrayObj.SetValue(obj, _indexMap);
+ _arrayObj!.SetValue(obj, _indexMap!);
break;
case ValueFixupEnum.Header:
throw new PlatformNotSupportedException();
case ValueFixupEnum.Member:
+ Debug.Assert(_objectInfo!._objectManager != null);
if (_objectInfo._isSi)
{
- _objectInfo._objectManager.RecordDelayedFixup(parent._objectId, _memberName, record._objectId);
+ _objectInfo._objectManager.RecordDelayedFixup(parent._objectId, _memberName!, record._objectId);
}
else
{
- MemberInfo memberInfo = _objectInfo.GetMemberInfo(_memberName);
+ MemberInfo? memberInfo = _objectInfo.GetMemberInfo(_memberName);
if (memberInfo != null)
{
_objectInfo._objectManager.RecordFixup(parent._objectId, memberInfo, record._objectId);
internal sealed class NameInfo
{
- internal string _fullName; // Name from SerObjectInfo.GetType
+ internal string? _fullName; // Name from SerObjectInfo.GetType
internal long _objectId;
internal long _assemId;
internal InternalPrimitiveTypeE _primitiveTypeEnum = InternalPrimitiveTypeE.Invalid;
- internal Type _type;
+ internal Type? _type;
internal bool _isSealed;
internal bool _isArray;
internal bool _isArrayItem;
{
if (!_sealedStatusChecked)
{
+ Debug.Assert(_type != null);
_isSealed = _type.IsSealed;
_sealedStatusChecked = true;
}
}
}
- public string NIname
+ public string? NIname
{
- get { return _fullName ?? (_fullName = _type.FullName); }
+ get { return _fullName ?? (_fullName = _type?.FullName); }
set { _fullName = value; }
}
}
internal sealed class PrimitiveArray
{
private readonly InternalPrimitiveTypeE _code;
- private readonly bool[] _booleanA = null;
- private readonly char[] _charA = null;
- private readonly double[] _doubleA = null;
- private readonly short[] _int16A = null;
- private readonly int[] _int32A = null;
- private readonly long[] _int64A = null;
- private readonly sbyte[] _sbyteA = null;
- private readonly float[] _singleA = null;
- private readonly ushort[] _uint16A = null;
- private readonly uint[] _uint32A = null;
- private readonly ulong[] _uint64A = null;
+ private readonly bool[] _booleanA = null!;
+ private readonly char[] _charA = null!;
+ private readonly double[] _doubleA = null!;
+ private readonly short[] _int16A = null!;
+ private readonly int[] _int32A = null!;
+ private readonly long[] _int64A = null!;
+ private readonly sbyte[] _sbyteA = null!;
+ private readonly float[] _singleA = null!;
+ private readonly ushort[] _uint16A = null!;
+ private readonly uint[] _uint32A = null!;
+ private readonly ulong[] _uint64A = null!;
internal PrimitiveArray(InternalPrimitiveTypeE code, Array array)
{
using System.Reflection;
using System.Globalization;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
namespace System.Runtime.Serialization.Formatters.Binary
{
// contain all the types which are living in mscorlib in netfx. Therefore we
// use our mscorlib facade which also contains manual type forwards for deserialization.
internal static readonly Assembly s_urtAssembly = Assembly.Load("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
- internal static readonly string s_urtAssemblyString = s_urtAssembly.FullName;
+ internal static readonly string s_urtAssemblyString = s_urtAssembly.FullName!;
internal static readonly Assembly s_urtAlternativeAssembly = s_typeofString.Assembly;
- internal static readonly string s_urtAlternativeAssemblyString = s_urtAlternativeAssembly.FullName;
+ internal static readonly string s_urtAlternativeAssemblyString = s_urtAlternativeAssembly.FullName!;
// Arrays
internal static readonly Type s_typeofTypeArray = typeof(Type[]);
private const int PrimitiveTypeEnumLength = 17; //Number of PrimitiveTypeEnums
- private static volatile Type[] s_typeA;
- private static volatile Type[] s_arrayTypeA;
- private static volatile string[] s_valueA;
- private static volatile TypeCode[] s_typeCodeA;
- private static volatile InternalPrimitiveTypeE[] s_codeA;
+ private static volatile Type?[]? s_typeA;
+ private static volatile Type?[]? s_arrayTypeA;
+ private static volatile string?[]? s_valueA;
+ private static volatile TypeCode[]? s_typeCodeA;
+ private static volatile InternalPrimitiveTypeE[]? s_codeA;
- internal static InternalPrimitiveTypeE ToCode(Type type) =>
+ internal static InternalPrimitiveTypeE ToCode(Type? type) =>
type == null ? ToPrimitiveTypeEnum(TypeCode.Empty) :
type.IsPrimitive ? ToPrimitiveTypeEnum(Type.GetTypeCode(type)) :
ReferenceEquals(type, s_typeofDateTime) ? InternalPrimitiveTypeE.DateTime :
_ => 0,
};
- internal static Type ToArrayType(InternalPrimitiveTypeE code)
+ internal static Type? ToArrayType(InternalPrimitiveTypeE code)
{
if (s_arrayTypeA == null)
{
InitArrayTypeA();
}
- return s_arrayTypeA[(int)code];
+ return s_arrayTypeA![(int)code];
}
private static void InitTypeA()
{
- var typeATemp = new Type[PrimitiveTypeEnumLength];
+ var typeATemp = new Type?[PrimitiveTypeEnumLength];
typeATemp[(int)InternalPrimitiveTypeE.Invalid] = null;
typeATemp[(int)InternalPrimitiveTypeE.Boolean] = s_typeofBoolean;
typeATemp[(int)InternalPrimitiveTypeE.Byte] = s_typeofByte;
private static void InitArrayTypeA()
{
- var arrayTypeATemp = new Type[PrimitiveTypeEnumLength];
+ var arrayTypeATemp = new Type?[PrimitiveTypeEnumLength];
arrayTypeATemp[(int)InternalPrimitiveTypeE.Invalid] = null;
arrayTypeATemp[(int)InternalPrimitiveTypeE.Boolean] = s_typeofBooleanArray;
arrayTypeATemp[(int)InternalPrimitiveTypeE.Byte] = s_typeofByteArray;
s_arrayTypeA = arrayTypeATemp;
}
- internal static Type ToType(InternalPrimitiveTypeE code)
+ internal static Type? ToType(InternalPrimitiveTypeE code)
{
if (s_typeA == null)
{
InitTypeA();
}
- return s_typeA[(int)code];
+ return s_typeA![(int)code];
}
- internal static Array CreatePrimitiveArray(InternalPrimitiveTypeE code, int length) =>
+ internal static Array? CreatePrimitiveArray(InternalPrimitiveTypeE code, int length) =>
code switch
{
InternalPrimitiveTypeE.Boolean => new bool[length],
_ => null,
};
- internal static bool IsPrimitiveArray(Type type, out object typeInformation)
+ internal static bool IsPrimitiveArray(Type? type, [NotNullWhen(true)] out object? typeInformation)
{
bool bIsPrimitive = true;
private static void InitValueA()
{
- var valueATemp = new string[PrimitiveTypeEnumLength];
+ var valueATemp = new string?[PrimitiveTypeEnumLength];
valueATemp[(int)InternalPrimitiveTypeE.Invalid] = null;
valueATemp[(int)InternalPrimitiveTypeE.Boolean] = "Boolean";
valueATemp[(int)InternalPrimitiveTypeE.Byte] = "Byte";
s_valueA = valueATemp;
}
- internal static string ToComType(InternalPrimitiveTypeE code)
+ internal static string? ToComType(InternalPrimitiveTypeE code)
{
if (s_valueA == null)
{
InitValueA();
}
- return s_valueA[(int)code];
+ return s_valueA![(int)code];
}
private static void InitTypeCodeA()
{
InitTypeCodeA();
}
- return s_typeCodeA[(int)code];
+ return s_typeCodeA![(int)code];
}
private static void InitCodeA()
{
InitCodeA();
}
- return s_codeA[(int)typeCode];
+ return s_codeA![(int)typeCode];
}
// Translates a string into an Object
- internal static object FromString(string value, InternalPrimitiveTypeE code)
+ internal static object? FromString(string? value, InternalPrimitiveTypeE code)
{
// InternalPrimitiveTypeE needs to be a primitive type
Debug.Assert((code != InternalPrimitiveTypeE.Invalid), "[Converter.FromString]!InternalPrimitiveTypeE.Invalid ");
internal sealed class MemberPrimitiveTyped : IStreamable
{
internal InternalPrimitiveTypeE _primitiveTypeEnum;
- internal object _value;
+ internal object? _value;
internal MemberPrimitiveTyped() { }
- internal void Set(InternalPrimitiveTypeE primitiveTypeEnum, object value)
+ internal void Set(InternalPrimitiveTypeE primitiveTypeEnum, object? value)
{
_primitiveTypeEnum = primitiveTypeEnum;
_value = value;
{
// Used for members with primitive values and types are needed
internal InternalPrimitiveTypeE _typeInformation;
- internal object _value;
+ internal object? _value;
internal MemberPrimitiveUnTyped() { }
- internal void Set(InternalPrimitiveTypeE typeInformation, object value)
+ internal void Set(InternalPrimitiveTypeE typeInformation, object? value)
{
_typeInformation = typeInformation;
_value = value;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
+
namespace System.Runtime.Serialization.Formatters.Binary
{
// When an ObjectWithMap or an ObjectWithMapTyped is read off the stream, an ObjectMap class is created
internal sealed class ObjectMap
{
internal string _objectName;
- internal Type _objectType;
+ internal Type? _objectType;
internal BinaryTypeEnum[] _binaryTypeEnumA;
- internal object[] _typeInformationA;
- internal Type[] _memberTypes;
+ internal object?[] _typeInformationA;
+ internal Type?[] _memberTypes;
internal string[] _memberNames;
internal ReadObjectInfo _objectInfo;
internal bool _isInitObjectInfo = true;
- internal ObjectReader _objectReader = null;
+ internal ObjectReader? _objectReader = null;
internal int _objectId;
internal BinaryAssemblyInfo _assemblyInfo;
_assemblyInfo = assemblyInfo;
_objectInfo = objectReader.CreateReadObjectInfo(objectType);
- _memberTypes = _objectInfo.GetMemberTypes(memberNames, objectType);
+ _memberTypes = _objectInfo.GetMemberTypes(memberNames, objectType)!;
_binaryTypeEnumA = new BinaryTypeEnum[_memberTypes.Length];
_typeInformationA = new object[_memberTypes.Length];
for (int i = 0; i < _memberTypes.Length; i++)
{
- object typeInformation = null;
- BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetParserBinaryTypeInfo(_memberTypes[i], out typeInformation);
+ BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetParserBinaryTypeInfo(_memberTypes[i]!, out object? typeInformation);
_binaryTypeEnumA[i] = binaryTypeEnum;
_typeInformationA[i] = typeInformation;
}
}
- internal ObjectMap(string objectName, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object[] typeInformationA, int[] memberAssemIds, ObjectReader objectReader, int objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable)
+ internal ObjectMap(string objectName, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object?[] typeInformationA, int[] memberAssemIds, ObjectReader objectReader, int objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable)
{
_objectName = objectName;
_memberNames = memberNames;
for (int i = 0; i < memberNames.Length; i++)
{
InternalPrimitiveTypeE primitiveTypeEnum;
- string typeString;
- Type type;
bool isVariant;
BinaryTypeConverter.TypeFromInfo(
- binaryTypeEnumA[i], typeInformationA[i], objectReader, (BinaryAssemblyInfo)assemIdToAssemblyTable[memberAssemIds[i]],
- out primitiveTypeEnum, out typeString, out type, out isVariant);
+ binaryTypeEnumA[i], typeInformationA[i], objectReader, (BinaryAssemblyInfo?)assemIdToAssemblyTable[memberAssemIds[i]],
+ out primitiveTypeEnum, out string? typeString, out Type? type, out isVariant);
_memberTypes[i] = type;
}
}
}
- internal ReadObjectInfo CreateObjectInfo(ref SerializationInfo si, ref object[] memberData)
+ internal ReadObjectInfo CreateObjectInfo(ref SerializationInfo? si, ref object?[]? memberData)
{
if (_isInitObjectInfo)
{
// Member type information
internal static ObjectMap Create(
- string name, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object[] typeInformationA,
+ string name, string[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, object?[] typeInformationA,
int[] memberAssemIds, ObjectReader objectReader, int objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable) =>
new ObjectMap(name, memberNames, binaryTypeEnumA, typeInformationA, memberAssemIds, objectReader, objectId, assemblyInfo, assemIdToAssemblyTable);
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+
namespace System.Runtime.Serialization.Formatters.Binary
{
// For each object or array being read off the stream, an ObjectProgress object is created. This object
internal bool _isInitial;
internal int _count; //Progress count
internal BinaryTypeEnum _expectedType = BinaryTypeEnum.ObjectUrt;
- internal object _expectedTypeInformation = null;
+ internal object? _expectedTypeInformation = null;
- internal string _name;
+ internal string? _name;
internal InternalObjectTypeE _objectTypeEnum = InternalObjectTypeE.Empty;
internal InternalMemberTypeE _memberTypeEnum;
internal InternalMemberValueE _memberValueEnum;
- internal Type _dtType;
+ internal Type? _dtType;
// Array Information
internal int _numItems;
internal BinaryTypeEnum _binaryTypeEnum;
- internal object _typeInformation;
+ internal object? _typeInformation;
// Member Information
internal int _memberLength;
- internal BinaryTypeEnum[] _binaryTypeEnumA;
- internal object[] _typeInformationA;
- internal string[] _memberNames;
- internal Type[] _memberTypes;
+ internal BinaryTypeEnum[]? _binaryTypeEnumA;
+ internal object?[]? _typeInformationA;
+ internal string[]? _memberNames;
+ internal Type?[]? _memberTypes;
// ParseRecord
internal ParseRecord _pr = new ParseRecord();
internal void ArrayCountIncrement(int value) => _count += value;
// Specifies what is to parsed next from the wire.
- internal bool GetNext(out BinaryTypeEnum outBinaryTypeEnum, out object outTypeInformation)
+ internal bool GetNext(out BinaryTypeEnum outBinaryTypeEnum, [NotNullWhen(true)] out object? outTypeInformation)
{
//Initialize the out params up here.
outBinaryTypeEnum = BinaryTypeEnum.Primitive;
}
else
{
+ Debug.Assert(_binaryTypeEnumA != null && _typeInformationA != null && _memberNames != null && _memberTypes != null);
outBinaryTypeEnum = _binaryTypeEnumA[_count];
outTypeInformation = _typeInformationA[_count];
if (_count == 0)
{
public interface IFieldInfo
{
- string[] FieldNames { get; set; }
- Type[] FieldTypes { get; set; }
+ string[]? FieldNames { get; set; }
+ Type[]? FieldTypes { get; set; }
}
}
{
object Deserialize(Stream serializationStream);
void Serialize(Stream serializationStream, object graph);
- ISurrogateSelector SurrogateSelector { get; set; }
- SerializationBinder Binder { get; set; }
+ ISurrogateSelector? SurrogateSelector { get; set; }
+ SerializationBinder? Binder { get; set; }
StreamingContext Context { get; set; }
}
}
public interface ISerializationSurrogate
{
void GetObjectData(object obj, SerializationInfo info, StreamingContext context);
- object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector);
+ object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector? selector);
}
}
public interface ISurrogateSelector
{
void ChainSelector(ISurrogateSelector selector);
- ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector);
- ISurrogateSelector GetNextSelector();
+ ISerializationSurrogate? GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector);
+ ISurrogateSelector? GetNextSelector();
}
}
{
internal sealed class MemberHolder
{
- internal readonly MemberInfo[] _members = null;
+ internal readonly MemberInfo[]? _members = null;
internal readonly Type _memberType;
internal readonly StreamingContext _context;
public override int GetHashCode() => _memberType.GetHashCode();
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
- var mh = obj as MemberHolder;
- return
- mh != null &&
+ return obj is MemberHolder mh &&
ReferenceEquals(mh._memberType, _memberType) &&
mh._context.State == _context.State;
}
using System.Diagnostics;
using System.Reflection;
using System.Globalization;
+using System.Diagnostics.CodeAnalysis;
namespace System.Runtime.Serialization
{
private const int ArrayMask = MaxArraySize - 1;
private const int MaxReferenceDepth = 100;
- private DeserializationEventHandler _onDeserializationHandler;
- private SerializationEventHandler _onDeserializedHandler;
+ private DeserializationEventHandler? _onDeserializationHandler;
+ private SerializationEventHandler? _onDeserializedHandler;
internal ObjectHolder[] _objects;
- internal object _topObject = null;
- internal ObjectHolderList _specialFixupObjects; //This is IObjectReference, ISerializable, or has a Surrogate.
+ internal object? _topObject = null;
+ internal ObjectHolderList? _specialFixupObjects; //This is IObjectReference, ISerializable, or has a Surrogate.
internal long _fixupCount;
- internal readonly ISurrogateSelector _selector;
+ internal readonly ISurrogateSelector? _selector;
internal readonly StreamingContext _context;
- public ObjectManager(ISurrogateSelector selector, StreamingContext context)
+ public ObjectManager(ISurrogateSelector? selector, StreamingContext context)
{
_objects = new ObjectHolder[DefaultInitialSize];
_selector = selector;
_context = context;
}
- private bool CanCallGetType(object obj) => true;
+ private bool CanCallGetType(object? obj) => true;
- internal object TopObject
+ internal object? TopObject
{
get { return _topObject; }
set { _topObject = value; }
internal ObjectHolderList SpecialFixupObjects =>
_specialFixupObjects ?? (_specialFixupObjects = new ObjectHolderList());
- internal ObjectHolder FindObjectHolder(long objectID)
+ internal ObjectHolder? FindObjectHolder(long objectID)
{
// The index of the bin in which we live is rightmost n bits of the objectID.
int index = (int)(objectID & ArrayMask);
}
// Find the bin in which we live.
- ObjectHolder temp = _objects[index];
+ ObjectHolder? temp = _objects[index];
// Walk the chain in that bin. Return the ObjectHolder if we find it, otherwise
// return null.
internal ObjectHolder FindOrCreateObjectHolder(long objectID)
{
- ObjectHolder holder;
- holder = FindObjectHolder(objectID);
+ ObjectHolder? holder = FindObjectHolder(objectID);
if (holder == null)
{
holder = new ObjectHolder(objectID);
_objects[index] = holder;
}
- private bool GetCompletionInfo(FixupHolder fixup, out ObjectHolder holder, out object member, bool bThrowIfMissing)
+ private bool GetCompletionInfo(FixupHolder fixup, [NotNullWhen(true)] out ObjectHolder? holder, out object member, bool bThrowIfMissing)
{
//Set the member id (String or MemberInfo) for the member being fixed up.
member = fixup._fixupInfo;
//Find the object required for the fixup. Throw if we can't find it.
holder = FindObjectHolder(fixup._id);
- // CompletelyFixed is our poorly named property which indicates if something requires a SerializationInfo fixup
- // or is an incomplete object reference. We have this particular branch to handle valuetypes which implement
- // ISerializable. In that case, we can't do any fixups on them later, so we need to delay the fixups further.
- if (!holder.CompletelyFixed)
- {
- if (holder.ObjectValue != null && holder.ObjectValue is ValueType)
- {
- SpecialFixupObjects.Add(holder);
- return false;
- }
- }
-
if (holder == null || holder.CanObjectValueChange || holder.ObjectValue == null)
{
if (bThrowIfMissing)
}
return false;
}
+
+ // CompletelyFixed is our poorly named property which indicates if something requires a SerializationInfo fixup
+ // or is an incomplete object reference. We have this particular branch to handle valuetypes which implement
+ // ISerializable. In that case, we can't do any fixups on them later, so we need to delay the fixups further.
+ if (!holder.CompletelyFixed)
+ {
+ if (holder.ObjectValue != null && holder.ObjectValue is ValueType)
+ {
+ SpecialFixupObjects.Add(holder);
+ return false;
+ }
+ }
+
return true;
}
private void FixupSpecialObject(ObjectHolder holder)
{
- ISurrogateSelector uselessSelector = null;
+ ISurrogateSelector? uselessSelector = null;
Debug.Assert(holder.RequiresSerInfoFixup, "[ObjectManager.FixupSpecialObject]holder.HasSurrogate||holder.HasISerializable");
if (holder.HasSurrogate)
{
- ISerializationSurrogate surrogate = holder.Surrogate;
+ ISerializationSurrogate? surrogate = holder.Surrogate;
Debug.Assert(surrogate != null, "surrogate!=null");
- object returnValue = surrogate.SetObjectData(holder.ObjectValue, holder.SerializationInfo, _context, uselessSelector);
+ Debug.Assert(holder.SerializationInfo != null);
+ object? returnValue = surrogate.SetObjectData(holder.ObjectValue!, holder.SerializationInfo, _context, uselessSelector);
if (returnValue != null)
{
if (!holder.CanSurrogatedObjectValueChange && returnValue != holder.ObjectValue)
/// <param name="holder"></param>
private bool ResolveObjectReference(ObjectHolder holder)
{
- object tempObject;
+ object? tempObject;
Debug.Assert(holder.IsIncompleteObjectReference, "holder.IsIncompleteObjectReference");
//In the pathological case, an Object implementing IObjectReference could return a reference
do
{
tempObject = holder.ObjectValue;
+ Debug.Assert(holder.ObjectValue != null);
holder.SetObjectValue(((IObjectReference)(holder.ObjectValue)).GetRealObject(_context), this);
//The object didn't yet have enough information to resolve the reference, so we'll
//return false and the graph walker should call us back again after more objects have
** holder -- the ObjectHolder for the object (a value type in this case) being completed.
** value -- the data to set into the field.
==============================================================================*/
- private bool DoValueTypeFixup(FieldInfo memberToFix, ObjectHolder holder, object value)
+ private bool DoValueTypeFixup(FieldInfo? memberToFix, ObjectHolder holder, object? value)
{
var fieldsTemp = new FieldInfo[4];
- FieldInfo[] fields = null;
+ FieldInfo[] fields;
int currentFieldIndex = 0;
- int[] arrayIndex = null;
- ValueTypeFixupInfo currFixup = null;
- object fixupObj = holder.ObjectValue;
- ObjectHolder originalHolder = holder;
+ int[]? arrayIndex = null;
+ ValueTypeFixupInfo currFixup;
+ object? fixupObj = holder.ObjectValue;
Debug.Assert(holder != null, "[TypedReferenceBuilder.ctor]holder!=null");
Debug.Assert(holder.RequiresValueTypeFixup, "[TypedReferenceBuilder.ctor]holder.RequiresValueTypeFixup");
//object that we have. In most cases, we could have just grabbed it after this loop finished.
//However, if the outermost containing object is an array, we need the object one further
//down the chain, so we have to do a lot of caching.
- currFixup = holder.ValueFixup;
+ currFixup = holder.ValueFixup!;
fixupObj = holder.ObjectValue; //Save the most derived
if (currFixup.ParentField != null)
{
FieldInfo parentField = currFixup.ParentField;
- ObjectHolder tempHolder = FindObjectHolder(currFixup.ContainerID);
+ ObjectHolder? tempHolder = FindObjectHolder(currFixup.ContainerID);
+ Debug.Assert(tempHolder != null);
if (tempHolder.ObjectValue == null)
{
break;
}
if (Nullable.GetUnderlyingType(parentField.FieldType) != null)
{
- fieldsTemp[currentFieldIndex] = parentField.FieldType.GetField(nameof(value), BindingFlags.NonPublic | BindingFlags.Instance);
+ fieldsTemp[currentFieldIndex] = parentField.FieldType.GetField(nameof(value), BindingFlags.NonPublic | BindingFlags.Instance)!;
currentFieldIndex++;
}
{
//If we find an index into an array, save that information.
Debug.Assert(currFixup.ParentIndex != null, "[ObjectManager.DoValueTypeFixup]currFixup.ParentIndex!=null");
- holder = FindObjectHolder(currFixup.ContainerID); //find the array to fix.
+ holder = FindObjectHolder(currFixup.ContainerID)!; //find the array to fix.
arrayIndex = currFixup.ParentIndex;
break;
}
fields = new FieldInfo[currentFieldIndex];
for (int i = 0; i < currentFieldIndex; i++)
{
- FieldInfo fieldInfo = fieldsTemp[(currentFieldIndex - 1 - i)];
- SerializationFieldInfo serInfo = fieldInfo as SerializationFieldInfo;
+ FieldInfo? fieldInfo = fieldsTemp[(currentFieldIndex - 1 - i)];
+ SerializationFieldInfo? serInfo = fieldInfo as SerializationFieldInfo;
fields[i] = serInfo == null ? fieldInfo : serInfo.FieldInfo;
}
TypedReference typedRef = TypedReference.MakeTypedReference(fixupObj, fields);
if (memberToFix != null)
{
- memberToFix.SetValueDirect(typedRef, value);
+ memberToFix.SetValueDirect(typedRef, value!);
}
else
{
internal void CompleteObject(ObjectHolder holder, bool bObjectFullyComplete)
{
- FixupHolderList fixups = holder._missingElements;
- FixupHolder currentFixup;
- SerializationInfo si;
- object fixupInfo = null;
- ObjectHolder tempObjectHolder = null;
+ FixupHolderList? fixups = holder._missingElements;
+ FixupHolder? currentFixup;
+ SerializationInfo? si;
+ object? fixupInfo = null;
+ ObjectHolder? tempObjectHolder = null;
int fixupsPerformed = 0;
Debug.Assert(holder != null, "[ObjectManager.CompleteObject]holder.m_object!=null");
{
continue;
}
- Debug.Assert(fixups._values[i]._fixupType == FixupHolder.DelayedFixup, "fixups.m_values[i].m_fixupType==FixupHolder.DelayedFixup");
- if (GetCompletionInfo(fixups._values[i], out tempObjectHolder, out fixupInfo, bObjectFullyComplete))
+ Debug.Assert(fixups._values[i]!._fixupType == FixupHolder.DelayedFixup, "fixups.m_values[i].m_fixupType==FixupHolder.DelayedFixup");
+ if (GetCompletionInfo(fixups._values[i]!, out tempObjectHolder, out fixupInfo, bObjectFullyComplete))
{
//Walk the SerializationInfo and find the member needing completion. All we have to do
//at this point is set the member into the Object
- object holderValue = tempObjectHolder.ObjectValue;
+ object? holderValue = tempObjectHolder.ObjectValue;
+ Debug.Assert(holderValue != null);
if (CanCallGetType(holderValue))
{
si.UpdateValue((string)fixupInfo, holderValue, holderValue.GetType());
// throw an exception with the type name
if (holder.Reachable)
{
- throw new SerializationException(SR.Format(SR.Serialization_TypeLoadFailure, holder.TypeLoadException.TypeName));
+ throw new SerializationException(SR.Format(SR.Serialization_TypeLoadFailure, holder.TypeLoadException!.TypeName));
}
}
_fixupCount -= fixupsPerformed;
- if (fixups._count == fixupsPerformed)
+ if (fixups!._count == fixupsPerformed)
{
holder._missingElements = null;
}
}
//If we don't have any dependencies, we're done.
- LongList dependencies = holder.DependentObjects;
+ LongList? dependencies = holder.DependentObjects;
if (dependencies == null)
{
return;
dependencies.StartEnumeration();
while (dependencies.MoveNext())
{
- ObjectHolder temp = FindObjectHolder(dependencies.Current);
+ ObjectHolder? temp = FindObjectHolder(dependencies.Current);
+ Debug.Assert(temp != null);
Debug.Assert(temp.DirectlyDependentObjects > 0, "temp.m_missingElementsRemaining>0");
temp.DecrementFixupsRemaining(this);
if (((temp.DirectlyDependentObjects)) == 0)
}
}
- public virtual object GetObject(long objectID)
+ public virtual object? GetObject(long objectID)
{
if (objectID <= 0)
{
//Find the bin in which we're interested. IObjectReference's shouldn't be returned -- the graph
//needs to link to the objects to which they refer, not to the references themselves.
- ObjectHolder holder = FindObjectHolder(objectID);
+ ObjectHolder? holder = FindObjectHolder(objectID);
if (holder == null || holder.CanObjectValueChange)
{
return null;
RegisterObject(obj, objectID, info, 0, null);
}
- public void RegisterObject(object obj, long objectID, SerializationInfo info, long idOfContainingObj, MemberInfo member)
+ public void RegisterObject(object obj, long objectID, SerializationInfo? info, long idOfContainingObj, MemberInfo? member)
{
RegisterObject(obj, objectID, info, idOfContainingObj, member, null);
}
- internal void RegisterString(string obj, long objectID, SerializationInfo info, long idOfContainingObj, MemberInfo member)
+ internal void RegisterString(string? obj, long objectID, SerializationInfo? info, long idOfContainingObj, MemberInfo? member)
{
ObjectHolder temp;
Debug.Assert(member == null || member is FieldInfo, "RegisterString - member is FieldInfo");
- temp = new ObjectHolder(obj, objectID, info, null, idOfContainingObj, (FieldInfo)member, null);
+ temp = new ObjectHolder(obj, objectID, info, null, idOfContainingObj, (FieldInfo?)member, null);
AddObjectHolder(temp);
return;
}
- public void RegisterObject(object obj, long objectID, SerializationInfo info, long idOfContainingObj, MemberInfo member, int[] arrayIndex)
+ public void RegisterObject(object obj, long objectID, SerializationInfo? info, long idOfContainingObj, MemberInfo? member, int[]? arrayIndex)
{
if (obj == null)
{
throw new SerializationException(SR.Serialization_UnknownMemberInfo);
}
- ObjectHolder temp;
- ISerializationSurrogate surrogate = null;
+ ObjectHolder? temp;
+ ISerializationSurrogate? surrogate = null;
ISurrogateSelector useless;
if (_selector != null)
temp = FindObjectHolder(objectID);
if (temp == null)
{
- temp = new ObjectHolder(obj, objectID, info, surrogate, idOfContainingObj, (FieldInfo)member, arrayIndex);
+ temp = new ObjectHolder(obj, objectID, info, surrogate, idOfContainingObj, (FieldInfo?)member, arrayIndex);
AddObjectHolder(temp);
if (temp.RequiresDelayedFixup)
{
}
//Complete the data in the ObjectHolder
- temp.UpdateData(obj, info, surrogate, idOfContainingObj, (FieldInfo)member, arrayIndex, this);
+ temp.UpdateData(obj, info, surrogate, idOfContainingObj, (FieldInfo?)member, arrayIndex, this);
// The following case will only be true when somebody has registered a fixup on an object before
// registering the object itself. I don't believe that most well-behaved formatters will do this,
/// <param name="obj">The object to be completed.</param>
/// <param name="info">The SerializationInfo containing all info for obj.</param>
/// <param name="context">The streaming context in which the serialization is taking place.</param>
- internal void CompleteISerializableObject(object obj, SerializationInfo info, StreamingContext context)
+ internal void CompleteISerializableObject(object obj, SerializationInfo? info, StreamingContext context)
{
if (obj == null)
{
throw new ArgumentException(SR.Serialization_NotISer);
}
- ConstructorInfo constInfo = null;
+ ConstructorInfo constInfo;
Type t = obj.GetType();
try
{
throw new SerializationException(SR.Format(SR.Serialization_ConstructorNotFound, t), e);
}
- constInfo.Invoke(obj, new object[] { info, context });
+ constInfo.Invoke(obj, new object?[] { info, context });
}
internal static ConstructorInfo GetDeserializationConstructor(Type t)
public virtual void DoFixups()
{
- ObjectHolder temp;
+ ObjectHolder? temp;
int fixupCount = -1;
//The first thing that we need to do is fixup all of the objects which implement
internal const int SER_INFO_FIXED = 0x4000;
internal const int VALUETYPE_FIXUP_PERFORMED = 0x8000;
- private object _object;
+ private object? _object;
internal readonly long _id;
private int _missingElementsRemaining;
private int _missingDecendents;
- internal SerializationInfo _serInfo;
- internal ISerializationSurrogate _surrogate;
- internal FixupHolderList _missingElements;
- internal LongList _dependentObjects;
- internal ObjectHolder _next;
+ internal SerializationInfo? _serInfo;
+ internal ISerializationSurrogate? _surrogate;
+ internal FixupHolderList? _missingElements;
+ internal LongList? _dependentObjects;
+ internal ObjectHolder? _next;
internal int _flags;
private bool _markForFixupWhenAvailable;
- private ValueTypeFixupInfo _valueFixup;
- private TypeLoadExceptionHolder _typeLoad = null;
+ private ValueTypeFixupInfo? _valueFixup;
+ private TypeLoadExceptionHolder? _typeLoad = null;
private bool _reachable = false;
internal ObjectHolder(long objID) : this(null, objID, null, null, 0, null, null)
}
internal ObjectHolder(
- object obj, long objID, SerializationInfo info, ISerializationSurrogate surrogate,
- long idOfContainingObj, FieldInfo field, int[] arrayIndex)
+ object? obj, long objID, SerializationInfo? info, ISerializationSurrogate? surrogate,
+ long idOfContainingObj, FieldInfo? field, int[]? arrayIndex)
{
Debug.Assert(objID >= 0, "objID>=0");
}
internal ObjectHolder(
- string obj, long objID, SerializationInfo info, ISerializationSurrogate surrogate,
- long idOfContainingObj, FieldInfo field, int[] arrayIndex)
+ string? obj, long objID, SerializationInfo? info, ISerializationSurrogate? surrogate,
+ long idOfContainingObj, FieldInfo? field, int[]? arrayIndex)
{
Debug.Assert(objID >= 0, "objID>=0");
/// <param name="surrogate">The surrogate handling this object. May be null.</param>
/// <param name="idOfContainer">The id of the object containing this one if this is a valuetype.</param>
internal void UpdateData(
- object obj, SerializationInfo info, ISerializationSurrogate surrogate, long idOfContainer,
- FieldInfo field, int[] arrayIndex, ObjectManager manager)
+ object obj, SerializationInfo? info, ISerializationSurrogate? surrogate, long idOfContainer,
+ FieldInfo? field, int[]? arrayIndex, ObjectManager manager)
{
Debug.Assert(obj != null, "obj!=null");
Debug.Assert(_id > 0, "m_id>0");
internal bool TypeLoadExceptionReachable => _typeLoad != null;
- internal TypeLoadExceptionHolder TypeLoadException { get { return _typeLoad; } set { _typeLoad = value; } }
+ internal TypeLoadExceptionHolder? TypeLoadException { get { return _typeLoad; } set { _typeLoad = value; } }
- internal object ObjectValue => _object;
+ internal object? ObjectValue => _object;
- internal void SetObjectValue(object obj, ObjectManager manager)
+ internal void SetObjectValue(object? obj, ObjectManager manager)
{
_object = obj;
if (obj == manager.TopObject)
}
}
- internal SerializationInfo SerializationInfo { get { return _serInfo; } set { _serInfo = value; } }
+ internal SerializationInfo? SerializationInfo { get { return _serInfo; } set { _serInfo = value; } }
- internal ISerializationSurrogate Surrogate => _surrogate;
+ internal ISerializationSurrogate? Surrogate => _surrogate;
- internal LongList DependentObjects { get { return _dependentObjects; } set { _dependentObjects = value; } }
+ internal LongList? DependentObjects { get { return _dependentObjects; } set { _dependentObjects = value; } }
internal bool RequiresSerInfoFixup
{
}
}
- internal ValueTypeFixupInfo ValueFixup => _valueFixup;
+ internal ValueTypeFixupInfo? ValueFixup => _valueFixup;
internal bool CompletelyFixed => !RequiresSerInfoFixup && !IsIncompleteObjectReference;
{
internal const int InitialSize = 2;
- internal FixupHolder[] _values;
+ internal FixupHolder?[] _values;
internal int _count;
internal FixupHolderList() : this(InitialSize)
public sealed class TypeLoadExceptionHolder
{
- internal TypeLoadExceptionHolder(string typeName)
+ internal TypeLoadExceptionHolder(string? typeName)
{
TypeName = typeName;
}
- internal string TypeName { get; }
+ internal string? TypeName { get; }
}
internal static class SerializationInfoExtensions
{
private static readonly Action<SerializationInfo, string, object, Type> s_updateValue =
(Action<SerializationInfo, string, object, Type>)typeof(SerializationInfo)
- .GetMethod("UpdateValue", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
+ .GetMethod("UpdateValue", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)!
.CreateDelegate(typeof(Action<SerializationInfo, string, object, Type>));
public static void UpdateValue(this SerializationInfo si, string name, object value, Type type) =>
{
public abstract class SerializationBinder
{
- public virtual void BindToName(Type serializedType, out string assemblyName, out string typeName)
+ public virtual void BindToName(Type serializedType, out string? assemblyName, out string? typeName)
{
assemblyName = null;
typeName = null;
}
- public abstract Type BindToType(string assemblyName, string typeName);
+ public abstract Type? BindToType(string assemblyName, string typeName);
}
}
{
internal sealed class SerializationEvents
{
- private readonly List<MethodInfo> _onSerializingMethods;
- private readonly List<MethodInfo> _onSerializedMethods;
- private readonly List<MethodInfo> _onDeserializingMethods;
- private readonly List<MethodInfo> _onDeserializedMethods;
+ private readonly List<MethodInfo>? _onSerializingMethods;
+ private readonly List<MethodInfo>? _onSerializedMethods;
+ private readonly List<MethodInfo>? _onDeserializingMethods;
+ private readonly List<MethodInfo>? _onDeserializedMethods;
- internal SerializationEvents(Type t)
+ internal SerializationEvents(Type? t)
{
_onSerializingMethods = GetMethodsWithAttribute(typeof(OnSerializingAttribute), t);
_onSerializedMethods = GetMethodsWithAttribute(typeof(OnSerializedAttribute), t);
_onDeserializedMethods = GetMethodsWithAttribute(typeof(OnDeserializedAttribute), t);
}
- private List<MethodInfo> GetMethodsWithAttribute(Type attribute, Type t)
+ private List<MethodInfo>? GetMethodsWithAttribute(Type attribute, Type? t)
{
- List<MethodInfo> mi = null;
+ List<MethodInfo>? mi = null;
// Traverse the hierarchy to find all methods with the particular attribute
- Type baseType = t;
+ Type? baseType = t;
while (baseType != null && baseType != typeof(object))
{
// Get all methods which are declared on this type, instance and public or nonpublic
internal void InvokeOnDeserialized(object obj, StreamingContext context) =>
InvokeOnDelegate(obj, context, _onDeserializedMethods);
- internal SerializationEventHandler AddOnSerialized(object obj, SerializationEventHandler handler) =>
+ internal SerializationEventHandler? AddOnSerialized(object obj, SerializationEventHandler? handler) =>
AddOnDelegate(obj, handler, _onSerializedMethods);
- internal SerializationEventHandler AddOnDeserialized(object obj, SerializationEventHandler handler) =>
+ internal SerializationEventHandler? AddOnDeserialized(object obj, SerializationEventHandler? handler) =>
AddOnDelegate(obj, handler, _onDeserializedMethods);
/// <summary>Invoke all methods.</summary>
- private static void InvokeOnDelegate(object obj, StreamingContext context, List<MethodInfo> methods)
+ private static void InvokeOnDelegate(object obj, StreamingContext context, List<MethodInfo>? methods)
{
Debug.Assert(obj != null, "object should have been initialized");
AddOnDelegate(obj, null, methods)?.Invoke(context);
}
/// <summary>Add all methods to a delegate.</summary>
- private static SerializationEventHandler AddOnDelegate(object obj, SerializationEventHandler handler, List<MethodInfo> methods)
+ private static SerializationEventHandler? AddOnDelegate(object obj, SerializationEventHandler? handler, List<MethodInfo>? methods)
{
if (methods != null)
{
public override int MetadataToken { get { return m_field.MetadataToken; } }
- public override Type DeclaringType => m_field.DeclaringType;
+ public override Type? DeclaringType => m_field.DeclaringType;
- public override Type ReflectedType => m_field.ReflectedType;
+ public override Type? ReflectedType => m_field.ReflectedType;
public override object[] GetCustomAttributes(bool inherit) => m_field.GetCustomAttributes(inherit);
public override Type FieldType => m_field.FieldType;
- public override object GetValue(object obj) => m_field.GetValue(obj);
+ public override object? GetValue(object? obj) => m_field.GetValue(obj);
- public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) => m_field.SetValue(obj, value, invokeAttr, binder, culture);
+ public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture) => m_field.SetValue(obj, value, invokeAttr, binder, culture);
public override RuntimeFieldHandle FieldHandle => m_field.FieldHandle;
{
private readonly Dictionary<object, object> _objectSeenTable; // Table to keep track of objects [OnSerializing] has been called on
private readonly StreamingContext _context;
- private SerializationEventHandler _onSerializedHandler;
+ private SerializationEventHandler? _onSerializedHandler;
public SerializationObjectManager(StreamingContext context)
{
public class SurrogateSelector : ISurrogateSelector
{
internal readonly SurrogateHashtable _surrogates = new SurrogateHashtable(32);
- internal ISurrogateSelector _nextSelector;
+ internal ISurrogateSelector? _nextSelector;
public virtual void AddSurrogate(Type type, StreamingContext context, ISerializationSurrogate surrogate)
{
{
Debug.Assert(selector != null, "[HasCycle]selector!=null");
- ISurrogateSelector head = selector, tail = selector;
+ ISurrogateSelector? head = selector, tail = selector;
while (head != null)
{
head = head.GetNextSelector();
return false;
}
head = head.GetNextSelector();
- tail = tail.GetNextSelector();
+ tail = tail!.GetNextSelector();
if (head == tail)
{
// Check for a cycle that would lead back to this. We find the end of the list that we're being asked to
// insert for use later.
- ISurrogateSelector tempCurr = selector.GetNextSelector();
+ ISurrogateSelector? tempCurr = selector.GetNextSelector();
ISurrogateSelector tempEnd = selector;
while (tempCurr != null && tempCurr != this)
{
// Check for a cycle later in the list which would be introduced by this insertion.
tempCurr = selector;
- ISurrogateSelector tempPrev = selector;
+ ISurrogateSelector? tempPrev = selector;
while (tempCurr != null)
{
if (tempCurr == tempEnd)
}
else
{
+ Debug.Assert(tempPrev != null);
tempPrev = tempPrev.GetNextSelector();
}
if (tempCurr == tempPrev)
}
// Add the new selector and it's entire chain of selectors as the next thing that we check.
- ISurrogateSelector temp = _nextSelector;
+ ISurrogateSelector? temp = _nextSelector;
_nextSelector = selector;
if (temp != null)
{
}
// Get the next selector on the chain of selectors.
- public virtual ISurrogateSelector GetNextSelector() => _nextSelector;
+ public virtual ISurrogateSelector? GetNextSelector() => _nextSelector;
// Gets the surrogate for a particular type. If this selector can't
// provide a surrogate, it checks with all of it's children before returning null.
- public virtual ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector)
+ public virtual ISerializationSurrogate? GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector)
{
if (type == null)
{
selector = this;
SurrogateKey key = new SurrogateKey(type, context);
- ISerializationSurrogate temp = (ISerializationSurrogate)_surrogates[key];
+ ISerializationSurrogate? temp = (ISerializationSurrogate?)_surrogates[key];
if (temp != null)
{
return temp;
// is a subset of the context for which the serialization selector is provided (presentContext)
// Note: This is done by overriding KeyEquals rather than overriding Equals() in the SurrogateKey
// class because Equals() method must be commutative.
+#pragma warning disable CS8610
protected override bool KeyEquals(object key, object item)
+#pragma warning restore CS8610
{
SurrogateKey givenValue = (SurrogateKey)item;
SurrogateKey presentValue = (SurrogateKey)key;
/// apply if the containing body is a field info or another
/// value type.
/// </summary>
- private readonly FieldInfo _parentField;
+ private readonly FieldInfo? _parentField;
/// <summary>
/// The array index of the index into the parent. This will only
/// apply if the containing body is an array.
/// </summary>
- private readonly int[] _parentIndex;
+ private readonly int[]? _parentIndex;
- public ValueTypeFixupInfo(long containerID, FieldInfo member, int[] parentIndex)
+ public ValueTypeFixupInfo(long containerID, FieldInfo? member, int[]? parentIndex)
{
// If both member and arrayIndex are null, we don't have enough information to create
// a tunnel to do the fixup.
public long ContainerID => _containerID;
- public FieldInfo ParentField => _parentField;
+ public FieldInfo? ParentField => _parentField;
- public int[] ParentIndex => _parentIndex;
+ public int[]? ParentIndex => _parentIndex;
}
}