using System;
using System.IO;
using System.Runtime.CompilerServices;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
namespace Mirror
{
/// Network Reader for most simple types like floats, ints, buffers, structs, etc. Use NetworkReaderPool.GetReader() to avoid allocations.
// 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.
public class NetworkReader
{
// internal buffer
// byte[] pointer would work, but we use ArraySegment to also support
// the ArraySegment constructor
ArraySegment buffer;
/// Next position to read from the buffer
// 'int' is the best type for .Position. 'short' is too small if we send >32kb which would result in negative .Position
// -> converting long to int is fine until 2GB of data (MAX_INT), so we don't have to worry about overflows here
public int Position;
/// Total number of bytes to read from buffer
public int Length
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => buffer.Count;
}
/// Remaining bytes that can be read, for convenience.
public int Remaining
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Length - Position;
}
public NetworkReader(byte[] bytes)
{
buffer = new ArraySegment(bytes);
}
public NetworkReader(ArraySegment segment)
{
buffer = segment;
}
// sometimes it's useful to point a reader on another buffer instead of
// allocating a new reader (e.g. NetworkReaderPool)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetBuffer(byte[] bytes)
{
buffer = new ArraySegment(bytes);
Position = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetBuffer(ArraySegment segment)
{
buffer = segment;
Position = 0;
}
// ReadBlittable from DOTSNET
// this is extremely fast, but only works for blittable types.
// => private to make sure nobody accidentally uses it for non-blittable
//
// Benchmark: see NetworkWriter.WriteBlittable!
//
// Note:
// ReadBlittable assumes same endianness for server & client.
// All Unity 2018+ platforms are little endian.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe T ReadBlittable()
where T : unmanaged
{
// check if blittable for safety
#if UNITY_EDITOR
if (!UnsafeUtility.IsBlittable(typeof(T)))
{
throw new ArgumentException($"{typeof(T)} is not blittable!");
}
#endif
// calculate size
// sizeof(T) gets the managed size at compile time.
// Marshal.SizeOf gets the unmanaged size at runtime (slow).
// => our 1mio writes benchmark is 6x slower with Marshal.SizeOf
// => for blittable types, sizeof(T) is even recommended:
// https://docs.microsoft.com/en-us/dotnet/standard/native-interop/best-practices
int size = sizeof(T);
// enough data to read?
if (Position + size > buffer.Count)
{
throw new EndOfStreamException($"ReadBlittable<{typeof(T)}> out of range: {ToString()}");
}
// read blittable
T value;
fixed (byte* ptr = &buffer.Array[buffer.Offset + Position])
{
#if UNITY_ANDROID
// on some android systems, reading *(T*)ptr throws a NRE if
// the ptr isn't aligned (i.e. if Position is 1,2,3,5, etc.).
// here we have to use memcpy.
//
// => we can't get a pointer of a struct in C# without
// marshalling allocations
// => instead, we stack allocate an array of type T and use that
// => stackalloc avoids GC and is very fast. it only works for
// value types, but all blittable types are anyway.
//
// this way, we can still support blittable reads on android.
// see also: https://github.com/vis2k/Mirror/issues/3044
// (solution discovered by AIIO, FakeByte, mischa)
T* valueBuffer = stackalloc T[1];
UnsafeUtility.MemCpy(valueBuffer, ptr, size);
value = valueBuffer[0];
#else
// cast buffer to a T* pointer and then read from it.
value = *(T*)ptr;
#endif
}
Position += size;
return value;
}
// blittable'?' template for code reuse
// note: bool isn't blittable. need to read as byte.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal T? ReadBlittableNullable()
where T : unmanaged =>
ReadByte() != 0 ? ReadBlittable() : default(T?);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public byte ReadByte() => ReadBlittable();
/// Read 'count' bytes into the bytes array
// NOTE: returns byte[] because all reader functions return something.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public byte[] ReadBytes(byte[] bytes, int count)
{
// check if passed byte array is big enough
if (count > bytes.Length)
{
throw new EndOfStreamException($"ReadBytes can't read {count} + bytes because the passed byte[] only has length {bytes.Length}");
}
// check if within buffer limits
if (Position + count > buffer.Count)
{
throw new EndOfStreamException($"ReadBytesSegment can't read {count} bytes because it would read past the end of the stream. {ToString()}");
}
Array.Copy(buffer.Array, buffer.Offset + Position, bytes, 0, count);
Position += count;
return bytes;
}
/// Read 'count' bytes allocation-free as ArraySegment that points to the internal array.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ArraySegment ReadBytesSegment(int count)
{
// check if within buffer limits
if (Position + count > buffer.Count)
{
throw new EndOfStreamException($"ReadBytesSegment can't read {count} bytes because it would read past the end of the stream. {ToString()}");
}
// return the segment
ArraySegment result = new ArraySegment(buffer.Array, buffer.Offset + Position, count);
Position += count;
return result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override string ToString() =>
$"NetworkReader pos={Position} len={Length} buffer={BitConverter.ToString(buffer.Array, buffer.Offset, buffer.Count)}";
/// Reads any data type that mirror supports. Uses weaver populated Reader(T).read
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Read()
{
Func readerDelegate = Reader.read;
if (readerDelegate == null)
{
Debug.LogError($"No reader found for {typeof(T)}. Use a type supported by Mirror or define a custom reader");
return default;
}
return readerDelegate(this);
}
}
/// Helper class that weaver populates with all reader types.
// Note that c# creates a different static variable for each type
// -> Weaver.ReaderWriterProcessor.InitializeReaderAndWriters() populates it
public static class Reader
{
public static Func read;
}
}