This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
StringBuilder.cs
2160 lines (1915 loc) · 93.3 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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
**
** Purpose: implementation of the StringBuilder
** class.
**
===========================================================*/
namespace System.Text {
using System.Text;
using System.Runtime;
using System.Runtime.Serialization;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Threading;
using System.Globalization;
using System.Diagnostics.Contracts;
// 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.
//
// When passing null into a constructor in VJ and VC, the null
// should be explicitly type cast.
// For Example:
// StringBuilder sb1 = new StringBuilder((StringBuilder)null);
// StringBuilder sb2 = new StringBuilder((String)null);
// Console.WriteLine(sb1);
// Console.WriteLine(sb2);
//
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public sealed 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.
//
//
// CLASS VARIABLES
//
//
internal char[] m_ChunkChars; // The characters in this block
internal StringBuilder m_ChunkPrevious; // Link to the block logically before this block
internal int m_ChunkLength; // The index in m_ChunkChars that represent the end of the block
internal int m_ChunkOffset; // The logial offset (sum of all characters in previous blocks)
internal int m_MaxCapacity = 0;
//
//
// STATIC CONSTANTS
//
//
internal const int DefaultCapacity = 16;
private const String CapacityField = "Capacity";
private const String MaxCapacityField = "m_MaxCapacity";
private const String StringValueField = "m_StringValue";
private const String ThreadIDField = "m_currentThread";
// 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;
//
//
//CONSTRUCTORS
//
//
// Creates a new empty string builder (i.e., it represents String.Empty)
// with the default capacity (16 characters).
public StringBuilder()
: this(DefaultCapacity) {
}
// Create a new empty string builder (i.e., it represents String.Empty)
// with the specified capacity.
public StringBuilder(int capacity)
: this(String.Empty, capacity) {
}
// Creates a new string builder from the specified string. If value
// is a null String (i.e., if it represents String.NullString)
// then the new string builder will also be null (i.e., it will also represent
// String.NullString).
//
public StringBuilder(String value)
: this(value, DefaultCapacity) {
}
// Creates a new string builder from the specified string with the specified
// capacity. If value is a null String (i.e., if it represents
// String.NullString) then the new string builder will also be null
// (i.e., it will also represent String.NullString).
// The maximum number of characters this string may contain is set by capacity.
//
public StringBuilder(String value, int capacity)
: this(value, 0, ((value != null) ? value.Length : 0), capacity) {
}
// Creates a new string builder from the specifed substring with the specified
// capacity. The maximum number of characters is set by capacity.
//
[System.Security.SecuritySafeCritical] // auto-generated
public StringBuilder(String value, int startIndex, int length, int capacity) {
if (capacity<0) {
throw new ArgumentOutOfRangeException("capacity",
Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", "capacity"));
}
if (length<0) {
throw new ArgumentOutOfRangeException("length",
Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", "length"));
}
if (startIndex<0) {
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
Contract.EndContractBlock();
if (value == null) {
value = String.Empty;
}
if (startIndex > value.Length - length) {
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
}
m_MaxCapacity = Int32.MaxValue;
if (capacity == 0) {
capacity = DefaultCapacity;
}
if (capacity < length)
capacity = length;
m_ChunkChars = new char[capacity];
m_ChunkLength = length;
unsafe {
fixed (char* sourcePtr = value)
ThreadSafeCopy(sourcePtr + startIndex, m_ChunkChars, 0, length);
}
}
// Creates an empty StringBuilder with a minimum capacity of capacity
// and a maximum capacity of maxCapacity.
public StringBuilder(int capacity, int maxCapacity) {
if (capacity>maxCapacity) {
throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
}
if (maxCapacity<1) {
throw new ArgumentOutOfRangeException("maxCapacity", Environment.GetResourceString("ArgumentOutOfRange_SmallMaxCapacity"));
}
if (capacity<0) {
throw new ArgumentOutOfRangeException("capacity",
Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", "capacity"));
}
Contract.EndContractBlock();
if (capacity == 0) {
capacity = Math.Min(DefaultCapacity, maxCapacity);
}
m_MaxCapacity = maxCapacity;
m_ChunkChars = new char[capacity];
}
#if FEATURE_SERIALIZATION
[System.Security.SecurityCritical] // auto-generated
private StringBuilder(SerializationInfo info, StreamingContext context) {
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
int persistedCapacity = 0;
string persistedString = null;
int persistedMaxCapacity = Int32.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 forward compatibility.
break;
}
}
// Check values and set defaults
if (persistedString == null) {
persistedString = String.Empty;
}
if (persistedMaxCapacity < 1 || persistedString.Length > persistedMaxCapacity) {
throw new SerializationException(Environment.GetResourceString("Serialization_StringBuilderMaxCapacity"));
}
if (!capacityPresent) {
// StringBuilder in V1.X did not persist the Capacity, so this is a valid legacy code path.
persistedCapacity = DefaultCapacity;
if (persistedCapacity < persistedString.Length) {
persistedCapacity = persistedString.Length;
}
if (persistedCapacity > persistedMaxCapacity) {
persistedCapacity = persistedMaxCapacity;
}
}
if (persistedCapacity < 0 || persistedCapacity < persistedString.Length || persistedCapacity > persistedMaxCapacity) {
throw new SerializationException(Environment.GetResourceString("Serialization_StringBuilderCapacity"));
}
// Assign
m_MaxCapacity = persistedMaxCapacity;
m_ChunkChars = new char[persistedCapacity];
persistedString.CopyTo(0, m_ChunkChars, 0, persistedString.Length);
m_ChunkLength = persistedString.Length;
m_ChunkPrevious = null;
VerifyClassInvariant();
}
[System.Security.SecurityCritical] // auto-generated
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info==null) {
throw new ArgumentNullException("info");
}
Contract.EndContractBlock();
VerifyClassInvariant();
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);
}
#endif //FEATURE_SERIALIZATION
[System.Diagnostics.Conditional("_DEBUG")]
private void VerifyClassInvariant() {
BCLDebug.Correctness((uint)(m_ChunkOffset + m_ChunkChars.Length) >= m_ChunkOffset, "Integer Overflow");
StringBuilder currentBlock = this;
int maxCapacity = this.m_MaxCapacity;
for (; ; )
{
// All blocks have copy of the maxCapacity.
Contract.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity");
Contract.Assert(currentBlock.m_ChunkChars != null, "Empty Buffer");
Contract.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length, "Out of range length");
Contract.Assert(currentBlock.m_ChunkLength >= 0, "Negative length");
Contract.Assert(currentBlock.m_ChunkOffset >= 0, "Negative offset");
StringBuilder prevBlock = currentBlock.m_ChunkPrevious;
if (prevBlock == null)
{
Contract.Assert(currentBlock.m_ChunkOffset == 0, "First chunk's offset is not 0");
break;
}
// There are no gaps in the blocks.
Contract.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength, "There is a gap between chunks!");
currentBlock = prevBlock;
}
}
public int Capacity {
get { return m_ChunkChars.Length + m_ChunkOffset; }
set {
if (value < 0) {
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
}
if (value > MaxCapacity) {
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
}
if (value < Length) {
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
}
Contract.EndContractBlock();
if (Capacity != value) {
int newLen = value - m_ChunkOffset;
char[] newArray = new char[newLen];
Array.Copy(m_ChunkChars, newArray, m_ChunkLength);
m_ChunkChars = newArray;
}
}
}
public int MaxCapacity {
get { return m_MaxCapacity; }
}
// Read-Only Property
// Ensures that the capacity of this string builder is at least the specified value.
// If capacity is greater than the capacity of this string builder, then the capacity
// is set to capacity; otherwise the capacity is unchanged.
//
public int EnsureCapacity(int capacity) {
if (capacity < 0) {
throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
}
Contract.EndContractBlock();
if (Capacity < capacity)
Capacity = capacity;
return Capacity;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
VerifyClassInvariant();
if (Length == 0)
return String.Empty;
string ret = string.FastAllocateString(Length);
StringBuilder chunk = this;
unsafe {
fixed (char* destinationPtr = ret)
{
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) <= ret.Length && (uint)chunkLength <= (uint)sourceArray.Length)
{
fixed (char* sourcePtr = sourceArray)
string.wstrcpy(destinationPtr + chunkOffset, sourcePtr, chunkLength);
}
else
{
throw new ArgumentOutOfRangeException("chunkLength", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
}
chunk = chunk.m_ChunkPrevious;
} while (chunk != null);
}
}
return ret;
}
// Converts a substring of this string builder to a String.
[System.Security.SecuritySafeCritical] // auto-generated
public String ToString(int startIndex, int length) {
Contract.Ensures(Contract.Result<String>() != null);
int currentLength = this.Length;
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
if (startIndex > currentLength)
{
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndexLargerThanLength"));
}
if (length < 0)
{
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
if (startIndex > (currentLength - length))
{
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
}
VerifyClassInvariant();
StringBuilder chunk = this;
int sourceEndIndex = startIndex + length;
string ret = string.FastAllocateString(length);
int curDestIndex = length;
unsafe {
fixed (char* destinationPtr = ret)
{
while (curDestIndex > 0)
{
int chunkEndIndex = sourceEndIndex - chunk.m_ChunkOffset;
if (chunkEndIndex >= 0)
{
if (chunkEndIndex > chunk.m_ChunkLength)
chunkEndIndex = chunk.m_ChunkLength;
int countLeft = curDestIndex;
int chunkCount = countLeft;
int chunkStartIndex = chunkEndIndex - countLeft;
if (chunkStartIndex < 0)
{
chunkCount += chunkStartIndex;
chunkStartIndex = 0;
}
curDestIndex -= chunkCount;
if (chunkCount > 0)
{
// work off of local variables so that they are stable even in the presence of race conditions
char[] sourceArray = chunk.m_ChunkChars;
// Check that we will not overrun our boundaries.
if ((uint)(chunkCount + curDestIndex) <= length && (uint)(chunkCount + chunkStartIndex) <= (uint)sourceArray.Length)
{
fixed (char* sourcePtr = &sourceArray[chunkStartIndex])
string.wstrcpy(destinationPtr + curDestIndex, sourcePtr, chunkCount);
}
else
{
throw new ArgumentOutOfRangeException("chunkCount", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
}
}
chunk = chunk.m_ChunkPrevious;
}
}
}
return ret;
}
// Convenience method for sb.Length=0;
public StringBuilder Clear() {
this.Length = 0;
return this;
}
// Sets the length of the String in this buffer. If length is less than the current
// instance, the StringBuilder is truncated. If length is greater than the current
// instance, nulls are appended. The capacity is adjusted to be the same as the length.
public int Length {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
return m_ChunkOffset + m_ChunkLength;
}
set {
//If the new length is less than 0 or greater than our Maximum capacity, bail.
if (value<0) {
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
if (value>MaxCapacity) {
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
}
Contract.EndContractBlock();
int originalCapacity = Capacity;
if (value == 0 && m_ChunkPrevious == null)
{
m_ChunkLength = 0;
m_ChunkOffset = 0;
Contract.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
return;
}
int delta = value - Length;
// if the specified length is greater than the current length
if (delta > 0)
{
// the end of the string value of the current StringBuilder object is padded with the Unicode NULL character
Append('\0', delta); // We could improve on this, but who does this anyway?
}
// if the specified length is less than or equal to the current length
else
{
StringBuilder chunk = FindChunkForIndex(value);
if (chunk != this)
{
// we crossed a chunk boundary when reducing the Length, we must replace this middle-chunk with a new
// larger chunk to ensure the original capacity is preserved
int newLen = originalCapacity - chunk.m_ChunkOffset;
char[] newArray = new char[newLen];
Contract.Assert(newLen > chunk.m_ChunkChars.Length, "the new chunk should be larger than the one it is replacing");
Array.Copy(chunk.m_ChunkChars, newArray, chunk.m_ChunkLength);
m_ChunkChars = newArray;
m_ChunkPrevious = chunk.m_ChunkPrevious;
m_ChunkOffset = chunk.m_ChunkOffset;
}
m_ChunkLength = value - chunk.m_ChunkOffset;
VerifyClassInvariant();
}
Contract.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
}
}
[System.Runtime.CompilerServices.IndexerName("Chars")]
public char this[int index] {
get {
StringBuilder chunk = this;
for (; ; )
{
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;
for (; ; )
{
int indexInBlock = index - chunk.m_ChunkOffset;
if (indexInBlock >= 0)
{
if (indexInBlock >= chunk.m_ChunkLength)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
chunk.m_ChunkChars[indexInBlock] = value;
return;
}
chunk = chunk.m_ChunkPrevious;
if (chunk == null)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
}
}
// Appends a character at the end of this string builder. The capacity is adjusted as needed.
public StringBuilder Append(char value, int repeatCount) {
if (repeatCount<0) {
throw new ArgumentOutOfRangeException("repeatCount", Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
}
Contract.Ensures(Contract.Result<StringBuilder>() != null);
Contract.EndContractBlock();
if (repeatCount==0) {
return this;
}
int idx = m_ChunkLength;
while (repeatCount > 0)
{
if (idx < m_ChunkChars.Length)
{
m_ChunkChars[idx++] = value;
--repeatCount;
}
else
{
m_ChunkLength = idx;
ExpandByABlock(repeatCount);
Contract.Assert(m_ChunkLength == 0, "Expand should create a new block");
idx = 0;
}
}
m_ChunkLength = idx;
VerifyClassInvariant();
return this;
}
// Appends an array of characters at the end of this string builder. The capacity is adjusted as needed.
[System.Security.SecuritySafeCritical] // auto-generated
public StringBuilder Append(char[] value, int startIndex, int charCount) {
// in NetCF arguments pretty much don't matter as long as count is 0
// we need to check this twice, as this is a contract area and we can't return from here
#if FEATURE_LEGACYNETCF
if (startIndex < 0 && !(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8 && (charCount == 0))) {
#else
if (startIndex < 0) {
#endif //FEATURE_LEGACYNETCF
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
if (charCount<0) {
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
#if !FEATURE_LEGACYNETCF // Avoid contract problems with compat switch above.
Contract.Ensures(Contract.Result<StringBuilder>() != null);
Contract.EndContractBlock();
#endif
// in NetCF arguments pretty much don't matter as long as count is 0
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8 && (charCount == 0))
{
return this;
}
if (value == null) {
if (startIndex == 0 && charCount == 0) {
return this;
}
throw new ArgumentNullException("value");
}
if (charCount > value.Length - startIndex) {
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (charCount==0) {
return this;
}
unsafe {
fixed (char* valueChars = &value[startIndex])
Append(valueChars, charCount);
}
return this;
}
// Appends a copy of this string at the end of this string builder.
[System.Security.SecuritySafeCritical] // auto-generated
public StringBuilder Append(String value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
if (value != null) {
// This is a hand specialization of the 'AppendHelper' code below.
// We could have just called AppendHelper.
char[] chunkChars = m_ChunkChars;
int chunkLength = m_ChunkLength;
int valueLen = value.Length;
int newCurrentIndex = chunkLength + valueLen;
if (newCurrentIndex < chunkChars.Length) // Use strictly < to avoid issue if count == 0, newIndex == length
{
if (valueLen <= 2)
{
if (valueLen > 0)
chunkChars[chunkLength] = value[0];
if (valueLen > 1)
chunkChars[chunkLength + 1] = value[1];
}
else
{
unsafe {
fixed (char* valuePtr = value)
fixed (char* destPtr = &chunkChars[chunkLength])
string.wstrcpy(destPtr, valuePtr, valueLen);
}
}
m_ChunkLength = newCurrentIndex;
}
else
AppendHelper(value);
}
return this;
}
// We put this fixed in its own helper to avoid the cost zero initing valueChars in the
// case we don't actually use it.
[System.Security.SecuritySafeCritical] // auto-generated
private void AppendHelper(string value) {
unsafe {
fixed (char* valueChars = value)
Append(valueChars, value.Length);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[SecurityCritical]
internal unsafe extern void ReplaceBufferInternal(char* newBuffer, int newLength);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[SecurityCritical]
internal unsafe extern void ReplaceBufferAnsiInternal(sbyte* newBuffer, int newLength);
// Appends a copy of the characters in value from startIndex to startIndex +
// count at the end of this string builder.
[System.Security.SecuritySafeCritical] // auto-generated
public StringBuilder Append(String value, int startIndex, int count) {
// in NetCF arguments pretty much don't matter as long as count is 0
// we need to check this twice, as this is a contract area and we can't return from here
#if FEATURE_LEGACYNETCF
if (startIndex < 0 && !(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8 && (count == 0))) {
#else
if (startIndex < 0) {
#endif //FEATURE_LEGACYNETCF
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (count < 0) {
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
#if !FEATURE_LEGACYNETCF // The use of CompatibilitySwitches above prevents us from marking this as a precondition.
Contract.Ensures(Contract.Result<StringBuilder>() != null);
#endif
// in NetCF arguments pretty much don't matter as long as count is 0
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8 && (count == 0)){
return this;
}
//If the value being added is null, eat the null
//and return.
if (value == null) {
if (startIndex == 0 && count == 0) {
return this;
}
throw new ArgumentNullException("value");
}
if (count == 0) {
return this;
}
if (startIndex > value.Length - count) {
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
unsafe {
fixed (char* valueChars = value)
Append(valueChars + startIndex, count);
}
return this;
}
[System.Runtime.InteropServices.ComVisible(false)]
public StringBuilder AppendLine() {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(Environment.NewLine);
}
[System.Runtime.InteropServices.ComVisible(false)]
public StringBuilder AppendLine(string value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
Append(value);
return Append(Environment.NewLine);
}
[System.Runtime.InteropServices.ComVisible(false)]
[SecuritySafeCritical]
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) {
if (destination == null) {
throw new ArgumentNullException("destination");
}
if (count < 0) {
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("Arg_NegativeArgCount"));
}
if (destinationIndex < 0) {
throw new ArgumentOutOfRangeException("destinationIndex",
Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", "destinationIndex"));
}
if (destinationIndex > destination.Length - count) {
throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_OffsetOut"));
}
if ((uint)sourceIndex > (uint)Length) {
throw new ArgumentOutOfRangeException("sourceIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (sourceIndex > Length - count) {
throw new ArgumentException(Environment.GetResourceString("Arg_LongerThanSrcString"));
}
Contract.EndContractBlock();
VerifyClassInvariant();
StringBuilder chunk = this;
int sourceEndIndex = sourceIndex + count;
int curDestIndex = destinationIndex + count;
while (count > 0)
{
int chunkEndIndex = sourceEndIndex - chunk.m_ChunkOffset;
if (chunkEndIndex >= 0)
{
if (chunkEndIndex > chunk.m_ChunkLength)
chunkEndIndex = chunk.m_ChunkLength;
int chunkCount = count;
int chunkStartIndex = chunkEndIndex - count;
if (chunkStartIndex < 0)
{
chunkCount += chunkStartIndex;
chunkStartIndex = 0;
}
curDestIndex -= chunkCount;
count -= chunkCount;
// SafeCritical: we ensure that chunkStartIndex + chunkCount are within range of m_chunkChars
// as well as ensuring that curDestIndex + chunkCount are within range of destination
ThreadSafeCopy(chunk.m_ChunkChars, chunkStartIndex, destination, curDestIndex, chunkCount);
}
chunk = chunk.m_ChunkPrevious;
}
}
// Inserts multiple copies of a string into this string builder at the specified position.
// Existing characters are shifted to make room for the new text.
// The capacity is adjusted as needed. If value equals String.Empty, this
// string builder is not changed.
//
[System.Security.SecuritySafeCritical] // auto-generated
public StringBuilder Insert(int index, String value, int count) {
if (count < 0) {
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.Ensures(Contract.Result<StringBuilder>() != null);
Contract.EndContractBlock();
//Range check the index.
int currentLength = Length;
if ((uint)index > (uint)currentLength) {
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
//If value is null, empty or count is 0, do nothing. This is ECMA standard.
if (value == null || value.Length == 0 || 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 inserted characters.
long insertingChars = (long) value.Length * count;
if (insertingChars > MaxCapacity - this.Length) {
throw new OutOfMemoryException();
}
Contract.Assert(insertingChars + this.Length < Int32.MaxValue);
StringBuilder chunk;
int indexInChunk;
MakeRoom(index, (int) insertingChars, out chunk, out indexInChunk, false);
unsafe {
fixed (char* valuePtr = value) {
while (count > 0)
{
ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, valuePtr, value.Length);
--count;
}
}
}
return this;
}
// Removes the specified characters from this string builder.
// The length of this string builder is reduced by
// length, but the capacity is unaffected.
//
public StringBuilder Remove(int startIndex, int length) {
if (length<0) {
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
if (startIndex<0) {
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
if (length > Length - startIndex) {
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.Ensures(Contract.Result<StringBuilder>() != null);
Contract.EndContractBlock();
if (Length == length && startIndex == 0) {
// Optimization. If we are deleting everything
Length = 0;
return this;
}
if (length > 0)
{
StringBuilder chunk;
int indexInChunk;
Remove(startIndex, length, out chunk, out indexInChunk);
}
return this;
}
//
// PUBLIC INSTANCE FUNCTIONS
//
//
/*====================================Append====================================
**
==============================================================================*/
// Appends a boolean to the end of this string builder.
// The capacity is adjusted as needed.
public StringBuilder Append(bool value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString());
}
// Appends an sbyte to this string builder.
// The capacity is adjusted as needed.
[CLSCompliant(false)]
public StringBuilder Append(sbyte value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
// Appends a ubyte to this string builder.
// The capacity is adjusted as needed.
public StringBuilder Append(byte value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
// Appends a character at the end of this string builder. The capacity is adjusted as needed.
public StringBuilder Append(char value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
if (m_ChunkLength < m_ChunkChars.Length)
m_ChunkChars[m_ChunkLength++] = value;
else
Append(value, 1);
return this;
}
// Appends a short to this string builder.
// The capacity is adjusted as needed.
public StringBuilder Append(short value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
// Appends an int to this string builder.
// The capacity is adjusted as needed.
public StringBuilder Append(int value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
// Appends a long to this string builder.
// The capacity is adjusted as needed.
public StringBuilder Append(long value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
// Appends a float to this string builder.
// The capacity is adjusted as needed.
public StringBuilder Append(float value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
// Appends a double to this string builder.
// The capacity is adjusted as needed.
public StringBuilder Append(double value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
public StringBuilder Append(decimal value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
// Appends an ushort to this string builder.
// The capacity is adjusted as needed.
[CLSCompliant(false)]
public StringBuilder Append(ushort value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
// Appends an uint to this string builder.
// The capacity is adjusted as needed.
[CLSCompliant(false)]
public StringBuilder Append(uint value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
// Appends an unsigned long to this string builder.
// The capacity is adjusted as needed.
[CLSCompliant(false)]
public StringBuilder Append(ulong value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
// Appends an Object to this string builder.
// The capacity is adjusted as needed.
public StringBuilder Append(Object value) {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
if (null==value) {
//Appending null is now a no-op.
return this;