Skip to content

Commit d6a8bf6

Browse files
committed
feat(serialization): Added support for writing nulls
1 parent 7b30ad0 commit d6a8bf6

File tree

3 files changed

+34
-3
lines changed

3 files changed

+34
-3
lines changed

MLAPI/Data/TypeExtensions.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,19 @@ internal static bool HasInterface(this Type type, Type interfaceType)
1414
}
1515
return false;
1616
}
17+
18+
internal static bool IsNullable<T>(this T obj)
19+
{
20+
if (obj == null) return true;
21+
22+
return typeof(T).IsNullable();
23+
}
24+
25+
internal static bool IsNullable(this Type type)
26+
{
27+
if (!type.IsValueType) return true; // ref-type
28+
if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T>
29+
return false; // value-type
30+
}
1731
}
1832
}

MLAPI/NetworkingManagerComponents/Binary/BitReader.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,16 @@ public void SkipPadBits()
8989
/// <returns>Returns the boxed read object</returns>
9090
public object ReadObjectPacked(Type type)
9191
{
92+
if (type.IsNullable())
93+
{
94+
bool isNull = ReadBool();
95+
96+
if (isNull)
97+
{
98+
return null;
99+
}
100+
}
101+
92102
if (type == typeof(byte))
93103
return ReadByteDirect();
94104
if (type == typeof(sbyte))

MLAPI/NetworkingManagerComponents/Binary/BitWriter.cs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System;
77
using System.Diagnostics;
88
using System.IO;
9+
using MLAPI.Internal;
910
using UnityEngine;
1011

1112
namespace MLAPI.Serialization
@@ -45,11 +46,17 @@ public void SetStream(Stream stream)
4546
/// <param name="value">The object to write</param>
4647
public void WriteObjectPacked(object value)
4748
{
48-
if (value == null)
49+
if (value.IsNullable())
4950
{
50-
throw new NullReferenceException("BitWriter cannot write null values");
51+
WriteBool(value == null);
52+
53+
if (value == null)
54+
{
55+
return;
56+
}
5157
}
52-
else if (value is byte)
58+
59+
if (value is byte)
5360
{
5461
WriteByte((byte)value);
5562
return;

0 commit comments

Comments
 (0)