forked from Unity-Technologies/com.unity.netcode.gameobjects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkReader.cs
More file actions
1667 lines (1521 loc) · 75.9 KB
/
NetworkReader.cs
File metadata and controls
1667 lines (1521 loc) · 75.9 KB
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define ARRAY_WRITE_PERMISSIVE // Allow attempt to write "packed" byte array (calls WriteByteArray())
#define ARRAY_RESOLVE_IMPLICIT // Include WriteArray() method with automatic type resolution
#define ARRAY_WRITE_PREMAP // Create a prefixed array diff mapping
#define ARRAY_DIFF_ALLOW_RESIZE // Whether or not to permit writing diffs of differently sized arrays
using System;
using System.IO;
using System.Text;
using MLAPI.Reflection;
using MLAPI.Logging;
using MLAPI.Spawning;
using UnityEngine;
namespace MLAPI.Serialization
{
/// <summary>
/// A BinaryReader that can do bit wise manipulation when backed by a NetworkBuffer
/// </summary>
public class NetworkReader
{
private Stream m_Source;
private NetworkBuffer m_NetworkSource;
/// <summary>
/// Creates a new NetworkReader backed by a given stream
/// </summary>
/// <param name="stream">The stream to read from</param>
public NetworkReader(Stream stream)
{
m_Source = stream;
m_NetworkSource = stream as NetworkBuffer;
}
/// <summary>
/// Changes the underlying stream the reader is reading from
/// </summary>
/// <param name="stream">The stream to read from</param>
public void SetStream(Stream stream)
{
m_Source = stream;
m_NetworkSource = stream as NetworkBuffer;
}
/// <summary>
/// Reads a single byte
/// </summary>
/// <returns>The byte read as an integer</returns>
public int ReadByte() => m_Source.ReadByte();
/// <summary>
/// Reads a byte
/// </summary>
/// <returns>The byte read</returns>
public byte ReadByteDirect() => (byte)m_Source.ReadByte();
/// <summary>
/// Reads a single bit
/// </summary>
/// <returns>The bit read</returns>
public bool ReadBit()
{
if (m_NetworkSource == null)
{
throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream");
}
return m_NetworkSource.ReadBit();
}
/// <summary>
/// Reads a single bit
/// </summary>
/// <returns>The bit read</returns>
public bool ReadBool()
{
if (m_NetworkSource == null)
{
return m_Source.ReadByte() != 0;
}
// return ReadBit(); // old (buggy)
return ReadByte() != 0; // new (hotfix)
}
/// <summary>
/// Skips pad bits and aligns the position to the next byte
/// </summary>
public void SkipPadBits()
{
if (m_NetworkSource == null)
{
throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream");
}
while (!m_NetworkSource.BitAligned) ReadBit();
}
/// <summary>
/// Reads a single boxed object of a given type in a packed format
/// </summary>
/// <param name="type">The type to read</param>
/// <returns>Returns the boxed read object</returns>
public object ReadObjectPacked(Type type)
{
if (type.IsNullable())
{
bool isNull = ReadBool();
if (isNull)
{
return null;
}
}
if (SerializationManager.TryDeserialize(m_Source, type, out object obj)) return obj;
if (type.IsArray && type.HasElementType)
{
int size = ReadInt32Packed();
Array array = Array.CreateInstance(type.GetElementType(), size);
for (int i = 0; i < size; i++)
{
array.SetValue(ReadObjectPacked(type.GetElementType()), i);
}
return array;
}
if (type == typeof(byte)) return ReadByteDirect();
if (type == typeof(sbyte)) return ReadSByte();
if (type == typeof(ushort)) return ReadUInt16Packed();
if (type == typeof(short)) return ReadInt16Packed();
if (type == typeof(int)) return ReadInt32Packed();
if (type == typeof(uint)) return ReadUInt32Packed();
if (type == typeof(long)) return ReadInt64Packed();
if (type == typeof(ulong)) return ReadUInt64Packed();
if (type == typeof(float)) return ReadSinglePacked();
if (type == typeof(double)) return ReadDoublePacked();
if (type == typeof(string)) return ReadStringPacked();
if (type == typeof(bool)) return ReadBool();
if (type == typeof(Vector2)) return ReadVector2Packed();
if (type == typeof(Vector3)) return ReadVector3Packed();
if (type == typeof(Vector4)) return ReadVector4Packed();
if (type == typeof(Color)) return ReadColorPacked();
if (type == typeof(Color32)) return ReadColor32();
if (type == typeof(Ray)) return ReadRayPacked();
if (type == typeof(Quaternion)) return ReadRotationPacked();
if (type == typeof(char)) return ReadCharPacked();
if (type.IsEnum) return ReadInt32Packed();
if (type == typeof(GameObject))
{
ulong networkObjectId = ReadUInt64Packed();
if (NetworkSpawnManager.SpawnedObjects.ContainsKey(networkObjectId))
{
return NetworkSpawnManager.SpawnedObjects[networkObjectId].gameObject;
}
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{
NetworkLog.LogWarning($"{nameof(NetworkReader)} cannot find the {nameof(GameObject)} sent in the {nameof(NetworkSpawnManager.SpawnedObjects)} list, it may have been destroyed. {nameof(networkObjectId)}: {networkObjectId}");
}
return null;
}
if (type == typeof(NetworkObject))
{
ulong networkObjectId = ReadUInt64Packed();
if (NetworkSpawnManager.SpawnedObjects.ContainsKey(networkObjectId))
{
return NetworkSpawnManager.SpawnedObjects[networkObjectId];
}
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{
NetworkLog.LogWarning($"{nameof(NetworkReader)} cannot find the {nameof(NetworkObject)} sent in the {nameof(NetworkSpawnManager.SpawnedObjects)} list, it may have been destroyed. {nameof(networkObjectId)}: {networkObjectId}");
}
return null;
}
if (typeof(NetworkBehaviour).IsAssignableFrom(type))
{
ulong networkObjectId = ReadUInt64Packed();
ushort behaviourId = ReadUInt16Packed();
if (NetworkSpawnManager.SpawnedObjects.ContainsKey(networkObjectId))
{
return NetworkSpawnManager.SpawnedObjects[networkObjectId].GetNetworkBehaviourAtOrderIndex(behaviourId);
}
if (NetworkLog.CurrentLogLevel <= LogLevel.Normal)
{
NetworkLog.LogWarning($"{nameof(NetworkReader)} cannot find the {nameof(NetworkBehaviour)} sent in the {nameof(NetworkSpawnManager.SpawnedObjects)} list, it may have been destroyed. {nameof(networkObjectId)}: {networkObjectId}");
}
return null;
}
if (typeof(INetworkSerializable).IsAssignableFrom(type))
{
object instance = Activator.CreateInstance(type);
((INetworkSerializable)instance).NetworkSerialize(new NetworkSerializer(this));
return instance;
}
Type nullableUnderlyingType = Nullable.GetUnderlyingType(type);
if (nullableUnderlyingType != null && SerializationManager.IsTypeSupported(nullableUnderlyingType))
{
return ReadObjectPacked(nullableUnderlyingType);
}
throw new ArgumentException($"{nameof(NetworkReader)} cannot read type {type.Name}");
}
/// <summary>
/// Read a single-precision floating point value from the stream.
/// </summary>
/// <returns>The read value</returns>
public float ReadSingle() => new UIntFloat { UIntValue = ReadUInt32() }.FloatValue;
/// <summary>
/// Read a double-precision floating point value from the stream.
/// </summary>
/// <returns>The read value</returns>
public double ReadDouble() => new UIntFloat { ULongValue = ReadUInt64() }.DoubleValue;
/// <summary>
/// Read a single-precision floating point value from the stream from a varint
/// </summary>
/// <returns>The read value</returns>
public float ReadSinglePacked() => new UIntFloat { UIntValue = ReadUInt32Packed() }.FloatValue;
/// <summary>
/// Read a double-precision floating point value from the stream as a varint
/// </summary>
/// <returns>The read value</returns>
public double ReadDoublePacked() => new UIntFloat { ULongValue = ReadUInt64Packed() }.DoubleValue;
/// <summary>
/// Read a Vector2 from the stream.
/// </summary>
/// <returns>The Vector2 read from the stream.</returns>
public Vector2 ReadVector2() => new Vector2(ReadSingle(), ReadSingle());
/// <summary>
/// Read a Vector2 from the stream.
/// </summary>
/// <returns>The Vector2 read from the stream.</returns>
public Vector2 ReadVector2Packed() => new Vector2(ReadSinglePacked(), ReadSinglePacked());
/// <summary>
/// Read a Vector3 from the stream.
/// </summary>
/// <returns>The Vector3 read from the stream.</returns>
public Vector3 ReadVector3() => new Vector3(ReadSingle(), ReadSingle(), ReadSingle());
/// <summary>
/// Read a Vector3 from the stream.
/// </summary>
/// <returns>The Vector3 read from the stream.</returns>
public Vector3 ReadVector3Packed() => new Vector3(ReadSinglePacked(), ReadSinglePacked(), ReadSinglePacked());
/// <summary>
/// Read a Vector4 from the stream.
/// </summary>
/// <returns>The Vector4 read from the stream.</returns>
public Vector4 ReadVector4() => new Vector4(ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle());
/// <summary>
/// Read a Vector4 from the stream.
/// </summary>
/// <returns>The Vector4 read from the stream.</returns>
public Vector4 ReadVector4Packed() => new Vector4(ReadSinglePacked(), ReadSinglePacked(), ReadSinglePacked(), ReadSinglePacked());
/// <summary>
/// Read a Color from the stream.
/// </summary>
/// <returns>The Color read from the stream.</returns>
public Color ReadColor() => new Color(ReadSingle(), ReadSingle(), ReadSingle(), ReadSingle());
/// <summary>
/// Read a Color from the stream.
/// </summary>
/// <returns>The Color read from the stream.</returns>
public Color ReadColorPacked() => new Color(ReadSinglePacked(), ReadSinglePacked(), ReadSinglePacked(), ReadSinglePacked());
/// <summary>
/// Read a Color32 from the stream.
/// </summary>
/// <returns>The Color32 read from the stream.</returns>
public Color32 ReadColor32() => new Color32((byte)ReadByte(), (byte)ReadByte(), (byte)ReadByte(), (byte)ReadByte());
/// <summary>
/// Read a Ray from the stream.
/// </summary>
/// <returns>The Ray read from the stream.</returns>
public Ray ReadRay() => new Ray(ReadVector3(), ReadVector3());
/// <summary>
/// Read a Ray from the stream.
/// </summary>
/// <returns>The Ray read from the stream.</returns>
public Ray ReadRayPacked() => new Ray(ReadVector3Packed(), ReadVector3Packed());
/// <summary>
/// Read a Ray2D from the stream.
/// </summary>
/// <returns>The Ray2D read from the stream.</returns>
public Ray2D ReadRay2D() => new Ray2D(ReadVector2(), ReadVector2());
/// <summary>
/// Read a Ray2D from the stream.
/// </summary>
/// <returns>The Ray2D read from the stream.</returns>
public Ray2D ReadRay2DPacked() => new Ray2D(ReadVector2Packed(), ReadVector2Packed());
/// <summary>
/// Read a single-precision floating point value from the stream. The value is between (inclusive) the minValue and maxValue.
/// </summary>
/// <param name="minValue">Minimum value that this value could be</param>
/// <param name="maxValue">Maximum possible value that this could be</param>
/// <param name="bytes">How many bytes the compressed value occupies. Must be between 1 and 4 (inclusive)</param>
/// <returns>The read value</returns>
public float ReadRangedSingle(float minValue, float maxValue, int bytes)
{
if (bytes < 1 || bytes > 4) throw new ArgumentOutOfRangeException("Result must occupy between 1 and 4 bytes!");
uint read = 0;
for (int i = 0; i < bytes; ++i) read |= (uint)ReadByte() << (i << 3);
return (((float)read / ((0x100 * bytes) - 1)) * (minValue + maxValue)) - minValue;
}
/// <summary>
/// read a double-precision floating point value from the stream. The value is between (inclusive) the minValue and maxValue.
/// </summary>
/// <param name="minValue">Minimum value that this value could be</param>
/// <param name="maxValue">Maximum possible value that this could be</param>
/// <param name="bytes">How many bytes the compressed value occupies. Must be between 1 and 8 (inclusive)</param>
/// <returns>The read value</returns>
public double ReadRangedDouble(double minValue, double maxValue, int bytes)
{
if (bytes < 1 || bytes > 8) throw new ArgumentOutOfRangeException("Result must occupy between 1 and 8 bytes!");
ulong read = 0;
for (int i = 0; i < bytes; ++i) read |= (ulong)ReadByte() << (i << 3);
return (((double)read / ((0x100 * bytes) - 1)) * (minValue + maxValue)) - minValue;
}
/// <summary>
/// Reads the rotation from the stream
/// </summary>
/// <returns>The rotation read from the stream</returns>
public Quaternion ReadRotationPacked()
{
float x = ReadSinglePacked();
float y = ReadSinglePacked();
float z = ReadSinglePacked();
// numerical precision issues can make the remainder very slightly negative.
// In this case, use 0 for w as, otherwise, w would be NaN.
float remainder = 1f - Mathf.Pow(x, 2) - Mathf.Pow(y, 2) - Mathf.Pow(z, 2);
float w = (remainder > 0f) ? Mathf.Sqrt(remainder) : 0.0f;
return new Quaternion(x, y, z, w);
}
/// <summary>
/// Reads the rotation from the stream
/// </summary>
/// <returns>The rotation read from the stream</returns>
public Quaternion ReadRotation()
{
float x = ReadSingle();
float y = ReadSingle();
float z = ReadSingle();
float w = ReadSingle();
return new Quaternion(x, y, z, w);
}
/// <summary>
/// Read a certain amount of bits from the stream.
/// </summary>
/// <param name="bitCount">How many bits to read. Minimum 0, maximum 8.</param>
/// <returns>The bits that were read</returns>
public ulong ReadBits(int bitCount)
{
if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream");
if (bitCount > 64) throw new ArgumentOutOfRangeException(nameof(bitCount), "Cannot read more than 64 bits into a 64-bit value!");
if (bitCount < 0) throw new ArgumentOutOfRangeException(nameof(bitCount), "Cannot read fewer than 0 bits!");
ulong read = 0;
for (int i = 0; i + 8 < bitCount; i += 8) read |= (ulong)ReadByte() << i;
read |= (ulong)ReadByteBits(bitCount & 7) << (bitCount & ~7);
return read;
}
/// <summary>
/// Read a certain amount of bits from the stream.
/// </summary>
/// <param name="bitCount">How many bits to read. Minimum 0, maximum 64.</param>
/// <returns>The bits that were read</returns>
public byte ReadByteBits(int bitCount)
{
if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream");
if (bitCount > 8) throw new ArgumentOutOfRangeException(nameof(bitCount), "Cannot read more than 8 bits into an 8-bit value!");
if (bitCount < 0) throw new ArgumentOutOfRangeException(nameof(bitCount), "Cannot read fewer than 0 bits!");
int result = 0;
ByteBool convert = new ByteBool();
for (int i = 0; i < bitCount; ++i) result |= convert.Collapse(ReadBit()) << i;
return (byte)result;
}
/// <summary>
/// Read a nibble (4 bits) from the stream.
/// </summary>
/// <param name="asUpper">Whether or not the nibble should be left-shifted by 4 bits</param>
/// <returns>The nibble that was read</returns>
public byte ReadNibble(bool asUpper)
{
if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream");
ByteBool convert = new ByteBool();
byte result = (byte)
(
convert.Collapse(ReadBit()) |
(convert.Collapse(ReadBit()) << 1) |
(convert.Collapse(ReadBit()) << 2) |
(convert.Collapse(ReadBit()) << 3)
);
if (asUpper) result <<= 4;
return result;
}
// Marginally faster than the one that accepts a bool
/// <summary>
/// Read a nibble (4 bits) from the stream.
/// </summary>
/// <returns>The nibble that was read</returns>
public byte ReadNibble()
{
if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream");
ByteBool convert = new ByteBool();
return (byte)
(
convert.Collapse(ReadBit()) |
(convert.Collapse(ReadBit()) << 1) |
(convert.Collapse(ReadBit()) << 2) |
(convert.Collapse(ReadBit()) << 3)
);
}
/// <summary>
/// Reads a signed byte
/// </summary>
/// <returns>Value read from stream.</returns>
public sbyte ReadSByte() => (sbyte)ReadByte();
/// <summary>
/// Read an unsigned short (UInt16) from the stream.
/// </summary>
/// <returns>Value read from stream.</returns>
public ushort ReadUInt16() => (ushort)(ReadByte() | (ReadByte() << 8));
/// <summary>
/// Read a signed short (Int16) from the stream.
/// </summary>
/// <returns>Value read from stream.</returns>
public short ReadInt16() => (short)ReadUInt16();
/// <summary>
/// Read a single character from the stream
/// </summary>
/// <returns>Value read from stream.</returns>
public char ReadChar() => (char)ReadUInt16();
/// <summary>
/// Read an unsigned int (UInt32) from the stream.
/// </summary>
/// <returns>Value read from stream.</returns>
public uint ReadUInt32() => (uint)(ReadByte() | (ReadByte() << 8) | (ReadByte() << 16) | (ReadByte() << 24));
/// <summary>
/// Read a signed int (Int32) from the stream.
/// </summary>
/// <returns>Value read from stream.</returns>
public int ReadInt32() => (int)ReadUInt32();
/// <summary>
/// Read an unsigned long (UInt64) from the stream.
/// </summary>
/// <returns>Value read from stream.</returns>
public ulong ReadUInt64() =>
(
((uint)ReadByte()) |
((ulong)ReadByte() << 8) |
((ulong)ReadByte() << 16) |
((ulong)ReadByte() << 24) |
((ulong)ReadByte() << 32) |
((ulong)ReadByte() << 40) |
((ulong)ReadByte() << 48) |
((ulong)ReadByte() << 56)
);
/// <summary>
/// Read a signed long (Int64) from the stream.
/// </summary>
/// <returns>Value read from stream.</returns>
public long ReadInt64() => (long)ReadUInt64();
/// <summary>
/// Read a ZigZag encoded varint signed short (Int16) from the stream.
/// </summary>
/// <returns>Decoded un-varinted value.</returns>
public short ReadInt16Packed() => (short)Arithmetic.ZigZagDecode(ReadUInt64Packed());
/// <summary>
/// Read a varint unsigned short (UInt16) from the stream.
/// </summary>
/// <returns>Un-varinted value.</returns>
public ushort ReadUInt16Packed() => (ushort)ReadUInt64Packed();
/// <summary>
/// Read a varint two-byte character from the stream.
/// </summary>
/// <returns>Un-varinted value.</returns>
public char ReadCharPacked() => (char)ReadUInt16Packed();
/// <summary>
/// Read a ZigZag encoded varint signed int (Int32) from the stream.
/// </summary>
/// <returns>Decoded un-varinted value.</returns>
public int ReadInt32Packed() => (int)Arithmetic.ZigZagDecode(ReadUInt64Packed());
/// <summary>
/// Read a varint unsigned int (UInt32) from the stream.
/// </summary>
/// <returns>Un-varinted value.</returns>
public uint ReadUInt32Packed() => (uint)ReadUInt64Packed();
/// <summary>
/// Read a ZigZag encoded varint signed long(Int64) from the stream.
/// </summary>
/// <returns>Decoded un-varinted value.</returns>
public long ReadInt64Packed() => Arithmetic.ZigZagDecode(ReadUInt64Packed());
/// <summary>
/// Read a varint unsigned long (UInt64) from the stream.
/// </summary>
/// <returns>Un-varinted value.</returns>
public ulong ReadUInt64Packed()
{
ulong header = ReadByteDirect();
if (header <= 240) return header;
if (header <= 248) return 240 + ((header - 241) << 8) + ReadByteDirect();
if (header == 249) return 2288UL + (ulong)(ReadByte() << 8) + ReadByteDirect();
ulong res = ReadByteDirect() | ((ulong)ReadByteDirect() << 8) | ((ulong)ReadByte() << 16);
int cmp = 2;
int hdr = (int)(header - 247);
while (hdr > ++cmp) res |= (ulong)ReadByte() << (cmp << 3);
return res;
}
// Read arrays
/// <summary>
/// Read a string from the stream.
/// </summary>
/// <returns>The string that was read.</returns>
/// <param name="oneByteChars">If set to <c>true</c> one byte chars are used and only ASCII is supported.</param>
public StringBuilder ReadString(bool oneByteChars) => ReadString(null, oneByteChars);
/// <summary>
/// Read a string from the stream.
/// </summary>
/// <returns>The string that was read.</returns>
/// <param name="builder">The builder to read the values into or null to use a new builder.</param>
/// <param name="oneByteChars">If set to <c>true</c> one byte chars are used and only ASCII is supported.</param>
public StringBuilder ReadString(StringBuilder builder = null, bool oneByteChars = false)
{
int expectedLength = (int)ReadUInt32Packed();
if (builder == null) builder = new StringBuilder(expectedLength);
else if (builder.Capacity + builder.Length < expectedLength) builder.Capacity = expectedLength + builder.Length;
for (int i = 0; i < expectedLength; ++i) builder.Insert(i, oneByteChars ? (char)ReadByte() : ReadChar());
return builder;
}
/// <summary>
/// Read string encoded as a varint from the stream.
/// </summary>
/// <returns>The string that was read.</returns>
/// <param name="builder">The builder to read the string into or null to use a new builder</param>
public string ReadStringPacked(StringBuilder builder = null)
{
int expectedLength = (int)ReadUInt32Packed();
if (builder == null) builder = new StringBuilder(expectedLength);
else if (builder.Capacity + builder.Length < expectedLength) builder.Capacity = expectedLength + builder.Length;
for (int i = 0; i < expectedLength; ++i) builder.Insert(i, ReadCharPacked());
return builder.ToString();
}
/// <summary>
/// Read string diff from the stream.
/// </summary>
/// <returns>The string based on the diff and the old version.</returns>
/// <param name="compare">The version to compare the diff to.</param>
/// <param name="oneByteChars">If set to <c>true</c> one byte chars are used and only ASCII is supported.</param>
public StringBuilder ReadStringDiff(string compare, bool oneByteChars = false) => ReadStringDiff(null, compare, oneByteChars);
/// <summary>
/// Read string diff from the stream.
/// </summary>
/// <returns>The string based on the diff and the old version</returns>
/// <param name="builder">The builder to read the string into or null to use a new builder.</param>
/// <param name="compare">The version to compare the diff to.</param>
/// <param name="oneByteChars">If set to <c>true</c> one byte chars are used and only ASCII is supported.</param>
public StringBuilder ReadStringDiff(StringBuilder builder, string compare, bool oneByteChars = false)
{
if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream");
int expectedLength = (int)ReadUInt32Packed();
if (builder == null) builder = new StringBuilder(expectedLength);
else if (builder.Capacity < expectedLength) builder.Capacity = expectedLength;
ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(compare == null ? 0 : Math.Min(expectedLength, compare.Length));
ulong mapStart;
int compareLength = compare?.Length ?? 0;
for (int i = 0; i < expectedLength; ++i)
{
if (i >= compareLength || ReadBit())
{
#if ARRAY_WRITE_PREMAP
// Move to data section
mapStart = m_NetworkSource.BitPosition;
m_NetworkSource.BitPosition = dBlockStart;
#endif
// Read datum
builder.Insert(i, oneByteChars ? (char)ReadByte() : ReadChar());
#if ARRAY_WRITE_PREMAP
dBlockStart = m_NetworkSource.BitPosition;
// Return to mapping section
m_NetworkSource.BitPosition = mapStart;
#endif
}
else if (i < compareLength) builder.Insert(i, compare[i]);
}
m_NetworkSource.BitPosition = dBlockStart;
return builder;
}
/// <summary>
/// Read string diff from the stream.
/// </summary>
/// <returns>The string based on the diff and the old version.</returns>
/// <param name="compareAndBuffer">The builder containing the current version and that will also be used as the output buffer.</param>
/// <param name="oneByteChars">If set to <c>true</c> one byte chars will be used and only ASCII will be supported.</param>
public StringBuilder ReadStringDiff(StringBuilder compareAndBuffer, bool oneByteChars = false)
{
if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream");
int expectedLength = (int)ReadUInt32Packed();
if (compareAndBuffer == null) throw new ArgumentNullException(nameof(compareAndBuffer), "Buffer cannot be null");
if (compareAndBuffer.Capacity < expectedLength) compareAndBuffer.Capacity = expectedLength;
ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)Math.Min(expectedLength, compareAndBuffer.Length);
ulong mapStart;
for (int i = 0; i < expectedLength; ++i)
{
if (i >= compareAndBuffer.Length || ReadBit())
{
#if ARRAY_WRITE_PREMAP
// Move to data section
mapStart = m_NetworkSource.BitPosition;
m_NetworkSource.BitPosition = dBlockStart;
#endif
// Read datum
compareAndBuffer.Remove(i, 1);
compareAndBuffer.Insert(i, oneByteChars ? (char)ReadByte() : ReadChar());
#if ARRAY_WRITE_PREMAP
dBlockStart = m_NetworkSource.BitPosition;
// Return to mapping section
m_NetworkSource.BitPosition = mapStart;
#endif
}
}
m_NetworkSource.BitPosition = dBlockStart;
return compareAndBuffer;
}
/// <summary>
/// Read string diff encoded as varints from the stream.
/// </summary>
/// <returns>The string based on the diff and the old version.</returns>
/// <param name="compare">The version to compare the diff to.</param>
public StringBuilder ReadStringPackedDiff(string compare) => ReadStringPackedDiff(null, compare);
/// <summary>
/// Read string diff encoded as varints from the stream.
/// </summary>
/// <returns>The string based on the diff and the old version</returns>
/// <param name="builder">The builder to read the string into or null to use a new builder.</param>
/// <param name="compare">The version to compare the diff to.</param>
public StringBuilder ReadStringPackedDiff(StringBuilder builder, string compare)
{
if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream");
int expectedLength = (int)ReadUInt32Packed();
if (builder == null) builder = new StringBuilder(expectedLength);
else if (builder.Capacity < expectedLength) builder.Capacity = expectedLength;
ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(compare == null ? 0 : Math.Min(expectedLength, compare.Length));
ulong mapStart;
int compareLength = compare?.Length ?? 0;
for (int i = 0; i < expectedLength; ++i)
{
if (i >= compareLength || ReadBit())
{
#if ARRAY_WRITE_PREMAP
// Move to data section
mapStart = m_NetworkSource.BitPosition;
m_NetworkSource.BitPosition = dBlockStart;
#endif
// Read datum
builder.Insert(i, ReadCharPacked());
#if ARRAY_WRITE_PREMAP
dBlockStart = m_NetworkSource.BitPosition;
// Return to mapping section
m_NetworkSource.BitPosition = mapStart;
#endif
}
else if (i < compareLength) builder.Insert(i, compare[i]);
}
m_NetworkSource.BitPosition = dBlockStart;
return builder;
}
/// <summary>
/// Read string diff encoded as varints from the stream.
/// </summary>
/// <returns>The string based on the diff and the old version.</returns>
/// <param name="compareAndBuffer">The builder containing the current version and that will also be used as the output buffer.</param>
public StringBuilder ReadStringPackedDiff(StringBuilder compareAndBuffer)
{
if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream");
int expectedLength = (int)ReadUInt32Packed();
if (compareAndBuffer == null) throw new ArgumentNullException(nameof(compareAndBuffer), "Buffer cannot be null");
if (compareAndBuffer.Capacity < expectedLength) compareAndBuffer.Capacity = expectedLength;
ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)Math.Min(expectedLength, compareAndBuffer.Length);
ulong mapStart;
for (int i = 0; i < expectedLength; ++i)
{
if (i >= compareAndBuffer.Length || ReadBit())
{
#if ARRAY_WRITE_PREMAP
// Move to data section
mapStart = m_NetworkSource.BitPosition;
m_NetworkSource.BitPosition = dBlockStart;
#endif
// Read datum
compareAndBuffer.Remove(i, 1);
compareAndBuffer.Insert(i, ReadCharPacked());
#if ARRAY_WRITE_PREMAP
dBlockStart = m_NetworkSource.BitPosition;
// Return to mapping section
m_NetworkSource.BitPosition = mapStart;
#endif
}
}
m_NetworkSource.BitPosition = dBlockStart;
return compareAndBuffer;
}
/// <summary>
/// Read byte array into an optional buffer from the stream.
/// </summary>
/// <returns>The byte array that has been read.</returns>
/// <param name="readTo">The array to read into. If the array is not large enough or if it's null. A new array is created.</param>
/// <param name="knownLength">The length of the array if it's known. Otherwise -1</param>
public byte[] ReadByteArray(byte[] readTo = null, long knownLength = -1)
{
if (knownLength < 0) knownLength = (long)ReadUInt64Packed();
if (readTo == null || readTo.LongLength != knownLength) readTo = new byte[knownLength];
for (long i = 0; i < knownLength; ++i) readTo[i] = ReadByteDirect();
return readTo;
}
/// <summary>
/// CreateArraySegment
/// Creates an array segment from the size and offset values passed in.
/// If none are passed in, then it creates an array segment of the entire buffer.
/// </summary>
/// <param name="sizeToCopy">size to copy</param>
/// <param name="offset">offset within the stream buffer to start copying</param>
/// <returns>ArraySegment<byte></returns>
public ArraySegment<byte> CreateArraySegment(int sizeToCopy = -1, int offset = -1)
{
if (m_NetworkSource != null)
{
//If no offset was passed, used the current position
int Offset = offset == -1 ? (int)m_NetworkSource.Position : offset;
int CopySize = sizeToCopy == -1 && offset == -1 ? (int)m_NetworkSource.Length : sizeToCopy;
if (CopySize > 0)
{
//Check to make sure we won't be copying beyond our bounds
if ((m_NetworkSource.Length - Offset) >= CopySize)
{
return new ArraySegment<byte>(m_NetworkSource.GetBuffer(), Offset, CopySize);
}
//If we didn't pass anything in or passed the length of the buffer
if (CopySize == m_NetworkSource.Length)
{
Offset = 0;
}
else
{
Debug.LogError($"{nameof(CopySize)} ({CopySize}) exceeds bounds with an {nameof(Offset)} of ({Offset})! <returning empty array segment>");
return new ArraySegment<byte>();
}
//Return the request array segment
return new ArraySegment<byte>(m_NetworkSource.GetBuffer(), Offset, CopySize);
}
Debug.LogError($"{nameof(CopySize)} ({CopySize}) is zero or less! <returning empty array segment>");
}
else
{
Debug.LogError("Reader has no stream assigned to it! <returning empty array segment>");
}
return new ArraySegment<byte>();
}
/// <summary>
/// Read byte array diff into an optional buffer from the stream.
/// </summary>
/// <returns>The byte array created from the diff and original.</returns>
/// <param name="readTo">The buffer containing the old version or null.</param>
/// <param name="knownLength">The length of the array if it's known. Otherwise -1</param>
public byte[] ReadByteArrayDiff(byte[] readTo = null, long knownLength = -1)
{
if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream");
if (knownLength < 0) knownLength = (long)ReadUInt64Packed();
byte[] writeTo = readTo == null || readTo.LongLength != knownLength ? new byte[knownLength] : readTo;
ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength));
ulong mapStart;
long readToLength = readTo?.LongLength ?? 0;
for (long i = 0; i < knownLength; ++i)
{
if (i >= readToLength || ReadBit())
{
#if ARRAY_WRITE_PREMAP
// Move to data section
mapStart = m_NetworkSource.BitPosition;
m_NetworkSource.BitPosition = dBlockStart;
#endif
// Read datum
writeTo[i] = ReadByteDirect();
#if ARRAY_WRITE_PREMAP
dBlockStart = m_NetworkSource.BitPosition;
// Return to mapping section
m_NetworkSource.BitPosition = mapStart;
#endif
}
else if (i < readTo.LongLength) writeTo[i] = readTo[i];
}
m_NetworkSource.BitPosition = dBlockStart;
return writeTo;
}
/// <summary>
/// Read short array from the stream.
/// </summary>
/// <returns>The array read from the stream.</returns>
/// <param name="readTo">The buffer to read into or null to create a new array</param>
/// <param name="knownLength">The known length or -1 if unknown</param>
public short[] ReadShortArray(short[] readTo = null, long knownLength = -1)
{
if (knownLength < 0) knownLength = (long)ReadUInt64Packed();
if (readTo == null || readTo.LongLength != knownLength) readTo = new short[knownLength];
for (long i = 0; i < knownLength; ++i) readTo[i] = ReadInt16();
return readTo;
}
/// <summary>
/// Read short array in a packed format from the stream.
/// </summary>
/// <returns>The array read from the stream.</returns>
/// <param name="readTo">The buffer to read into or null to create a new array</param>
/// <param name="knownLength">The known length or -1 if unknown</param>
public short[] ReadShortArrayPacked(short[] readTo = null, long knownLength = -1)
{
if (knownLength < 0) knownLength = (long)ReadUInt64Packed();
if (readTo == null || readTo.LongLength != knownLength) readTo = new short[knownLength];
for (long i = 0; i < knownLength; ++i) readTo[i] = ReadInt16Packed();
return readTo;
}
/// <summary>
/// Read short array diff from the stream.
/// </summary>
/// <returns>The array created from the diff and the current version.</returns>
/// <param name="readTo">The buffer containing the old version or null.</param>
/// <param name="knownLength">The known length or -1 if unknown</param>
public short[] ReadShortArrayDiff(short[] readTo = null, long knownLength = -1)
{
if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream");
if (knownLength < 0) knownLength = (long)ReadUInt64Packed();
short[] writeTo = readTo == null || readTo.LongLength != knownLength ? new short[knownLength] : readTo;
ulong dBlockStart = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength));
ulong mapStart;
long readToLength = readTo?.LongLength ?? 0;
for (long i = 0; i < knownLength; ++i)
{
if (i >= readToLength || ReadBit())
{
#if ARRAY_WRITE_PREMAP
// Move to data section
mapStart = m_NetworkSource.BitPosition;
m_NetworkSource.BitPosition = dBlockStart;
#endif
// Read datum
writeTo[i] = ReadInt16();
#if ARRAY_WRITE_PREMAP
dBlockStart = m_NetworkSource.BitPosition;
// Return to mapping section
m_NetworkSource.BitPosition = mapStart;
#endif
}
else if (i < readTo.LongLength) writeTo[i] = readTo[i];
}
m_NetworkSource.BitPosition = dBlockStart;
return writeTo;
}
/// <summary>
/// Read short array diff in a packed format from the stream.
/// </summary>
/// <returns>The array created from the diff and the current version.</returns>
/// <param name="readTo">The buffer containing the old version or null.</param>
/// <param name="knownLength">The known length or -1 if unknown</param>
public short[] ReadShortArrayPackedDiff(short[] readTo = null, long knownLength = -1)
{
if (m_NetworkSource == null) throw new InvalidOperationException($"Cannot read bits on a non-{nameof(NetworkBuffer)} stream");
if (knownLength < 0) knownLength = (long)ReadUInt64Packed();
short[] writeTo = readTo == null || readTo.LongLength != knownLength ? new short[knownLength] : readTo;
ulong data = m_NetworkSource.BitPosition + (ulong)(readTo == null ? 0 : Math.Min(knownLength, readTo.LongLength));
ulong rset;
long readToLength = readTo?.LongLength ?? 0;
for (long i = 0; i < knownLength; ++i)
{
if (i >= readToLength || ReadBit())
{
#if ARRAY_WRITE_PREMAP
// Move to data section
rset = m_NetworkSource.BitPosition;
m_NetworkSource.BitPosition = data;
#endif
// Read datum
writeTo[i] = ReadInt16Packed();
#if ARRAY_WRITE_PREMAP
// Return to mapping section
data = m_NetworkSource.BitPosition;
m_NetworkSource.BitPosition = rset;
#endif
}
else if (i < readTo.LongLength) writeTo[i] = readTo[i];
}
m_NetworkSource.BitPosition = data;
return writeTo;
}
/// <summary>
/// Read ushort array from the stream.
/// </summary>
/// <returns>The array read from the stream.</returns>
/// <param name="readTo">The buffer to read into or null to create a new array</param>
/// <param name="knownLength">The known length or -1 if unknown</param>
public ushort[] ReadUShortArray(ushort[] readTo = null, long knownLength = -1)
{
if (knownLength < 0) knownLength = (long)ReadUInt64Packed();
if (readTo == null || readTo.LongLength != knownLength) readTo = new ushort[knownLength];
for (long i = 0; i < knownLength; ++i) readTo[i] = ReadUInt16();
return readTo;
}
/// <summary>
/// Read ushort array in a packed format from the stream.
/// </summary>
/// <returns>The array read from the stream.</returns>
/// <param name="readTo">The buffer to read into or null to create a new array</param>
/// <param name="knownLength">The known length or -1 if unknown</param>
public ushort[] ReadUShortArrayPacked(ushort[] readTo = null, long knownLength = -1)
{
if (knownLength < 0) knownLength = (long)ReadUInt64Packed();
if (readTo == null || readTo.LongLength != knownLength) readTo = new ushort[knownLength];