/
StringBuilder.cs
3048 lines (2653 loc) · 134 KB
/
StringBuilder.cs
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.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace System.Text
{
// This class represents a mutable string. It is convenient for situations in
// which it is desirable to modify a string, perhaps by removing, replacing, or
// inserting characters, without creating a new String subsequent to
// each modification.
//
// The methods contained within this class do not return a new StringBuilder
// object unless specified otherwise. This class may be used in conjunction with the String
// class to carry out modifications upon strings.
[Serializable]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed partial class StringBuilder : ISerializable
{
// A StringBuilder is internally represented as a linked list of blocks each of which holds
// a chunk of the string. It turns out string as a whole can also be represented as just a chunk,
// so that is what we do.
/// <summary>
/// The character buffer for this chunk.
/// </summary>
internal char[] m_ChunkChars;
/// <summary>
/// The chunk that logically precedes this chunk.
/// </summary>
internal StringBuilder? m_ChunkPrevious;
/// <summary>
/// The number of characters in this chunk.
/// This is the number of elements in <see cref="m_ChunkChars"/> that are in use, from the start of the buffer.
/// </summary>
internal int m_ChunkLength;
/// <summary>
/// The logical offset of this chunk's characters in the string it is a part of.
/// This is the sum of the number of characters in preceding blocks.
/// </summary>
internal int m_ChunkOffset;
/// <summary>
/// The maximum capacity this builder is allowed to have.
/// </summary>
internal int m_MaxCapacity;
/// <summary>
/// The default capacity of a <see cref="StringBuilder"/>.
/// </summary>
internal const int DefaultCapacity = 16;
private const string CapacityField = "Capacity"; // Do not rename (binary serialization)
private const string MaxCapacityField = "m_MaxCapacity"; // Do not rename (binary serialization)
private const string StringValueField = "m_StringValue"; // Do not rename (binary serialization)
private const string ThreadIDField = "m_currentThread"; // Do not rename (binary serialization)
// We want to keep chunk arrays out of large object heap (< 85K bytes ~ 40K chars) to be sure.
// Making the maximum chunk size big means less allocation code called, but also more waste
// in unused characters and slower inserts / replaces (since you do need to slide characters over
// within a buffer).
internal const int MaxChunkSize = 8000;
/// <summary>
/// Initializes a new instance of the <see cref="StringBuilder"/> class.
/// </summary>
public StringBuilder()
{
m_MaxCapacity = int.MaxValue;
m_ChunkChars = new char[DefaultCapacity];
}
/// <summary>
/// Initializes a new instance of the <see cref="StringBuilder"/> class.
/// </summary>
/// <param name="capacity">The initial capacity of this builder.</param>
public StringBuilder(int capacity)
: this(capacity, int.MaxValue)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StringBuilder"/> class.
/// </summary>
/// <param name="value">The initial contents of this builder.</param>
public StringBuilder(string? value)
: this(value, DefaultCapacity)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StringBuilder"/> class.
/// </summary>
/// <param name="value">The initial contents of this builder.</param>
/// <param name="capacity">The initial capacity of this builder.</param>
public StringBuilder(string? value, int capacity)
: this(value, 0, value?.Length ?? 0, capacity)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StringBuilder"/> class.
/// </summary>
/// <param name="value">The initial contents of this builder.</param>
/// <param name="startIndex">The index to start in <paramref name="value"/>.</param>
/// <param name="length">The number of characters to read in <paramref name="value"/>.</param>
/// <param name="capacity">The initial capacity of this builder.</param>
public StringBuilder(string? value, int startIndex, int length, int capacity)
{
ArgumentOutOfRangeException.ThrowIfNegative(capacity);
ArgumentOutOfRangeException.ThrowIfNegative(length);
ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
value ??= string.Empty;
if (startIndex > value.Length - length)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength);
}
m_MaxCapacity = int.MaxValue;
if (capacity == 0)
{
capacity = DefaultCapacity;
}
capacity = Math.Max(capacity, length);
m_ChunkChars = GC.AllocateUninitializedArray<char>(capacity);
m_ChunkLength = length;
value.AsSpan(startIndex, length).CopyTo(m_ChunkChars);
}
/// <summary>
/// Initializes a new instance of the <see cref="StringBuilder"/> class.
/// </summary>
/// <param name="capacity">The initial capacity of this builder.</param>
/// <param name="maxCapacity">The maximum capacity of this builder.</param>
public StringBuilder(int capacity, int maxCapacity)
{
if (capacity > maxCapacity)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity);
}
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxCapacity);
ArgumentOutOfRangeException.ThrowIfNegative(capacity);
if (capacity == 0)
{
capacity = Math.Min(DefaultCapacity, maxCapacity);
}
m_MaxCapacity = maxCapacity;
m_ChunkChars = GC.AllocateUninitializedArray<char>(capacity);
}
private StringBuilder(SerializationInfo info, StreamingContext context)
{
ArgumentNullException.ThrowIfNull(info);
int persistedCapacity = 0;
string? persistedString = null;
int persistedMaxCapacity = int.MaxValue;
bool capacityPresent = false;
// Get the data
SerializationInfoEnumerator enumerator = info.GetEnumerator();
while (enumerator.MoveNext())
{
switch (enumerator.Name)
{
case MaxCapacityField:
persistedMaxCapacity = info.GetInt32(MaxCapacityField);
break;
case StringValueField:
persistedString = info.GetString(StringValueField);
break;
case CapacityField:
persistedCapacity = info.GetInt32(CapacityField);
capacityPresent = true;
break;
default:
// Ignore other fields for forwards-compatibility.
break;
}
}
// Check values and set defaults
persistedString ??= string.Empty;
if (persistedMaxCapacity < 1 || persistedString.Length > persistedMaxCapacity)
{
throw new SerializationException(SR.Serialization_StringBuilderMaxCapacity);
}
if (!capacityPresent)
{
// StringBuilder in V1.X did not persist the Capacity, so this is a valid legacy code path.
persistedCapacity = Math.Min(Math.Max(DefaultCapacity, persistedString.Length), persistedMaxCapacity);
}
if (persistedCapacity < 0 || persistedCapacity < persistedString.Length || persistedCapacity > persistedMaxCapacity)
{
throw new SerializationException(SR.Serialization_StringBuilderCapacity);
}
// Assign
m_MaxCapacity = persistedMaxCapacity;
m_ChunkChars = GC.AllocateUninitializedArray<char>(persistedCapacity);
persistedString.CopyTo(0, m_ChunkChars, 0, persistedString.Length);
m_ChunkLength = persistedString.Length;
AssertInvariants();
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
ArgumentNullException.ThrowIfNull(info);
AssertInvariants();
info.AddValue(MaxCapacityField, m_MaxCapacity);
info.AddValue(CapacityField, Capacity);
info.AddValue(StringValueField, ToString());
// Note: persist "m_currentThread" to be compatible with old versions
info.AddValue(ThreadIDField, 0);
}
[Conditional("DEBUG")]
private void AssertInvariants()
{
Debug.Assert(m_ChunkOffset + m_ChunkChars.Length >= m_ChunkOffset, "The length of the string is greater than int.MaxValue.");
StringBuilder currentBlock = this;
int maxCapacity = this.m_MaxCapacity;
while (true)
{
// All blocks have the same max capacity.
Debug.Assert(currentBlock.m_MaxCapacity == maxCapacity);
Debug.Assert(currentBlock.m_ChunkChars != null);
Debug.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length);
Debug.Assert(currentBlock.m_ChunkLength >= 0);
Debug.Assert(currentBlock.m_ChunkOffset >= 0);
StringBuilder? prevBlock = currentBlock.m_ChunkPrevious;
if (prevBlock == null)
{
Debug.Assert(currentBlock.m_ChunkOffset == 0);
break;
}
// There are no gaps in the blocks.
Debug.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength);
currentBlock = prevBlock;
}
}
public int Capacity
{
get => m_ChunkChars.Length + m_ChunkOffset;
set
{
ArgumentOutOfRangeException.ThrowIfNegative(value);
if (value > MaxCapacity)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_Capacity);
}
if (value < Length)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
}
if (Capacity != value)
{
int newLen = value - m_ChunkOffset;
char[] newArray = GC.AllocateUninitializedArray<char>(newLen);
Array.Copy(m_ChunkChars, newArray, m_ChunkLength);
m_ChunkChars = newArray;
}
}
}
/// <summary>
/// Gets the maximum capacity this builder is allowed to have.
/// </summary>
public int MaxCapacity => m_MaxCapacity;
/// <summary>
/// Ensures that the capacity of this builder is at least the specified value.
/// </summary>
/// <param name="capacity">The new capacity for this builder.</param>
/// <remarks>
/// If <paramref name="capacity"/> is less than or equal to the current capacity of
/// this builder, the capacity remains unchanged.
/// </remarks>
public int EnsureCapacity(int capacity)
{
ArgumentOutOfRangeException.ThrowIfNegative(capacity);
if (Capacity < capacity)
{
Capacity = capacity;
}
return Capacity;
}
public override string ToString()
{
AssertInvariants();
if (Length == 0)
{
return string.Empty;
}
string result = string.FastAllocateString(Length);
StringBuilder? chunk = this;
do
{
if (chunk.m_ChunkLength > 0)
{
// Copy these into local variables so that they are stable even in the presence of race conditions
char[] sourceArray = chunk.m_ChunkChars;
int chunkOffset = chunk.m_ChunkOffset;
int chunkLength = chunk.m_ChunkLength;
// Check that we will not overrun our boundaries.
if ((uint)(chunkLength + chunkOffset) > (uint)result.Length || (uint)chunkLength > (uint)sourceArray.Length)
{
throw new ArgumentOutOfRangeException(nameof(chunkLength), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
}
Buffer.Memmove(
ref Unsafe.Add(ref result.GetRawStringData(), chunkOffset),
ref MemoryMarshal.GetArrayDataReference(sourceArray),
(nuint)chunkLength);
}
chunk = chunk.m_ChunkPrevious;
}
while (chunk != null);
return result;
}
/// <summary>
/// Creates a string from a substring of this builder.
/// </summary>
/// <param name="startIndex">The index to start in this builder.</param>
/// <param name="length">The number of characters to read in this builder.</param>
public string ToString(int startIndex, int length)
{
int currentLength = this.Length;
ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
if (startIndex > currentLength)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndexLargerThanLength);
}
ArgumentOutOfRangeException.ThrowIfNegative(length);
if (startIndex > currentLength - length)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength);
}
AssertInvariants();
string result = string.FastAllocateString(length);
CopyTo(startIndex, new Span<char>(ref result.GetRawStringData(), result.Length), result.Length);
return result;
}
public StringBuilder Clear()
{
this.Length = 0;
return this;
}
/// <summary>
/// Gets or sets the length of this builder.
/// </summary>
public int Length
{
get => m_ChunkOffset + m_ChunkLength;
set
{
// If the new length is less than 0 or greater than our Maximum capacity, bail.
ArgumentOutOfRangeException.ThrowIfNegative(value);
if (value > MaxCapacity)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
}
if (value == 0 && m_ChunkPrevious == null)
{
m_ChunkLength = 0;
m_ChunkOffset = 0;
return;
}
int delta = value - Length;
if (delta > 0)
{
// Pad ourselves with null characters.
Append('\0', delta);
}
else
{
StringBuilder chunk = FindChunkForIndex(value);
if (chunk != this)
{
// Avoid possible infinite capacity growth. See https://github.com/dotnet/coreclr/pull/16926
int capacityToPreserve = Math.Min(Capacity, Math.Max(Length * 6 / 5, m_ChunkChars.Length));
int newLen = capacityToPreserve - chunk.m_ChunkOffset;
if (newLen > chunk.m_ChunkChars.Length)
{
// We crossed a chunk boundary when reducing the Length. We must replace this middle-chunk with a new larger chunk,
// to ensure the capacity we want is preserved.
char[] newArray = GC.AllocateUninitializedArray<char>(newLen);
Array.Copy(chunk.m_ChunkChars, newArray, chunk.m_ChunkLength);
m_ChunkChars = newArray;
}
else
{
// Special case where the capacity we want to keep corresponds exactly to the size of the content.
// Just take ownership of the array.
Debug.Assert(newLen == chunk.m_ChunkChars.Length, "The new chunk should be larger or equal to the one it is replacing.");
m_ChunkChars = chunk.m_ChunkChars;
}
m_ChunkPrevious = chunk.m_ChunkPrevious;
m_ChunkOffset = chunk.m_ChunkOffset;
}
m_ChunkLength = value - chunk.m_ChunkOffset;
AssertInvariants();
}
Debug.Assert(Length == value, "Something went wrong setting Length.");
}
}
[IndexerName("Chars")]
public char this[int index]
{
get
{
StringBuilder? chunk = this;
while (true)
{
int indexInBlock = index - chunk.m_ChunkOffset;
if (indexInBlock >= 0)
{
if (indexInBlock >= chunk.m_ChunkLength)
{
throw new IndexOutOfRangeException();
}
return chunk.m_ChunkChars[indexInBlock];
}
chunk = chunk.m_ChunkPrevious;
if (chunk == null)
{
throw new IndexOutOfRangeException();
}
}
}
set
{
StringBuilder? chunk = this;
while (true)
{
int indexInBlock = index - chunk.m_ChunkOffset;
if (indexInBlock >= 0)
{
if (indexInBlock >= chunk.m_ChunkLength)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLess);
}
chunk.m_ChunkChars[indexInBlock] = value;
return;
}
chunk = chunk.m_ChunkPrevious;
if (chunk == null)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLess);
}
}
}
}
/// <summary>
/// GetChunks returns ChunkEnumerator that follows the IEnumerable pattern and
/// thus can be used in a C# 'foreach' statements to retrieve the data in the StringBuilder
/// as chunks (ReadOnlyMemory) of characters. An example use is:
///
/// foreach (ReadOnlyMemory<char> chunk in sb.GetChunks())
/// foreach (char c in chunk.Span)
/// { /* operation on c }
///
/// It is undefined what happens if the StringBuilder is modified while the chunk
/// enumeration is incomplete. StringBuilder is also not thread-safe, so operating
/// on it with concurrent threads is illegal. Finally the ReadOnlyMemory chunks returned
/// are NOT guaranteed to remain unchanged if the StringBuilder is modified, so do
/// not cache them for later use either. This API's purpose is efficiently extracting
/// the data of a CONSTANT StringBuilder.
///
/// Creating a ReadOnlySpan from a ReadOnlyMemory (the .Span property) is expensive
/// compared to the fetching of the character, so create a local variable for the SPAN
/// if you need to use it in a nested for statement. For example
///
/// foreach (ReadOnlyMemory<char> chunk in sb.GetChunks())
/// {
/// var span = chunk.Span;
/// for (int i = 0; i < span.Length; i++)
/// { /* operation on span[i] */ }
/// }
/// </summary>
public ChunkEnumerator GetChunks() => new ChunkEnumerator(this);
/// <summary>
/// ChunkEnumerator supports both the IEnumerable and IEnumerator pattern so foreach
/// works (see GetChunks). It needs to be public (so the compiler can use it
/// when building a foreach statement) but users typically don't use it explicitly.
/// (which is why it is a nested type).
/// </summary>
public struct ChunkEnumerator
{
private readonly StringBuilder _firstChunk; // The first Stringbuilder chunk (which is the end of the logical string)
private StringBuilder? _currentChunk; // The chunk that this enumerator is currently returning (Current).
private readonly ManyChunkInfo? _manyChunks; // Only used for long string builders with many chunks (see constructor)
/// <summary>
/// Implement IEnumerable.GetEnumerator() to return 'this' as the IEnumerator
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)] // Only here to make foreach work
public ChunkEnumerator GetEnumerator() { return this; }
/// <summary>
/// Implements the IEnumerator pattern.
/// </summary>
public bool MoveNext()
{
if (_currentChunk == _firstChunk)
{
return false;
}
if (_manyChunks != null)
{
return _manyChunks.MoveNext(ref _currentChunk);
}
StringBuilder next = _firstChunk;
while (next.m_ChunkPrevious != _currentChunk)
{
Debug.Assert(next.m_ChunkPrevious != null);
next = next.m_ChunkPrevious;
}
_currentChunk = next;
return true;
}
/// <summary>
/// Implements the IEnumerator pattern.
/// </summary>
public ReadOnlyMemory<char> Current
{
get
{
if (_currentChunk == null)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return new ReadOnlyMemory<char>(_currentChunk.m_ChunkChars, 0, _currentChunk.m_ChunkLength);
}
}
#region private
internal ChunkEnumerator(StringBuilder stringBuilder)
{
Debug.Assert(stringBuilder != null);
_firstChunk = stringBuilder;
_currentChunk = null; // MoveNext will find the last chunk if we do this.
_manyChunks = null;
// There is a performance-vs-allocation tradeoff. Because the chunks
// are a linked list with each chunk pointing to its PREDECESSOR, walking
// the list FORWARD is not efficient. If there are few chunks (< 8) we
// simply scan from the start each time, and tolerate the N*N behavior.
// However above this size, we allocate an array to hold reference to all
// the chunks and we can be efficient for large N.
int chunkCount = ChunkCount(stringBuilder);
if (8 < chunkCount)
{
_manyChunks = new ManyChunkInfo(stringBuilder, chunkCount);
}
}
private static int ChunkCount(StringBuilder? stringBuilder)
{
int ret = 0;
while (stringBuilder != null)
{
ret++;
stringBuilder = stringBuilder.m_ChunkPrevious;
}
return ret;
}
/// <summary>
/// Used to hold all the chunks indexes when you have many chunks.
/// </summary>
private sealed class ManyChunkInfo
{
private readonly StringBuilder[] _chunks; // These are in normal order (first chunk first)
private int _chunkPos;
public bool MoveNext(ref StringBuilder? current)
{
int pos = ++_chunkPos;
if (_chunks.Length <= pos)
{
return false;
}
current = _chunks[pos];
return true;
}
public ManyChunkInfo(StringBuilder? stringBuilder, int chunkCount)
{
_chunks = new StringBuilder[chunkCount];
while (0 <= --chunkCount)
{
Debug.Assert(stringBuilder != null);
_chunks[chunkCount] = stringBuilder;
stringBuilder = stringBuilder.m_ChunkPrevious;
}
_chunkPos = -1;
}
}
#endregion
}
/// <summary>
/// Appends a character 0 or more times to the end of this builder.
/// </summary>
/// <param name="value">The character to append.</param>
/// <param name="repeatCount">The number of times to append <paramref name="value"/>.</param>
public StringBuilder Append(char value, int repeatCount)
{
ArgumentOutOfRangeException.ThrowIfNegative(repeatCount);
if (repeatCount == 0)
{
return this;
}
char[] chunkChars = m_ChunkChars;
int chunkLength = m_ChunkLength;
// Try to fit the whole repeatCount in the current chunk
// Use the same check as Span<T>.Slice for 64-bit so it can be folded
// Since repeatCount can't be negative, there's no risk for it to overflow on 32 bit
if (((nuint)(uint)chunkLength + (nuint)(uint)repeatCount) <= (nuint)(uint)chunkChars.Length)
{
chunkChars.AsSpan(chunkLength, repeatCount).Fill(value);
m_ChunkLength += repeatCount;
}
else
{
AppendWithExpansion(value, repeatCount);
}
AssertInvariants();
return this;
}
private void AppendWithExpansion(char value, int repeatCount)
{
Debug.Assert(repeatCount > 0, "Invalid length; should have been validated by caller.");
// Check if the repeatCount will put us over m_MaxCapacity
if ((uint)(repeatCount + Length) > (uint)m_MaxCapacity)
{
throw new ArgumentOutOfRangeException(nameof(repeatCount), SR.ArgumentOutOfRange_LengthGreaterThanCapacity);
}
char[] chunkChars = m_ChunkChars;
int chunkLength = m_ChunkLength;
// Fill the rest of the current chunk
int firstLength = chunkChars.Length - chunkLength;
if (firstLength > 0)
{
chunkChars.AsSpan(chunkLength, firstLength).Fill(value);
m_ChunkLength = chunkChars.Length;
}
// Expand the builder to add another chunk
int restLength = repeatCount - firstLength;
ExpandByABlock(restLength);
Debug.Assert(m_ChunkLength == 0, "A new block was not created.");
// Fill the new chunk with the remaining part of repeatCount
m_ChunkChars.AsSpan(0, restLength).Fill(value);
m_ChunkLength = restLength;
}
/// <summary>
/// Appends a range of characters to the end of this builder.
/// </summary>
/// <param name="value">The characters to append.</param>
/// <param name="startIndex">The index to start in <paramref name="value"/>.</param>
/// <param name="charCount">The number of characters to read in <paramref name="value"/>.</param>
public StringBuilder Append(char[]? value, int startIndex, int charCount)
{
ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
ArgumentOutOfRangeException.ThrowIfNegative(charCount);
if (value == null)
{
if (startIndex == 0 && charCount == 0)
{
return this;
}
ArgumentNullException.Throw(nameof(value));
}
if (charCount > value.Length - startIndex)
{
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
}
if (charCount != 0)
{
Append(ref value[startIndex], charCount);
}
return this;
}
/// <summary>
/// Appends a string to the end of this builder.
/// </summary>
/// <param name="value">The string to append.</param>
public StringBuilder Append(string? value)
{
if (value is not null)
{
Append(ref value.GetRawStringData(), value.Length);
}
return this;
}
/// <summary>
/// Appends part of a string to the end of this builder.
/// </summary>
/// <param name="value">The string to append.</param>
/// <param name="startIndex">The index to start in <paramref name="value"/>.</param>
/// <param name="count">The number of characters to read in <paramref name="value"/>.</param>
public StringBuilder Append(string? value, int startIndex, int count)
{
ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
ArgumentOutOfRangeException.ThrowIfNegative(count);
if (value == null)
{
if (startIndex == 0 && count == 0)
{
return this;
}
ArgumentNullException.Throw(nameof(value));
}
if (count != 0)
{
if (startIndex > value.Length - count)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
}
Append(ref Unsafe.Add(ref value.GetRawStringData(), startIndex), count);
}
return this;
}
public StringBuilder Append(StringBuilder? value)
{
if (value != null && value.Length != 0)
{
return AppendCore(value, 0, value.Length);
}
return this;
}
public StringBuilder Append(StringBuilder? value, int startIndex, int count)
{
ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
ArgumentOutOfRangeException.ThrowIfNegative(count);
if (value == null)
{
if (startIndex == 0 && count == 0)
{
return this;
}
ArgumentNullException.Throw(nameof(value));
}
if (count == 0)
{
return this;
}
if (count > value.Length - startIndex)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
}
return AppendCore(value, startIndex, count);
}
private StringBuilder AppendCore(StringBuilder value, int startIndex, int count)
{
if (value == this)
{
return Append(value.ToString(startIndex, count));
}
int newLength = Length + count;
if ((uint)newLength > (uint)m_MaxCapacity)
{
throw new ArgumentOutOfRangeException(nameof(Capacity), SR.ArgumentOutOfRange_Capacity);
}
while (count > 0)
{
int length = Math.Min(m_ChunkChars.Length - m_ChunkLength, count);
if (length == 0)
{
ExpandByABlock(count);
length = Math.Min(m_ChunkChars.Length - m_ChunkLength, count);
}
value.CopyTo(startIndex, new Span<char>(m_ChunkChars, m_ChunkLength, length), length);
m_ChunkLength += length;
startIndex += length;
count -= length;
}
return this;
}
public StringBuilder AppendLine() => Append(Environment.NewLine);
public StringBuilder AppendLine(string? value)
{
Append(value);
return Append(Environment.NewLine);
}
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
{
ArgumentNullException.ThrowIfNull(destination);
ArgumentOutOfRangeException.ThrowIfNegative(destinationIndex);
if (destinationIndex > destination.Length - count)
{
throw new ArgumentException(SR.ArgumentOutOfRange_OffsetOut);
}
CopyTo(sourceIndex, new Span<char>(destination).Slice(destinationIndex), count);
}
public void CopyTo(int sourceIndex, Span<char> destination, int count)
{
ArgumentOutOfRangeException.ThrowIfNegative(count);
if ((uint)sourceIndex > (uint)Length)
{
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
}
if (sourceIndex > Length - count)
{
throw new ArgumentException(SR.Arg_LongerThanSrcString);
}
AssertInvariants();
StringBuilder? chunk = this;
int sourceEndIndex = sourceIndex + count;
int curDestIndex = count;
while (count > 0)
{
Debug.Assert(chunk != null);
int chunkEndIndex = sourceEndIndex - chunk.m_ChunkOffset;
if (chunkEndIndex >= 0)
{
chunkEndIndex = Math.Min(chunkEndIndex, chunk.m_ChunkLength);
int chunkCount = count;
int chunkStartIndex = chunkEndIndex - count;
if (chunkStartIndex < 0)
{
chunkCount += chunkStartIndex;
chunkStartIndex = 0;
}
curDestIndex -= chunkCount;
count -= chunkCount;
new ReadOnlySpan<char>(chunk.m_ChunkChars, chunkStartIndex, chunkCount).CopyTo(destination.Slice(curDestIndex));
}
chunk = chunk.m_ChunkPrevious;
}
}
/// <summary>
/// Inserts a string 0 or more times into this builder at the specified position.
/// </summary>
/// <param name="index">The index to insert in this builder.</param>
/// <param name="value">The string to insert.</param>
/// <param name="count">The number of times to insert the string.</param>
public StringBuilder Insert(int index, string? value, int count) => Insert(index, value.AsSpan(), count);
private StringBuilder Insert(int index, ReadOnlySpan<char> value, int count)
{
ArgumentOutOfRangeException.ThrowIfNegative(count);
int currentLength = Length;
if ((uint)index > (uint)currentLength)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
}
if (value.IsEmpty || count == 0)
{
return this;
}
// Ensure we don't insert more chars than we can hold, and we don't
// have any integer overflow in our new length.
long insertingChars = (long)value.Length * count;
if (insertingChars > MaxCapacity - this.Length)
{
throw new OutOfMemoryException();
}
Debug.Assert(insertingChars + this.Length < int.MaxValue);
MakeRoom(index, (int)insertingChars, out StringBuilder chunk, out int indexInChunk, false);
while (count > 0)
{
ReplaceInPlaceAtChunk(ref chunk!, ref indexInChunk, ref MemoryMarshal.GetReference(value), value.Length);
--count;
}
return this;
}
/// <summary>
/// Removes a range of characters from this builder.
/// </summary>
/// <remarks>
/// This method does not reduce the capacity of this builder.
/// </remarks>
public StringBuilder Remove(int startIndex, int length)
{
ArgumentOutOfRangeException.ThrowIfNegative(length);
ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
if (length > Length - startIndex)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
}
if (Length == length && startIndex == 0)
{
Length = 0;
return this;
}
if (length > 0)
{
Remove(startIndex, length, out _, out _);
}
return this;
}
#pragma warning disable CA1830 // Prefer strongly-typed Append and Insert method overloads on StringBuilder. No need to fix for the builder itself
public StringBuilder Append(bool value) => Append(value.ToString());
#pragma warning restore CA1830