feature: NetworkWriter implicit ArraySegment conversion for convenience.

also allows for implicit NetworkWriter to NetworkReader conversion.
This commit is contained in:
vis2k 2022-09-27 11:53:04 +07:00
parent a84bf0769e
commit 136b8d9956
3 changed files with 20 additions and 0 deletions

View File

@ -11,6 +11,10 @@ namespace Mirror
// Note: This class is intended to be extremely pedantic,
// and throw exceptions whenever stuff is going slightly wrong.
// The exceptions will be handled in NetworkServer/NetworkClient.
//
// Note that NetworkWriter can be passed in constructor thanks to implicit
// ArraySegment conversion:
// NetworkReader reader = new NetworkReader(writer);
public class NetworkReader
{
// internal buffer

View File

@ -69,6 +69,11 @@ public byte[] ToArray()
public ArraySegment<byte> ToArraySegment() =>
new ArraySegment<byte>(buffer, 0, Position);
// implicit conversion for convenience
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator ArraySegment<byte>(NetworkWriter w) =>
w.ToArraySegment();
// WriteBlittable<T> from DOTSNET.
// this is extremely fast, but only works for blittable types.
//

View File

@ -57,6 +57,17 @@ public void ToStringTest()
Assert.That(writer.ToString(), Is.EqualTo($"[DD-CC-BB-AA-FF @ 5/{NetworkWriter.DefaultCapacity}]"));
}
[Test]
public void SegmentImplicit()
{
NetworkWriter writer = new NetworkWriter();
writer.WriteUInt(0xAABBCCDD);
writer.WriteByte(0xFF);
ArraySegment<byte> segment = writer;
Assert.That(segment.SequenceEqual(new byte[] {0xDD, 0xCC, 0xBB, 0xAA, 0xFF}));
}
// some platforms may not support unaligned *(T*) reads/writes.
// but it still needs to work with our workaround.
// let's have an editor test to maybe catch it early.