public static ArraySegment <byte> ReadBytesAndSizeSegment(this NetworkReader reader) { // count = 0 means the array was null // otherwise count - 1 is the length of the array uint count = reader.ReadUInt(); // Use checked() to force it to throw OverflowException if data is invalid return(count == 0 ? default : reader.ReadBytesSegment(checked ((int)(count - 1u)))); }
public void TestWritingBytesSegment() { byte[] data = { 1, 2, 3 }; NetworkWriter writer = new NetworkWriter(); writer.WriteBytes(data, 0, data.Length); NetworkReader reader = new NetworkReader(writer.ToArray()); ArraySegment<byte> deserialized = reader.ReadBytesSegment(data.Length); Assert.That(deserialized.Count, Is.EqualTo(data.Length)); for (int i = 0; i < data.Length; ++i) Assert.That(deserialized.Array[deserialized.Offset + i], Is.EqualTo(data[i])); }
public static string ReadString(this NetworkReader reader) { // read number of bytes ushort size = reader.ReadUShort(); // null support, see NetworkWriter if (size == 0) { return(null); } int realSize = size - 1; // make sure it's within limits to avoid allocation attacks etc. if (realSize >= NetworkWriter.MaxStringLength) { throw new EndOfStreamException($"ReadString too long: {realSize}. Limit is: {NetworkWriter.MaxStringLength}"); } ArraySegment <byte> data = reader.ReadBytesSegment(realSize); // convert directly from buffer to string via encoding return(encoding.GetString(data.Array, data.Offset, data.Count)); }