-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathBlobBuilder.cs
More file actions
1189 lines (995 loc) · 44.5 KB
/
Copy pathBlobBuilder.cs
File metadata and controls
1189 lines (995 loc) · 44.5 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Reflection.Internal;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Reflection.Metadata
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
public partial class BlobBuilder
{
// The implementation is akin to StringBuilder.
// The differences:
// - BlobBuilder allows efficient sequential write of the built content to a stream.
// - BlobBuilder allows for chunk allocation customization. A custom allocator can use pooling strategy, for example.
internal const int DefaultChunkSize = 256;
// Must be at least the size of the largest primitive type we write atomically (Guid).
internal const int MinChunkSize = 16;
// Builders are linked like so:
//
// [1:first]->[2]->[3:last]<-[4:head]
// ^_______________|
//
// In this case the content represented is a sequence (1,2,3,4).
// This structure optimizes for append write operations and sequential enumeration from the start of the chain.
// Data can only be written to the head node. Other nodes are "frozen".
private BlobBuilder _nextOrPrevious;
private BlobBuilder FirstChunk => _nextOrPrevious._nextOrPrevious;
// The sum of lengths of all preceding chunks (not including the current chunk),
// or a difference between original buffer length of a builder that was linked as a suffix to another builder,
// and the current length of the buffer (not that the buffers are swapped when suffix linking).
private int _previousLengthOrFrozenSuffixLengthDelta;
private byte[] _buffer;
// The length of data in the buffer in lower 31 bits.
// Head: highest bit is 0, length may be 0.
// Non-head: highest bit is 1, lower 31 bits are not all 0.
private uint _length;
private const uint IsFrozenMask = 0x80000000;
internal bool IsHead => (_length & IsFrozenMask) == 0;
private int Length => (int)(_length & ~IsFrozenMask);
private uint FrozenLength => _length | IsFrozenMask;
private Span<byte> Span => _buffer.AsSpan(0, Length);
public BlobBuilder(int capacity = DefaultChunkSize)
{
if (capacity < 0)
{
Throw.ArgumentOutOfRange(nameof(capacity));
}
_nextOrPrevious = this;
_buffer = new byte[Math.Max(MinChunkSize, capacity)];
}
protected virtual BlobBuilder AllocateChunk(int minimalSize)
{
return new BlobBuilder(Math.Max(_buffer.Length, minimalSize));
}
protected virtual void FreeChunk()
{
// nop
}
public void Clear()
{
if (!IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}
// Swap buffer with the first chunk.
// Note that we need to keep holding on all allocated buffers,
// so that builders with custom allocator can release them.
var first = FirstChunk;
if (first != this)
{
var firstBuffer = first._buffer;
first._length = FrozenLength;
first._buffer = _buffer;
_buffer = firstBuffer;
}
// free all chunks except for the current one
foreach (BlobBuilder chunk in GetChunks())
{
if (chunk != this)
{
chunk.ClearAndFreeChunk();
}
}
ClearChunk();
}
protected void Free()
{
Clear();
FreeChunk();
}
// internal for testing
internal void ClearChunk()
{
_length = 0;
_previousLengthOrFrozenSuffixLengthDelta = 0;
_nextOrPrevious = this;
}
[Conditional("DEBUG")]
private void CheckInvariants()
{
Debug.Assert(_buffer != null);
Debug.Assert(Length >= 0 && Length <= _buffer.Length);
Debug.Assert(_nextOrPrevious != null);
if (IsHead)
{
Debug.Assert(_previousLengthOrFrozenSuffixLengthDelta >= 0);
// last chunk:
int totalLength = 0;
foreach (var chunk in GetChunks())
{
Debug.Assert(chunk.IsHead || chunk.Length > 0);
totalLength += chunk.Length;
}
Debug.Assert(totalLength == Count);
}
}
public int Count => _previousLengthOrFrozenSuffixLengthDelta + Length;
private int PreviousLength
{
get
{
Debug.Assert(IsHead);
return _previousLengthOrFrozenSuffixLengthDelta;
}
set
{
Debug.Assert(IsHead);
_previousLengthOrFrozenSuffixLengthDelta = value;
}
}
protected int FreeBytes => _buffer.Length - Length;
// internal for testing
protected internal int ChunkCapacity => _buffer.Length;
// internal for testing
internal Chunks GetChunks()
{
if (!IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}
return new Chunks(this);
}
/// <summary>
/// Returns a sequence of all blobs that represent the content of the builder.
/// </summary>
/// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception>
public Blobs GetBlobs()
{
if (!IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}
return new Blobs(this);
}
/// <summary>
/// Compares the current content of this writer with another one.
/// </summary>
/// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception>
public bool ContentEquals(BlobBuilder other)
{
if (!IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}
if (ReferenceEquals(this, other))
{
return true;
}
if (other == null)
{
return false;
}
if (!other.IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}
if (Count != other.Count)
{
return false;
}
var leftEnumerator = GetChunks();
var rightEnumerator = other.GetChunks();
int leftStart = 0;
int rightStart = 0;
bool leftContinues = leftEnumerator.MoveNext();
bool rightContinues = rightEnumerator.MoveNext();
while (leftContinues && rightContinues)
{
Debug.Assert(leftStart == 0 || rightStart == 0);
var left = leftEnumerator.Current;
var right = rightEnumerator.Current;
int minLength = Math.Min(left.Length - leftStart, right.Length - rightStart);
if (!left._buffer.AsSpan(leftStart, minLength).SequenceEqual(right._buffer.AsSpan(rightStart, minLength)))
{
return false;
}
leftStart += minLength;
rightStart += minLength;
// nothing remains in left chunk to compare:
if (leftStart == left.Length)
{
leftContinues = leftEnumerator.MoveNext();
leftStart = 0;
}
// nothing remains in left chunk to compare:
if (rightStart == right.Length)
{
rightContinues = rightEnumerator.MoveNext();
rightStart = 0;
}
}
return leftContinues == rightContinues;
}
/// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception>
public byte[] ToArray()
{
return ToArray(0, Count);
}
/// <exception cref="ArgumentOutOfRangeException">Range specified by <paramref name="start"/> and <paramref name="byteCount"/> falls outside of the bounds of the buffer content.</exception>
/// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception>
public byte[] ToArray(int start, int byteCount)
{
BlobUtilities.ValidateRange(Count, start, byteCount, nameof(byteCount));
var result = new byte[byteCount];
int chunkStart = 0;
int bufferStart = start;
int bufferEnd = start + byteCount;
foreach (var chunk in GetChunks())
{
int chunkEnd = chunkStart + chunk.Length;
Debug.Assert(bufferStart >= chunkStart);
if (chunkEnd > bufferStart)
{
int bytesToCopy = Math.Min(bufferEnd, chunkEnd) - bufferStart;
Debug.Assert(bytesToCopy >= 0);
Array.Copy(chunk._buffer, bufferStart - chunkStart, result, bufferStart - start, bytesToCopy);
bufferStart += bytesToCopy;
if (bufferStart == bufferEnd)
{
break;
}
}
chunkStart = chunkEnd;
}
Debug.Assert(bufferStart == bufferEnd);
return result;
}
/// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception>
public ImmutableArray<byte> ToImmutableArray()
{
return ToImmutableArray(0, Count);
}
/// <exception cref="ArgumentOutOfRangeException">Range specified by <paramref name="start"/> and <paramref name="byteCount"/> falls outside of the bounds of the buffer content.</exception>
/// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception>
public ImmutableArray<byte> ToImmutableArray(int start, int byteCount)
{
byte[]? array = ToArray(start, byteCount);
return ImmutableCollectionsMarshal.AsImmutableArray(array);
}
internal bool TryGetSpan(out ReadOnlySpan<byte> buffer)
{
if (_nextOrPrevious == this)
{
// If the blob builder has one chunk, we can just return it and avoid copies.
buffer = Span;
return true;
}
buffer = default;
return false;
}
/// <exception cref="ArgumentNullException"><paramref name="destination"/> is null.</exception>
/// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception>
public void WriteContentTo(Stream destination)
{
if (destination is null)
{
Throw.ArgumentNull(nameof(destination));
}
foreach (var chunk in GetChunks())
{
destination.Write(chunk._buffer, 0, chunk.Length);
}
}
/// <exception cref="ArgumentNullException"><paramref name="destination"/> is default(<see cref="BlobWriter"/>).</exception>
/// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception>
public void WriteContentTo(ref BlobWriter destination)
{
if (destination.IsDefault)
{
Throw.ArgumentNull(nameof(destination));
}
foreach (var chunk in GetChunks())
{
destination.WriteBytes(chunk.Span);
}
}
/// <exception cref="ArgumentNullException"><paramref name="destination"/> is null.</exception>
/// <exception cref="InvalidOperationException">Content is not available, the builder has been linked with another one.</exception>
public void WriteContentTo(BlobBuilder destination)
{
if (destination is null)
{
Throw.ArgumentNull(nameof(destination));
}
foreach (var chunk in GetChunks())
{
destination.WriteBytes(chunk.Span);
}
}
/// <exception cref="ArgumentNullException"><paramref name="prefix"/> is null.</exception>
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void LinkPrefix(BlobBuilder prefix)
{
if (prefix is null)
{
Throw.ArgumentNull(nameof(prefix));
}
// TODO: consider copying data from right to left while there is space
if (!prefix.IsHead || !IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}
// avoid chaining empty chunks:
if (prefix.Count == 0)
{
prefix.ClearAndFreeChunk();
return;
}
PreviousLength += prefix.Count;
// prefix is not a head anymore:
prefix._length = prefix.FrozenLength;
// First and last chunks:
//
// [PrefixFirst]->[]->[PrefixLast] <- [prefix] [First]->[]->[Last] <- [this]
// ^_________________| ^___________|
//
// Degenerate cases:
// this == First == Last and/or prefix == PrefixFirst == PrefixLast.
var first = FirstChunk;
var prefixFirst = prefix.FirstChunk;
var last = _nextOrPrevious;
var prefixLast = prefix._nextOrPrevious;
// Relink like so:
// [PrefixFirst]->[]->[PrefixLast] -> [prefix] -> [First]->[]->[Last] <- [this]
// ^________________________________________________________|
_nextOrPrevious = (last != this) ? last : prefix;
prefix._nextOrPrevious = (first != this) ? first : (prefixFirst != prefix) ? prefixFirst : prefix;
if (last != this)
{
last._nextOrPrevious = (prefixFirst != prefix) ? prefixFirst : prefix;
}
if (prefixLast != prefix)
{
prefixLast._nextOrPrevious = prefix;
}
prefix.CheckInvariants();
CheckInvariants();
}
/// <exception cref="ArgumentNullException"><paramref name="suffix"/> is null.</exception>
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void LinkSuffix(BlobBuilder suffix)
{
if (suffix is null)
{
Throw.ArgumentNull(nameof(suffix));
}
// TODO: consider copying data from right to left while there is space
if (!IsHead || !suffix.IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}
// avoid chaining empty chunks:
if (suffix.Count == 0)
{
suffix.ClearAndFreeChunk();
return;
}
bool isEmpty = Count == 0;
// swap buffers of the heads:
var suffixBuffer = suffix._buffer;
uint suffixLength = suffix._length;
int suffixPreviousLength = suffix.PreviousLength;
int oldSuffixLength = suffix.Length;
suffix._buffer = _buffer;
suffix._length = FrozenLength; // suffix is not a head anymore
_buffer = suffixBuffer;
_length = suffixLength;
PreviousLength += suffix.Length + suffixPreviousLength;
// Update the _previousLength of the suffix so that suffix.Count = suffix._previousLength + suffix.Length doesn't change.
// Note that the resulting previous length might be negative.
// The value is not used, other than for calculating the value of Count property.
suffix._previousLengthOrFrozenSuffixLengthDelta = suffixPreviousLength + oldSuffixLength - suffix.Length;
if (!isEmpty)
{
// First and last chunks:
//
// [First]->[]->[Last] <- [this] [SuffixFirst]->[]->[SuffixLast] <- [suffix]
// ^___________| ^_________________|
//
// Degenerate cases:
// this == First == Last and/or suffix == SuffixFirst == SuffixLast.
var first = FirstChunk;
var suffixFirst = suffix.FirstChunk;
var last = _nextOrPrevious;
var suffixLast = suffix._nextOrPrevious;
// Relink like so:
// [First]->[]->[Last] -> [suffix] -> [SuffixFirst]->[]->[SuffixLast] <- [this]
// ^_______________________________________________________|
_nextOrPrevious = suffixLast;
suffix._nextOrPrevious = (suffixFirst != suffix) ? suffixFirst : (first != this) ? first : suffix;
if (last != this)
{
last._nextOrPrevious = suffix;
}
if (suffixLast != suffix)
{
suffixLast._nextOrPrevious = (first != this) ? first : suffix;
}
}
CheckInvariants();
suffix.CheckInvariants();
}
private void AddLength(int value)
{
_length += (uint)value;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void Expand(int newLength)
{
// TODO: consider converting the last chunk to a smaller one if there is too much empty space left
// May happen only if the derived class attempts to write to a builder that is not last,
// or if a builder prepended to another one is not discarded.
if (!IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}
var newChunk = AllocateChunk(Math.Max(newLength, MinChunkSize));
if (newChunk.ChunkCapacity < newLength)
{
// The overridden allocator didn't provide large enough buffer:
throw new InvalidOperationException(SR.Format(SR.ReturnedBuilderSizeTooSmall, GetType(), nameof(AllocateChunk)));
}
var newBuffer = newChunk._buffer;
if (_length == 0)
{
// If the first write into an empty buffer needs more space than the buffer provides, swap the buffers.
newChunk._buffer = _buffer;
_buffer = newBuffer;
}
else
{
// Otherwise append the new buffer.
var last = _nextOrPrevious;
var first = FirstChunk;
if (last == this)
{
// single chunk in the chain
_nextOrPrevious = newChunk;
}
else
{
newChunk._nextOrPrevious = first;
last._nextOrPrevious = newChunk;
_nextOrPrevious = newChunk;
}
newChunk._buffer = _buffer;
newChunk._length = FrozenLength;
newChunk._previousLengthOrFrozenSuffixLengthDelta = PreviousLength;
_buffer = newBuffer;
PreviousLength += Length;
_length = 0;
}
CheckInvariants();
}
/// <summary>
/// Reserves a contiguous block of bytes.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative.</exception>
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public Blob ReserveBytes(int byteCount)
{
if (byteCount < 0)
{
Throw.ArgumentOutOfRange(nameof(byteCount));
}
int start = ReserveBytesImpl(byteCount);
Array.Clear(_buffer, start, byteCount);
return new Blob(_buffer, start, byteCount);
}
private int ReserveBytesImpl(int byteCount)
{
Debug.Assert(byteCount >= 0);
// If write is attempted to a frozen builder we fall back
// to expand where an exception is thrown:
uint result = _length;
if (result > _buffer.Length - byteCount)
{
Expand(byteCount);
result = 0;
}
_length = result + (uint)byteCount;
return (int)result;
}
private int ReserveBytesPrimitive(int byteCount)
{
// If the primitive doesn't fit to the current chuck we'll allocate a new chunk that is at least MinChunkSize.
// That chunk has to fit the primitive otherwise we might keep allocating new chunks and never end up with one that fits.
Debug.Assert(byteCount <= MinChunkSize);
return ReserveBytesImpl(byteCount);
}
/// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative.</exception>
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteBytes(byte value, int byteCount)
{
if (byteCount < 0)
{
Throw.ArgumentOutOfRange(nameof(byteCount));
}
if (!IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}
int bytesToCurrent = Math.Min(FreeBytes, byteCount);
_buffer.WriteBytes(Length, value, bytesToCurrent);
AddLength(bytesToCurrent);
int remaining = byteCount - bytesToCurrent;
if (remaining > 0)
{
Expand(remaining);
_buffer.WriteBytes(0, value, remaining);
AddLength(remaining);
}
}
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative.</exception>
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public unsafe void WriteBytes(byte* buffer, int byteCount)
{
if (buffer is null)
{
Throw.ArgumentNull(nameof(buffer));
}
if (byteCount < 0)
{
Throw.ArgumentOutOfRange(nameof(byteCount));
}
if (!IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}
WriteBytesUnchecked(new ReadOnlySpan<byte>(buffer, byteCount));
}
private void WriteBytesUnchecked(ReadOnlySpan<byte> buffer)
{
int bytesToCurrent = Math.Min(FreeBytes, buffer.Length);
buffer.Slice(0, bytesToCurrent).CopyTo(_buffer.AsSpan(Length));
AddLength(bytesToCurrent);
ReadOnlySpan<byte> remaining = buffer.Slice(bytesToCurrent);
if (!remaining.IsEmpty)
{
Expand(remaining.Length);
remaining.CopyTo(_buffer);
AddLength(remaining.Length);
}
}
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative.</exception>
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
/// <returns>Bytes successfully written from the <paramref name="source" />.</returns>
public int TryWriteBytes(Stream source, int byteCount)
{
if (source is null)
{
Throw.ArgumentNull(nameof(source));
}
if (byteCount < 0)
{
throw new ArgumentOutOfRangeException(nameof(byteCount));
}
if (byteCount == 0)
{
return 0;
}
int bytesRead = 0;
int bytesToCurrent = Math.Min(FreeBytes, byteCount);
if (bytesToCurrent > 0)
{
bytesRead = source.TryReadAll(_buffer, Length, bytesToCurrent);
AddLength(bytesRead);
if (bytesRead != bytesToCurrent)
{
return bytesRead;
}
}
int remaining = byteCount - bytesToCurrent;
if (remaining > 0)
{
Expand(remaining);
bytesRead = source.TryReadAll(_buffer, 0, remaining);
AddLength(bytesRead);
bytesRead += bytesToCurrent;
}
return bytesRead;
}
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception>
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteBytes(ImmutableArray<byte> buffer)
{
if (buffer.IsDefault)
{
Throw.ArgumentNull(nameof(buffer));
}
WriteBytes(buffer.AsSpan());
}
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Range specified by <paramref name="start"/> and <paramref name="byteCount"/> falls outside of the bounds of the <paramref name="buffer"/>.</exception>
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteBytes(ImmutableArray<byte> buffer, int start, int byteCount)
{
if (buffer.IsDefault)
{
Throw.ArgumentNull(nameof(buffer));
}
BlobUtilities.ValidateRange(buffer.Length, start, byteCount, nameof(byteCount));
WriteBytes(buffer.AsSpan(start, byteCount));
}
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception>
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteBytes(byte[] buffer)
{
if (buffer is null)
{
Throw.ArgumentNull(nameof(buffer));
}
WriteBytes(buffer.AsSpan());
}
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Range specified by <paramref name="start"/> and <paramref name="byteCount"/> falls outside of the bounds of the <paramref name="buffer"/>.</exception>
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteBytes(byte[] buffer, int start, int byteCount)
{
if (buffer is null)
{
Throw.ArgumentNull(nameof(buffer));
}
BlobUtilities.ValidateRange(buffer.Length, start, byteCount, nameof(byteCount));
WriteBytes(buffer.AsSpan(start, byteCount));
}
internal void WriteBytes(ReadOnlySpan<byte> buffer)
{
if (!IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}
WriteBytesUnchecked(buffer);
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void PadTo(int position)
{
WriteBytes(0, position - Count);
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void Align(int alignment)
{
int position = Count;
WriteBytes(0, BitArithmetic.Align(position, alignment) - position);
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteBoolean(bool value)
{
WriteByte((byte)(value ? 1 : 0));
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteByte(byte value)
{
int start = ReserveBytesPrimitive(sizeof(byte));
_buffer[start] = value;
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteSByte(sbyte value)
{
WriteByte(unchecked((byte)value));
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteDouble(double value)
{
int start = ReserveBytesPrimitive(sizeof(double));
_buffer.WriteDouble(start, value);
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteSingle(float value)
{
int start = ReserveBytesPrimitive(sizeof(float));
_buffer.WriteSingle(start, value);
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteInt16(short value)
{
WriteUInt16(unchecked((ushort)value));
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteUInt16(ushort value)
{
int start = ReserveBytesPrimitive(sizeof(ushort));
_buffer.WriteUInt16(start, value);
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteInt16BE(short value)
{
WriteUInt16BE(unchecked((ushort)value));
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteUInt16BE(ushort value)
{
int start = ReserveBytesPrimitive(sizeof(ushort));
_buffer.WriteUInt16BE(start, value);
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteInt32BE(int value)
{
WriteUInt32BE(unchecked((uint)value));
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteUInt32BE(uint value)
{
int start = ReserveBytesPrimitive(sizeof(uint));
_buffer.WriteUInt32BE(start, value);
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteInt32(int value)
{
WriteUInt32(unchecked((uint)value));
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteUInt32(uint value)
{
int start = ReserveBytesPrimitive(sizeof(uint));
_buffer.WriteUInt32(start, value);
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteInt64(long value)
{
WriteUInt64(unchecked((ulong)value));
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteUInt64(ulong value)
{
int start = ReserveBytesPrimitive(sizeof(ulong));
_buffer.WriteUInt64(start, value);
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteDecimal(decimal value)
{
int start = ReserveBytesPrimitive(BlobUtilities.SizeOfSerializedDecimal);
_buffer.WriteDecimal(start, value);
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteGuid(Guid value)
{
int start = ReserveBytesPrimitive(BlobUtilities.SizeOfGuid);
_buffer.WriteGuid(start, value);
}
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteDateTime(DateTime value)
{
WriteInt64(value.Ticks);
}
/// <summary>
/// Writes a reference to a heap (heap offset) or a table (row number).
/// </summary>
/// <param name="reference">Heap offset or table row number.</param>
/// <param name="isSmall">True to encode the reference as 16-bit integer, false to encode as 32-bit integer.</param>
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteReference(int reference, bool isSmall)
{
// This code is a very hot path, hence we don't check if the reference actually fits 2B.
if (isSmall)
{
Debug.Assert(unchecked((ushort)reference) == reference);
WriteUInt16((ushort)reference);
}
else
{
WriteInt32(reference);
}
}
/// <summary>
/// Writes UTF-16 (little-endian) encoded string at the current position.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception>
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteUTF16(char[] value)
{
if (value is null)
{
Throw.ArgumentNull(nameof(value));
}
if (!IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}
WriteUTF16(value.AsSpan());
}
/// <summary>
/// Writes UTF-16 (little-endian) encoded string at the current position.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception>
/// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception>
public void WriteUTF16(string value)
{
if (value is null)
{
Throw.ArgumentNull(nameof(value));
}
if (!IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}
WriteUTF16(value.AsSpan());
}
private void WriteUTF16(ReadOnlySpan<char> value)
{
if (!IsHead)
{
Throw.InvalidOperationBuilderAlreadyLinked();
}