Skip to content

Commit

Permalink
feat: adding support for Span<T>
Browse files Browse the repository at this point in the history
  • Loading branch information
James-Frowen committed Mar 12, 2024
1 parent 68ba92c commit 3c48db8
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions Assets/Mirage/Runtime/Serialization/CollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public static void WriteArraySegment<T>(this NetworkWriter writer, ArraySegment<
}

[WeaverSerializeCollection]
public static void WriteGodotDictionary<TKey, TValue>(this NetworkWriter writer, Dictionary<TKey, TValue> dictionary)
public static void WriteDictionary<TKey, TValue>(this NetworkWriter writer, Dictionary<TKey, TValue> dictionary)
{
WriteCountPlusOne(writer, dictionary?.Count);

Expand All @@ -104,6 +104,17 @@ public static void WriteGodotDictionary<TKey, TValue>(this NetworkWriter writer,
}
}

[WeaverSerializeCollection]
public static void WriteSpan<T>(this NetworkWriter writer, Span<T> span) => WriteReadOnlySpan<T>(writer, span);
[WeaverSerializeCollection]
public static void WriteReadOnlySpan<T>(this NetworkWriter writer, ReadOnlySpan<T> span)
{
var length = span.Length;
writer.WritePackedUInt32(checked((uint)length));
for (var i = 0; i < length; i++)
writer.Write(span[i]);
}

/// <returns>array or null</returns>
public static byte[] ReadBytesAndSize(this NetworkReader reader)
{
Expand Down Expand Up @@ -174,7 +185,7 @@ public static ArraySegment<T> ReadArraySegment<T>(this NetworkReader reader)
}

[WeaverSerializeCollection]
public static Dictionary<TKey, TValue> ReadGodotDictionary<TKey, TValue>(this NetworkReader reader)
public static Dictionary<TKey, TValue> ReadDictionary<TKey, TValue>(this NetworkReader reader)
{
var hasValue = ReadCountPlusOne(reader, out var length);
if (!hasValue)
Expand All @@ -192,6 +203,23 @@ public static Dictionary<TKey, TValue> ReadGodotDictionary<TKey, TValue>(this Ne
return result;
}

[WeaverSerializeCollection]
public static Span<T> ReadSpan<T>(this NetworkReader reader)
{
var length = checked((int)reader.ReadPackedUInt32());
ValidateSize(reader, length);

var result = new T[length]; // todo remove allocation
for (var i = 0; i < length; i++)
{
result[i] = reader.Read<T>();
}
return result;
}
[WeaverSerializeCollection]
public static ReadOnlySpan<T> ReadReadOnlySpan<T>(this NetworkReader reader) => ReadSpan<T>(reader);


/// <summary>Writes null as 0, and all over values as +1</summary>
/// <param name="count">The real count or null if collection is is null</param>
internal static void WriteCountPlusOne(NetworkWriter writer, int? count)
Expand Down

0 comments on commit 3c48db8

Please sign in to comment.