-
Notifications
You must be signed in to change notification settings - Fork 459
Expand file tree
/
Copy pathFastBufferWriter.cs
More file actions
1926 lines (1762 loc) · 85.3 KB
/
FastBufferWriter.cs
File metadata and controls
1926 lines (1762 loc) · 85.3 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
using System;
using System.Runtime.CompilerServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
namespace Unity.Netcode
{
/// <summary>
/// Optimized class used for writing values into a byte stream
/// <see cref="FastBufferReader"/>
/// <see cref="BytePacker"/>
/// <see cref="ByteUnpacker"/>
/// </summary>
public struct FastBufferWriter : IDisposable
{
internal struct WriterHandle
{
internal unsafe byte* BufferPointer;
internal int Position;
internal int Length;
internal int Capacity;
internal int MaxCapacity;
internal Allocator Allocator;
internal bool BufferGrew;
#if DEVELOPMENT_BUILD || UNITY_EDITOR
internal int AllowedWriteMark;
internal bool InBitwiseContext;
#endif
}
internal unsafe WriterHandle* Handle;
private static byte[] s_ByteArrayCache = new byte[65535];
/// <summary>
/// The current write position
/// </summary>
public unsafe int Position
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Handle->Position;
}
/// <summary>
/// The current total buffer size
/// </summary>
public unsafe int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Handle->Capacity;
}
/// <summary>
/// The maximum possible total buffer size
/// </summary>
public unsafe int MaxCapacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Handle->MaxCapacity;
}
/// <summary>
/// The total amount of bytes that have been written to the stream
/// </summary>
public unsafe int Length
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Handle->Position > Handle->Length ? Handle->Position : Handle->Length;
}
/// <summary>
/// Gets a value indicating whether the writer has been initialized and a handle allocated.
/// </summary>
public unsafe bool IsInitialized => Handle != null;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void CommitBitwiseWrites(int amount)
{
Handle->Position += amount;
#if DEVELOPMENT_BUILD || UNITY_EDITOR
Handle->InBitwiseContext = false;
#endif
}
/// <summary>
/// Create a FastBufferWriter.
/// </summary>
/// <param name="size">Size of the buffer to create</param>
/// <param name="allocator">Allocator to use in creating it</param>
/// <param name="maxSize">Maximum size the buffer can grow to. If less than size, buffer cannot grow.</param>
public unsafe FastBufferWriter(int size, Allocator allocator, int maxSize = -1)
{
// Allocating both the Handle struct and the buffer in a single allocation - sizeof(WriterHandle) + size
// The buffer for the initial allocation is the next block of memory after the handle itself.
// If the buffer grows, a new buffer will be allocated and the handle pointer pointed at the new location...
// The original buffer won't be deallocated until the writer is destroyed since it's part of the handle allocation.
Handle = (WriterHandle*)UnsafeUtility.Malloc(sizeof(WriterHandle) + size, UnsafeUtility.AlignOf<WriterHandle>(), allocator);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
UnsafeUtility.MemSet(Handle, 0, sizeof(WriterHandle) + size);
#endif
Handle->BufferPointer = (byte*)(Handle + 1);
Handle->Position = 0;
Handle->Length = 0;
Handle->Capacity = size;
Handle->Allocator = allocator;
Handle->MaxCapacity = maxSize < size ? size : maxSize;
Handle->BufferGrew = false;
#if DEVELOPMENT_BUILD || UNITY_EDITOR
Handle->AllowedWriteMark = 0;
Handle->InBitwiseContext = false;
#endif
}
/// <summary>
/// <see cref="IDisposable"/> implementation that frees the allocated buffer
/// </summary>
public unsafe void Dispose()
{
if (Handle->BufferGrew)
{
UnsafeUtility.Free(Handle->BufferPointer, Handle->Allocator);
}
UnsafeUtility.Free(Handle, Handle->Allocator);
Handle = null;
}
/// <summary>
/// Move the write position in the stream.
/// Note that moving forward past the current length will extend the buffer's Length value even if you don't write.
/// </summary>
/// <param name="where">Absolute value to move the position to, truncated to Capacity</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Seek(int where)
{
// This avoids us having to synchronize length all the time.
// Writing things is a much more common operation than seeking
// or querying length. The length here is a high watermark of
// what's been written. So before we seek, if the current position
// is greater than the length, we update that watermark.
// When querying length later, we'll return whichever of the two
// values is greater, thus if we write past length, length increases
// because position increases, and if we seek backward, length remembers
// the position it was in.
// Seeking forward will not update the length.
where = Math.Min(where, Handle->Capacity);
if (Handle->Position > Handle->Length && where < Handle->Position)
{
Handle->Length = Handle->Position;
}
Handle->Position = where;
}
/// <summary>
/// Truncate the stream by setting Length to the specified value.
/// If Position is greater than the specified value, it will be moved as well.
/// </summary>
/// <param name="where">The value to truncate to. If -1, the current position will be used.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Truncate(int where = -1)
{
if (where == -1)
{
where = Position;
}
if (Handle->Position > where)
{
Handle->Position = where;
}
if (Handle->Length > where)
{
Handle->Length = where;
}
}
/// <summary>
/// Retrieve a BitWriter to be able to perform bitwise operations on the buffer.
/// No bytewise operations can be performed on the buffer until bitWriter.Dispose() has been called.
/// At the end of the operation, FastBufferWriter will remain byte-aligned.
/// </summary>
/// <returns>A BitWriter</returns>
public unsafe BitWriter EnterBitwiseContext()
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
Handle->InBitwiseContext = true;
#endif
return new BitWriter(this);
}
internal unsafe void Grow(int additionalSizeRequired)
{
var desiredSize = Handle->Capacity * 2;
while (desiredSize < Position + additionalSizeRequired)
{
desiredSize *= 2;
}
var newSize = Math.Min(desiredSize, Handle->MaxCapacity);
byte* newBuffer = (byte*)UnsafeUtility.Malloc(newSize, UnsafeUtility.AlignOf<byte>(), Handle->Allocator);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
UnsafeUtility.MemSet(newBuffer, 0, newSize);
#endif
UnsafeUtility.MemCpy(newBuffer, Handle->BufferPointer, Length);
if (Handle->BufferGrew)
{
UnsafeUtility.Free(Handle->BufferPointer, Handle->Allocator);
}
Handle->BufferGrew = true;
Handle->BufferPointer = newBuffer;
Handle->Capacity = newSize;
}
/// <summary>
/// Allows faster serialization by batching bounds checking.
/// When you know you will be writing multiple fields back-to-back and you know the total size,
/// you can call TryBeginWrite() once on the total size, and then follow it with calls to
/// WriteValue() instead of WriteValueSafe() for faster serialization.
///
/// Unsafe write operations will throw OverflowException in editor and development builds if you
/// go past the point you've marked using TryBeginWrite(). In release builds, OverflowException will not be thrown
/// for performance reasons, since the point of using TryBeginWrite is to avoid bounds checking in the following
/// operations in release builds.
/// </summary>
/// <param name="bytes">Amount of bytes to write</param>
/// <returns>True if the write is allowed, false otherwise</returns>
/// <exception cref="InvalidOperationException">If called while in a bitwise context</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe bool TryBeginWrite(int bytes)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferWriter in bytewise mode while in a bitwise context.");
}
#endif
if (Handle->Position + bytes > Handle->Capacity)
{
if (Handle->Position + bytes > Handle->MaxCapacity)
{
return false;
}
if (Handle->Capacity < Handle->MaxCapacity)
{
Grow(bytes);
}
else
{
return false;
}
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
Handle->AllowedWriteMark = Handle->Position + bytes;
#endif
return true;
}
/// <summary>
/// Allows faster serialization by batching bounds checking.
/// When you know you will be writing multiple fields back-to-back and you know the total size,
/// you can call TryBeginWrite() once on the total size, and then follow it with calls to
/// WriteValue() instead of WriteValueSafe() for faster serialization.
///
/// Unsafe write operations will throw OverflowException in editor and development builds if you
/// go past the point you've marked using TryBeginWrite(). In release builds, OverflowException will not be thrown
/// for performance reasons, since the point of using TryBeginWrite is to avoid bounds checking in the following
/// operations in release builds. Instead, attempting to write past the marked position in release builds
/// will write to random memory and cause undefined behavior, likely including instability and crashes.
/// </summary>
/// <typeparam name="T">The value type to write</typeparam>
/// <param name="value">The value of the type `T` you want to write</param>
/// <returns>True if the write is allowed, false otherwise</returns>
/// <exception cref="InvalidOperationException">If called while in a bitwise context</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe bool TryBeginWriteValue<T>(in T value) where T : unmanaged
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferWriter in bytewise mode while in a bitwise context.");
}
#endif
int len = sizeof(T);
if (Handle->Position + len > Handle->Capacity)
{
if (Handle->Position + len > Handle->MaxCapacity)
{
return false;
}
if (Handle->Capacity < Handle->MaxCapacity)
{
Grow(len);
}
else
{
return false;
}
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
Handle->AllowedWriteMark = Handle->Position + len;
#endif
return true;
}
/// <summary>
/// Internal version of TryBeginWrite.
/// Differs from TryBeginWrite only in that it won't ever move the AllowedWriteMark backward.
/// </summary>
/// <param name="bytes">The number of bytes to check for write availability</param>
/// <returns>True if the specified number of bytes can be written, false if there isn't enough space</returns>
/// <exception cref="InvalidOperationException">Thrown when attempting to use BufferWriter in bytewise mode while in a bitwise context</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe bool TryBeginWriteInternal(int bytes)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferWriter in bytewise mode while in a bitwise context.");
}
#endif
if (Handle->Position + bytes > Handle->Capacity)
{
if (Handle->Position + bytes > Handle->MaxCapacity)
{
return false;
}
if (Handle->Capacity < Handle->MaxCapacity)
{
Grow(bytes);
}
else
{
return false;
}
}
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->Position + bytes > Handle->AllowedWriteMark)
{
Handle->AllowedWriteMark = Handle->Position + bytes;
}
#endif
return true;
}
/// <summary>
/// Returns an array representation of the underlying byte buffer.
/// !!Allocates a new array!!
/// </summary>
/// <returns>A new byte array containing a copy of the buffer's contents.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe byte[] ToArray()
{
byte[] ret = new byte[Length];
fixed (byte* b = ret)
{
UnsafeUtility.MemCpy(b, Handle->BufferPointer, Length);
}
return ret;
}
/// <summary>
/// Uses a static cached array to create an array segment with no allocations.
/// This array can only be used until the next time ToTempByteArray() is called on ANY FastBufferWriter,
/// as the cached buffer is shared by all of them and will be overwritten.
/// As such, this should be used with care.
/// </summary>
/// <returns></returns>
internal unsafe ArraySegment<byte> ToTempByteArray()
{
var length = Length;
if (length > s_ByteArrayCache.Length)
{
return new ArraySegment<byte>(ToArray(), 0, length);
}
fixed (byte* b = s_ByteArrayCache)
{
UnsafeUtility.MemCpy(b, Handle->BufferPointer, length);
}
return new ArraySegment<byte>(s_ByteArrayCache, 0, length);
}
/// <summary>
/// Gets a direct pointer to the underlying buffer
/// </summary>
/// <returns>An unsafe pointer to the start of the underlying buffer memory</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe byte* GetUnsafePtr()
{
return Handle->BufferPointer;
}
/// <summary>
/// Gets a direct pointer to the underlying buffer at the current read position
/// </summary>
/// <returns>An unsafe pointer to the underlying buffer memory offset by the current position</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe byte* GetUnsafePtrAtCurrentPosition()
{
return Handle->BufferPointer + Handle->Position;
}
/// <summary>
/// Get the required size to write a string
/// </summary>
/// <param name="s">The string to write</param>
/// <param name="oneByteChars">Whether or not to use one byte per character. This will only allow ASCII</param>
/// <returns>The total number of bytes required to write the string, including the length field</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetWriteSize(string s, bool oneByteChars = false)
{
return SizeOfLengthField() + s.Length * (oneByteChars ? sizeof(byte) : sizeof(char));
}
/// <summary>
/// Write an INetworkSerializable
/// </summary>
/// <param name="value">The value to write</param>
/// <typeparam name="T">The type of the value</typeparam>
public void WriteNetworkSerializable<T>(in T value) where T : INetworkSerializable
{
var bufferSerializer = new BufferSerializer<BufferSerializerWriter>(new BufferSerializerWriter(this));
value.NetworkSerialize(bufferSerializer);
}
/// <summary>
/// Write an array of INetworkSerializables
/// </summary>
/// <param name="array">The array of objects to write</param>
/// <param name="count">The number of elements to write. If set to -1, will write all elements from offset to end</param>
/// <param name="offset">The starting position in the array from which to begin writing</param>
/// <typeparam name="T">The type of the value</typeparam>
public void WriteNetworkSerializable<T>(T[] array, int count = -1, int offset = 0) where T : INetworkSerializable
{
int sizeInTs = count != -1 ? count : array.Length - offset;
WriteLengthSafe(sizeInTs);
foreach (var item in array)
{
WriteNetworkSerializable(item);
}
}
/// <summary>
/// Write a NativeArray of INetworkSerializables
/// </summary>
/// <param name="array">The NativeArray containing the values to write</param>
/// <param name="count">The number of elements to write. If -1 (default), writes array.Length - offset elements</param>
/// <param name="offset">The starting position in the array. Defaults to 0</param>
/// <typeparam name="T">The type of the value</typeparam>
public void WriteNetworkSerializable<T>(NativeArray<T> array, int count = -1, int offset = 0) where T : unmanaged, INetworkSerializable
{
int sizeInTs = count != -1 ? count : array.Length - offset;
WriteLengthSafe(sizeInTs);
foreach (var item in array)
{
WriteNetworkSerializable(item);
}
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
/// <summary>
/// Write a NativeList of INetworkSerializables
/// </summary>
/// <param name="array">The NativeArray containing the values to write</param>
/// <param name="count">The number of elements to write. If -1 (default), writes array.Length - offset elements</param>
/// <param name="offset">The starting position in the array. Defaults to 0/param>
/// <typeparam name="T">The type of the value</typeparam>
public void WriteNetworkSerializable<T>(NativeList<T> array, int count = -1, int offset = 0) where T : unmanaged, INetworkSerializable
{
int sizeInTs = count != -1 ? count : array.Length - offset;
WriteLengthSafe(sizeInTs);
foreach (var item in array)
{
WriteNetworkSerializable(item);
}
}
#endif
/// <summary>
/// Writes a string
/// </summary>
/// <param name="s">The string to write</param>
/// <param name="oneByteChars">Whether or not to use one byte per character. This will only allow ASCII</param>
public unsafe void WriteValue(string s, bool oneByteChars = false)
{
WriteLength((uint)s.Length);
int target = s.Length;
if (oneByteChars)
{
for (int i = 0; i < target; ++i)
{
WriteByte((byte)s[i]);
}
}
else
{
fixed (char* native = s)
{
WriteBytes((byte*)native, target * sizeof(char));
}
}
}
/// <summary>
/// Writes a string
///
/// "Safe" version - automatically performs bounds checking. Less efficient than bounds checking
/// for multiple writes at once by calling TryBeginWrite.
/// </summary>
/// <param name="s">The string to write</param>
/// <param name="oneByteChars">Whether or not to use one byte per character. This will only allow ASCII</param>
public unsafe void WriteValueSafe(string s, bool oneByteChars = false)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferWriter in bytewise mode while in a bitwise context.");
}
#endif
int sizeInBytes = GetWriteSize(s, oneByteChars);
if (!TryBeginWriteInternal(sizeInBytes))
{
throw new OverflowException("Writing past the end of the buffer");
}
WriteLength((uint)s.Length);
int target = s.Length;
if (oneByteChars)
{
for (int i = 0; i < target; ++i)
{
WriteByte((byte)s[i]);
}
}
else
{
fixed (char* native = s)
{
WriteBytes((byte*)native, target * sizeof(char));
}
}
}
/// <summary>
/// Get the required size to write an unmanaged array
/// </summary>
/// <param name="array">The array to write</param>
/// <param name="count">The amount of elements to write</param>
/// <param name="offset">Where in the array to start</param>
/// <typeparam name="T">The type of elements in the array, must be unmanaged</typeparam>
/// <returns>The total number of bytes required to write the array, including the length field</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int GetWriteSize<T>(T[] array, int count = -1, int offset = 0) where T : unmanaged
{
int sizeInTs = count != -1 ? count : array.Length - offset;
int sizeInBytes = sizeInTs * sizeof(T);
return SizeOfLengthField() + sizeInBytes;
}
/// <summary>
/// Get the required size to write a NativeArray
/// </summary>
/// <param name="array">The array to write</param>
/// <param name="count">The amount of elements to write</param>
/// <param name="offset">Where in the array to start</param>
/// <typeparam name="T">The type of elements in the array, must be unmanaged</typeparam>
/// <returns>The total number of bytes required to write the array, including the length field</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int GetWriteSize<T>(NativeArray<T> array, int count = -1, int offset = 0) where T : unmanaged
{
int sizeInTs = count != -1 ? count : array.Length - offset;
int sizeInBytes = sizeInTs * sizeof(T);
return SizeOfLengthField() + sizeInBytes;
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
/// <summary>
/// Get the required size to write a NativeList
/// </summary>
/// <param name="array">The array to write</param>
/// <param name="count">The amount of elements to write</param>
/// <param name="offset">Where in the array to start</param>
/// <typeparam name="T">The type of elements in the array, must be unmanaged</typeparam>
/// <returns>The total number of bytes required to write the array, including the length field</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int GetWriteSize<T>(NativeList<T> array, int count = -1, int offset = 0) where T : unmanaged
{
int sizeInTs = count != -1 ? count : array.Length - offset;
int sizeInBytes = sizeInTs * sizeof(T);
return SizeOfLengthField() + sizeInBytes;
}
#endif
/// <summary>
/// Write a partial value. The specified number of bytes is written from the value and the rest is ignored.
/// </summary>
/// <param name="value">Value to write</param>
/// <param name="bytesToWrite">Number of bytes</param>
/// <param name="offsetBytes">Offset into the value to begin reading the bytes</param>
/// <typeparam name="T">The type of elements in the array, must be unmanaged</typeparam>
/// <exception cref="InvalidOperationException">Thrown when attempting to use BufferWriter in bytewise mode while in a bitwise context</exception>
/// <exception cref="OverflowException">Thrown when attempting to write without first calling TryBeginWrite() or when writing beyond the allowed write mark</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WritePartialValue<T>(T value, int bytesToWrite, int offsetBytes = 0) where T : unmanaged
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferWriter in bytewise mode while in a bitwise context.");
}
if (Handle->Position + bytesToWrite > Handle->AllowedWriteMark)
{
throw new OverflowException($"Attempted to write without first calling {nameof(TryBeginWrite)}()");
}
#endif
byte* ptr = ((byte*)&value) + offsetBytes;
byte* bufferPointer = Handle->BufferPointer + Handle->Position;
UnsafeUtility.MemCpy(bufferPointer, ptr, bytesToWrite);
Handle->Position += bytesToWrite;
}
/// <summary>
/// Write a byte to the stream.
/// </summary>
/// <param name="value">Value to write</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteByte(byte value)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferWriter in bytewise mode while in a bitwise context.");
}
if (Handle->Position + 1 > Handle->AllowedWriteMark)
{
throw new OverflowException($"Attempted to write without first calling {nameof(TryBeginWrite)}()");
}
#endif
Handle->BufferPointer[Handle->Position++] = value;
}
/// <summary>
/// Write a byte to the stream.
///
/// "Safe" version - automatically performs bounds checking. Less efficient than bounds checking
/// for multiple writes at once by calling TryBeginWrite.
/// </summary>
/// <param name="value">Value to write</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteByteSafe(byte value)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferWriter in bytewise mode while in a bitwise context.");
}
#endif
if (!TryBeginWriteInternal(1))
{
throw new OverflowException("Writing past the end of the buffer");
}
Handle->BufferPointer[Handle->Position++] = value;
}
/// <summary>
/// Write multiple bytes to the stream
/// </summary>
/// <param name="value">Value to write</param>
/// <param name="size">Number of bytes to write</param>
/// <param name="offset">Offset into the buffer to begin writing</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteBytes(byte* value, int size, int offset = 0)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferWriter in bytewise mode while in a bitwise context.");
}
if (Handle->Position + size > Handle->AllowedWriteMark)
{
throw new OverflowException($"Attempted to write without first calling {nameof(TryBeginWrite)}(), Position+Size={Handle->Position + size} > AllowedWriteMark={Handle->AllowedWriteMark}");
}
#endif
UnsafeUtility.MemCpy((Handle->BufferPointer + Handle->Position), value + offset, size);
Handle->Position += size;
}
/// <summary>
/// Write multiple bytes to the stream
///
/// "Safe" version - automatically performs bounds checking. Less efficient than bounds checking
/// for multiple writes at once by calling TryBeginWrite.
/// </summary>
/// <param name="value">Value to write</param>
/// <param name="size">Number of bytes to write</param>
/// <param name="offset">Offset into the buffer to begin writing</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteBytesSafe(byte* value, int size, int offset = 0)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (Handle->InBitwiseContext)
{
throw new InvalidOperationException(
"Cannot use BufferWriter in bytewise mode while in a bitwise context.");
}
#endif
if (!TryBeginWriteInternal(size))
{
throw new OverflowException($"Writing past the end of the buffer, size is {size} bytes but remaining capacity is {Handle->Capacity - Handle->Position} bytes");
}
UnsafeUtility.MemCpy((Handle->BufferPointer + Handle->Position), value + offset, size);
Handle->Position += size;
}
/// <summary>
/// Write multiple bytes to the stream
/// </summary>
/// <param name="value">Value to write</param>
/// <param name="size">Number of bytes to write</param>
/// <param name="offset">Offset into the buffer to begin writing</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteBytes(byte[] value, int size = -1, int offset = 0)
{
fixed (byte* ptr = value)
{
WriteBytes(ptr, size == -1 ? value.Length : size, offset);
}
}
/// <summary>
/// Write multiple bytes to the stream
/// </summary>
/// <param name="value">Value to write</param>
/// <param name="size">Number of bytes to write</param>
/// <param name="offset">Offset into the buffer to begin writing</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteBytes(NativeArray<byte> value, int size = -1, int offset = 0)
{
byte* ptr = (byte*)value.GetUnsafePtr();
WriteBytes(ptr, size == -1 ? value.Length : size, offset);
}
/// <summary>
/// Write multiple bytes to the stream
/// </summary>
/// <param name="value">Value to write</param>
/// <param name="size">Number of bytes to write</param>
/// <param name="offset">Offset into the buffer to begin writing</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteBytes(NativeList<byte> value, int size = -1, int offset = 0)
{
byte* ptr = value.GetUnsafePtr();
WriteBytes(ptr, size == -1 ? value.Length : size, offset);
}
/// <summary>
/// Write multiple bytes to the stream
///
/// "Safe" version - automatically performs bounds checking. Less efficient than bounds checking
/// for multiple writes at once by calling TryBeginWrite.
/// </summary>
/// <param name="value">Value to write</param>
/// <param name="size">Number of bytes to write</param>
/// <param name="offset">Offset into the buffer to begin writing</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteBytesSafe(byte[] value, int size = -1, int offset = 0)
{
fixed (byte* ptr = value)
{
WriteBytesSafe(ptr, size == -1 ? value.Length : size, offset);
}
}
/// <summary>
/// Write multiple bytes to the stream
/// </summary>
/// <param name="value">Value to write</param>
/// <param name="size">Number of bytes to write</param>
/// <param name="offset">Offset into the buffer to begin writing</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteBytesSafe(NativeArray<byte> value, int size = -1, int offset = 0)
{
byte* ptr = (byte*)value.GetUnsafePtr();
WriteBytesSafe(ptr, size == -1 ? value.Length : size, offset);
}
/// <summary>
/// Write multiple bytes to the stream
/// </summary>
/// <param name="value">Value to write</param>
/// <param name="size">Number of bytes to write</param>
/// <param name="offset">Offset into the buffer to begin writing</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void WriteBytesSafe(NativeList<byte> value, int size = -1, int offset = 0)
{
byte* ptr = value.GetUnsafePtr();
WriteBytesSafe(ptr, size == -1 ? value.Length : size, offset);
}
/// <summary>
/// Copy the contents of this writer into another writer.
/// The contents will be copied from the beginning of this writer to its current position.
/// They will be copied to the other writer starting at the other writer's current position.
/// </summary>
/// <param name="other">Writer to copy to</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void CopyTo(FastBufferWriter other)
{
other.WriteBytes(Handle->BufferPointer, Handle->Position);
}
/// <summary>
/// Copy the contents of another writer into this writer.
/// The contents will be copied from the beginning of the other writer to its current position.
/// They will be copied to this writer starting at this writer's current position.
/// </summary>
/// <param name="other">Writer to copy to</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void CopyFrom(FastBufferWriter other)
{
WriteBytes(other.Handle->BufferPointer, other.Handle->Position);
}
/// <summary>
/// Get the write size for any general unmanaged value
/// The ForStructs value here makes this the lowest-priority overload so other versions
/// will be prioritized over this if they match
/// </summary>
/// <param name="value">The unmanaged value to calculate the size for</param>
/// <param name="unused">Unused parameter for overload resolution</param>
/// <typeparam name="T">The type of the value, must be unmanaged</typeparam>
/// <returns>The size in bytes required to write the value</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int GetWriteSize<T>(in T value, ForStructs unused = default) where T : unmanaged
{
return sizeof(T);
}
/// <summary>
/// Get the write size for a FixedString
/// </summary>
/// <param name="value">The FixedString value to calculate the size for</param>
/// <typeparam name="T">The specific FixedString type, must implement INativeList{byte} and IUTF8Bytes</typeparam>
/// <returns>The size in bytes required to write the value</returns>
public static int GetWriteSize<T>(in T value)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
return SizeOfLengthField() + value.Length;
}
/// <summary>
/// Get the write size for an array of FixedStrings
/// </summary>
/// <param name="value">The NativeArray of FixedStrings to calculate the size for</param>
/// <typeparam name="T">The specific FixedString type, must implement INativeList{byte} and IUTF8Bytes</typeparam>
/// <returns>The total size in bytes required to write all strings, including all length fields</returns>
public static int GetWriteSize<T>(in NativeArray<T> value)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
var size = SizeOfLengthField();
foreach (var item in value)
{
size += SizeOfLengthField() + item.Length;
}
return size;
}
#if UNITY_NETCODE_NATIVE_COLLECTION_SUPPORT
/// <summary>
/// Get the write size for an array of FixedStrings
/// </summary>
/// <param name="value">The NativeList of FixedStrings to calculate the size for</param>
/// <typeparam name="T">The specific FixedString type, must implement INativeList{byte} and IUTF8Bytes</typeparam>
/// <returns>The total size in bytes required to write all strings, including all length fields</returns>
public static int GetWriteSize<T>(in NativeList<T> value)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
var size = SizeOfLengthField();
foreach (var item in value)
{
size += SizeOfLengthField() + item.Length;
}
return size;
}
#endif
/// <summary>
/// Get the size required to write an unmanaged value of type T
/// </summary>
/// <typeparam name="T">The type to calculate the size for, must be unmanaged</typeparam>
/// <returns>The size in bytes required to write a value of type T</returns>
public static unsafe int GetWriteSize<T>() where T : unmanaged
{
return sizeof(T);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void WriteUnmanaged<T>(in T value) where T : unmanaged
{
fixed (T* ptr = &value)
{
byte* bytes = (byte*)ptr;
WriteBytes(bytes, sizeof(T));
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void WriteUnmanagedSafe<T>(in T value) where T : unmanaged
{
fixed (T* ptr = &value)
{
byte* bytes = (byte*)ptr;
WriteBytesSafe(bytes, sizeof(T));
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int SizeOfLengthField() => sizeof(uint);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteLengthSafe(uint length) => WriteUnmanagedSafe(length);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteLength(uint length) => WriteUnmanaged(length);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteLengthSafe(int length)
{
if (length < 0)
{
throw new InvalidCastException("Cannot write negative length");
}
WriteLengthSafe((uint)length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteLength(int length) => WriteLength((uint)length);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void WriteUnmanaged<T>(T[] value) where T : unmanaged
{
WriteLength(value.Length);
fixed (T* ptr = value)
{
byte* bytes = (byte*)ptr;
WriteBytes(bytes, sizeof(T) * value.Length);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void WriteUnmanagedSafe<T>(T[] value) where T : unmanaged
{
WriteLengthSafe(value.Length);
fixed (T* ptr = value)
{
byte* bytes = (byte*)ptr;
WriteBytesSafe(bytes, sizeof(T) * value.Length);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void WriteUnmanaged<T>(NativeArray<T> value) where T : unmanaged
{
WriteLength(value.Length);
var ptr = (T*)value.GetUnsafePtr();
{
byte* bytes = (byte*)ptr;
WriteBytes(bytes, sizeof(T) * value.Length);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void WriteUnmanagedSafe<T>(NativeArray<T> value) where T : unmanaged
{
WriteLengthSafe(value.Length);
var ptr = (T*)value.GetUnsafePtr();
{
byte* bytes = (byte*)ptr;