1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
| public class NetworkWriter { public const ushort MaxStringLength = ushort.MaxValue - 1;
public const int DefaultCapacity = 1500; private byte[] buffer = new byte[DefaultCapacity];
public int Position;
public int Capacity => buffer.Length;
private readonly UTF8Encoding encoding = new UTF8Encoding(false, true);
[MethodImpl(MethodImplOptions.AggressiveInlining)] public void Reset() { Position = 0; }
[MethodImpl(MethodImplOptions.AggressiveInlining)] private void EnsureCapacity(int value) { if(buffer.Length < value) { int capacity = Mathf.Max(value, buffer.Length * 2); Array.Resize(ref buffer, capacity); } }
[MethodImpl(MethodImplOptions.AggressiveInlining)] public byte[] ToArray() { byte[] data = new byte[Position]; Array.ConstrainedCopy(buffer, 0, data, 0, Position); return data; }
[MethodImpl(MethodImplOptions.AggressiveInlining)] public ArraySegment<byte> ToArraySegment() => new ArraySegment<byte>(buffer, 0, Position);
[MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator ArraySegment<byte>(NetworkWriter w) => w.ToArraySegment();
internal unsafe void WriteBlittable<T>(T value) where T : unmanaged { #if UNITY_EDITOR if (!UnsafeUtility.IsBlittable(typeof(T))) { Debug.LogError($"{typeof(T)} is not blittable!"); return; } #endif int size = sizeof(T);
EnsureCapacity(Position + size);
fixed(byte* ptr = &buffer[Position]) { #if UNITY_ANDROID T* valueBuffer = stackalloc T[1]{value}; UnsafeUtility.MemCpy(ptr, valueBuffer, size); #else *(T*)ptr = value; #endif } Position += size; }
[MethodImpl(MethodImplOptions.AggressiveInlining)] internal void WriteBlittableNullable<T>(T? value) where T : unmanaged { WriteByte((byte)(value.HasValue ? 0x01 : 0x00)); if (value.HasValue) WriteBlittable(value.Value); }
public void WriteByte(byte value) => WriteBlittable(value);
public void WriteBytes(byte[] array, int offset, int count) { EnsureCapacity(Position + count); Array.ConstrainedCopy(array, offset, this.buffer, Position, count); Position += count; }
public unsafe bool WriteBytes(byte* ptr, int offset, int size) { EnsureCapacity(Position + size);
fixed(byte* destination = &buffer[Position]) { UnsafeUtility.MemCpy(destination, ptr + offset, size); }
Position += size; return true; }
public override string ToString() { return base.ToString(); }
}
|