diff --git a/Assets/Mirror/Core/NetworkReader.cs b/Assets/Mirror/Core/NetworkReader.cs index af86d725d..4244fa69a 100644 --- a/Assets/Mirror/Core/NetworkReader.cs +++ b/Assets/Mirror/Core/NetworkReader.cs @@ -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 diff --git a/Assets/Mirror/Core/NetworkWriter.cs b/Assets/Mirror/Core/NetworkWriter.cs index 6249dbbea..2185d13ab 100644 --- a/Assets/Mirror/Core/NetworkWriter.cs +++ b/Assets/Mirror/Core/NetworkWriter.cs @@ -69,6 +69,11 @@ public byte[] ToArray() public ArraySegment ToArraySegment() => new ArraySegment(buffer, 0, Position); + // implicit conversion for convenience + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static implicit operator ArraySegment(NetworkWriter w) => + w.ToArraySegment(); + // WriteBlittable from DOTSNET. // this is extremely fast, but only works for blittable types. // diff --git a/Assets/Mirror/Tests/Editor/NetworkWriterTest.cs b/Assets/Mirror/Tests/Editor/NetworkWriterTest.cs index 32b27f64a..81d0da9c6 100644 --- a/Assets/Mirror/Tests/Editor/NetworkWriterTest.cs +++ b/Assets/Mirror/Tests/Editor/NetworkWriterTest.cs @@ -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 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.