Skip to content

Commit

Permalink
perf: return the contents of the writer as an array segment (#916)
Browse files Browse the repository at this point in the history
* Return the contents of the writer as an array segment

* Use a safer ToArraySegment method and add some comments

* refactor: for readability and debuggability

* Test that ToArraySegment works

* Updated with master

* Update NetworkWriter.cs
  • Loading branch information
paulpach authored and miwarnec committed Jun 23, 2019
1 parent 7b3e82a commit ced3690
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Assets/Mirror/Runtime/NetworkWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,21 @@ public byte[] ToArray()
return stream.ToArray();
}

// Gets the serialized data in an ArraySegment<byte>
// this is similar to ToArray(), but it gets the data in O(1)
// and without allocations.
// Do not write anything else or modify the NetworkWriter
// while you are using the ArraySegment
public ArraySegment<byte> ToArraySegment()
{
stream.Flush();
if (stream.TryGetBuffer(out ArraySegment<byte> data))
{
return data;
}
throw new Exception("Cannot expose contents of memory stream. Make sure that MemoryStream buffer is publicly visible (see MemoryStream source code).");
}

// reset both the position and length of the stream, but leaves the capacity the same
// so that we can reuse this writer without extra allocations
public void SetLength(long value)
Expand Down
12 changes: 12 additions & 0 deletions Assets/Mirror/Tests/NetworkWriterTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,18 @@ public void TestToArray()
Assert.That(writer.ToArray().Length, Is.EqualTo(2));
}

[Test]
public void TestToArraySegment()
{
NetworkWriter writer = new NetworkWriter();
writer.Write("hello");
writer.Write("world");

NetworkReader reader = new NetworkReader(writer.ToArraySegment());
Assert.That(reader.ReadString(), Is.EqualTo("hello"));
Assert.That(reader.ReadString(), Is.EqualTo("world"));
}

[Test]
public void TestChar()
{
Expand Down

0 comments on commit ced3690

Please sign in to comment.