/
String.Manipulation.cs
2380 lines (1983 loc) · 95.6 KB
/
String.Manipulation.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.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Text;
namespace System
{
public partial class String
{
// Avoid paying the init cost of all the SearchValues unless they are actually used.
internal static class SearchValuesStorage
{
/// <summary>
/// SearchValues would use SpanHelpers.IndexOfAnyValueType for 5 values in this case.
/// No need to allocate the SearchValues as a regular Span.IndexOfAny will use the same implementation.
/// </summary>
public const string NewLineCharsExceptLineFeed = "\r\f\u0085\u2028\u2029";
/// <summary>
/// The Unicode Standard, Sec. 5.8, Recommendation R4 and Table 5-2 state that the CR, LF,
/// CRLF, NEL, LS, FF, and PS sequences are considered newline functions. That section
/// also specifically excludes VT from the list of newline functions, so we do not include
/// it in the needle list.
/// </summary>
public static readonly SearchValues<char> NewLineChars =
SearchValues.Create(NewLineCharsExceptLineFeed + "\n");
}
internal const int StackallocIntBufferSizeLimit = 128;
internal const int StackallocCharBufferSizeLimit = 256;
private static void CopyStringContent(string dest, int destPos, string src)
{
Debug.Assert(dest != null);
Debug.Assert(src != null);
Debug.Assert(src.Length <= dest.Length - destPos);
Buffer.Memmove(
destination: ref Unsafe.Add(ref dest._firstChar, destPos),
source: ref src._firstChar,
elementCount: (uint)src.Length);
}
public static string Concat(object? arg0) =>
arg0?.ToString() ?? Empty;
public static string Concat(object? arg0, object? arg1) =>
Concat(arg0?.ToString(), arg1?.ToString());
public static string Concat(object? arg0, object? arg1, object? arg2) =>
Concat(arg0?.ToString(), arg1?.ToString(), arg2?.ToString());
public static string Concat(params object?[] args)
{
ArgumentNullException.ThrowIfNull(args);
if (args.Length <= 1)
{
return args.Length == 0 ?
Empty :
args[0]?.ToString() ?? Empty;
}
// We need to get an intermediary string array
// to fill with each of the args' ToString(),
// and then just concat that in one operation.
// This way we avoid any intermediary string representations,
// or buffer resizing if we use StringBuilder (although the
// latter case is partially alleviated due to StringBuilder's
// linked-list style implementation)
var strings = new string[args.Length];
int totalLength = 0;
for (int i = 0; i < args.Length; i++)
{
object? value = args[i];
string toString = value?.ToString() ?? Empty; // We need to handle both the cases when value or value.ToString() is null
strings[i] = toString;
totalLength += toString.Length;
if (totalLength < 0) // Check for a positive overflow
{
ThrowHelper.ThrowOutOfMemoryException_StringTooLong();
}
}
// If all of the ToStrings are null/empty, just return string.Empty
if (totalLength == 0)
{
return Empty;
}
string result = FastAllocateString(totalLength);
int position = 0; // How many characters we've copied so far
for (int i = 0; i < strings.Length; i++)
{
string s = strings[i];
Debug.Assert(s != null);
Debug.Assert(position <= totalLength - s.Length, "We didn't allocate enough space for the result string!");
CopyStringContent(result, position, s);
position += s.Length;
}
return result;
}
public static string Concat<T>(IEnumerable<T> values) =>
JoinCore(ReadOnlySpan<char>.Empty, values);
public static string Concat(IEnumerable<string?> values)
{
ArgumentNullException.ThrowIfNull(values);
using (IEnumerator<string?> en = values.GetEnumerator())
{
if (!en.MoveNext())
return Empty;
string? firstValue = en.Current;
if (!en.MoveNext())
{
return firstValue ?? Empty;
}
var result = new ValueStringBuilder(stackalloc char[StackallocCharBufferSizeLimit]);
result.Append(firstValue);
do
{
result.Append(en.Current);
}
while (en.MoveNext());
return result.ToString();
}
}
public static string Concat(string? str0, string? str1)
{
if (IsNullOrEmpty(str0))
{
if (IsNullOrEmpty(str1))
{
return Empty;
}
return str1;
}
if (IsNullOrEmpty(str1))
{
return str0;
}
int str0Length = str0.Length;
int totalLength = str0Length + str1.Length;
// Can't overflow to a positive number so just check < 0
if (totalLength < 0)
{
ThrowHelper.ThrowOutOfMemoryException_StringTooLong();
}
string result = FastAllocateString(totalLength);
CopyStringContent(result, 0, str0);
CopyStringContent(result, str0Length, str1);
return result;
}
public static string Concat(string? str0, string? str1, string? str2)
{
if (IsNullOrEmpty(str0))
{
return Concat(str1, str2);
}
if (IsNullOrEmpty(str1))
{
return Concat(str0, str2);
}
if (IsNullOrEmpty(str2))
{
return Concat(str0, str1);
}
// It can overflow to a positive number so we accumulate the total length as a long.
long totalLength = (long)str0.Length + (long)str1.Length + (long)str2.Length;
if (totalLength > int.MaxValue)
{
ThrowHelper.ThrowOutOfMemoryException_StringTooLong();
}
string result = FastAllocateString((int)totalLength);
CopyStringContent(result, 0, str0);
CopyStringContent(result, str0.Length, str1);
CopyStringContent(result, str0.Length + str1.Length, str2);
return result;
}
public static string Concat(string? str0, string? str1, string? str2, string? str3)
{
if (IsNullOrEmpty(str0))
{
return Concat(str1, str2, str3);
}
if (IsNullOrEmpty(str1))
{
return Concat(str0, str2, str3);
}
if (IsNullOrEmpty(str2))
{
return Concat(str0, str1, str3);
}
if (IsNullOrEmpty(str3))
{
return Concat(str0, str1, str2);
}
// It can overflow to a positive number so we accumulate the total length as a long.
long totalLength = (long)str0.Length + (long)str1.Length + (long)str2.Length + (long)str3.Length;
if (totalLength > int.MaxValue)
{
ThrowHelper.ThrowOutOfMemoryException_StringTooLong();
}
string result = FastAllocateString((int)totalLength);
CopyStringContent(result, 0, str0);
CopyStringContent(result, str0.Length, str1);
CopyStringContent(result, str0.Length + str1.Length, str2);
CopyStringContent(result, str0.Length + str1.Length + str2.Length, str3);
return result;
}
public static string Concat(ReadOnlySpan<char> str0, ReadOnlySpan<char> str1)
{
int length = checked(str0.Length + str1.Length);
if (length == 0)
{
return Empty;
}
string result = FastAllocateString(length);
Span<char> resultSpan = new Span<char>(ref result._firstChar, result.Length);
str0.CopyTo(resultSpan);
str1.CopyTo(resultSpan.Slice(str0.Length));
return result;
}
public static string Concat(ReadOnlySpan<char> str0, ReadOnlySpan<char> str1, ReadOnlySpan<char> str2)
{
int length = checked(str0.Length + str1.Length + str2.Length);
if (length == 0)
{
return Empty;
}
string result = FastAllocateString(length);
Span<char> resultSpan = new Span<char>(ref result._firstChar, result.Length);
str0.CopyTo(resultSpan);
resultSpan = resultSpan.Slice(str0.Length);
str1.CopyTo(resultSpan);
resultSpan = resultSpan.Slice(str1.Length);
str2.CopyTo(resultSpan);
return result;
}
public static string Concat(ReadOnlySpan<char> str0, ReadOnlySpan<char> str1, ReadOnlySpan<char> str2, ReadOnlySpan<char> str3)
{
int length = checked(str0.Length + str1.Length + str2.Length + str3.Length);
if (length == 0)
{
return Empty;
}
string result = FastAllocateString(length);
Span<char> resultSpan = new Span<char>(ref result._firstChar, result.Length);
str0.CopyTo(resultSpan);
resultSpan = resultSpan.Slice(str0.Length);
str1.CopyTo(resultSpan);
resultSpan = resultSpan.Slice(str1.Length);
str2.CopyTo(resultSpan);
resultSpan = resultSpan.Slice(str2.Length);
str3.CopyTo(resultSpan);
return result;
}
internal static string Concat(ReadOnlySpan<char> str0, ReadOnlySpan<char> str1, ReadOnlySpan<char> str2, ReadOnlySpan<char> str3, ReadOnlySpan<char> str4)
{
int length = checked(str0.Length + str1.Length + str2.Length + str3.Length + str4.Length);
if (length == 0)
{
return Empty;
}
string result = FastAllocateString(length);
Span<char> resultSpan = new Span<char>(ref result._firstChar, result.Length);
str0.CopyTo(resultSpan);
resultSpan = resultSpan.Slice(str0.Length);
str1.CopyTo(resultSpan);
resultSpan = resultSpan.Slice(str1.Length);
str2.CopyTo(resultSpan);
resultSpan = resultSpan.Slice(str2.Length);
str3.CopyTo(resultSpan);
resultSpan = resultSpan.Slice(str3.Length);
str4.CopyTo(resultSpan);
return result;
}
public static string Concat(params string?[] values)
{
ArgumentNullException.ThrowIfNull(values);
if (values.Length <= 1)
{
return values.Length == 0 ?
Empty :
values[0] ?? Empty;
}
// It's possible that the input values array could be changed concurrently on another
// thread, such that we can't trust that each read of values[i] will be equivalent.
// Worst case, we can make a defensive copy of the array and use that, but we first
// optimistically try the allocation and copies assuming that the array isn't changing,
// which represents the 99.999% case, in particular since string.Concat is used for
// string concatenation by the languages, with the input array being a params array.
// Sum the lengths of all input strings
long totalLengthLong = 0;
for (int i = 0; i < values.Length; i++)
{
string? value = values[i];
if (value != null)
{
totalLengthLong += value.Length;
}
}
// If it's too long, fail, or if it's empty, return an empty string.
if (totalLengthLong > int.MaxValue)
{
ThrowHelper.ThrowOutOfMemoryException_StringTooLong();
}
int totalLength = (int)totalLengthLong;
if (totalLength == 0)
{
return Empty;
}
// Allocate a new string and copy each input string into it
string result = FastAllocateString(totalLength);
int copiedLength = 0;
for (int i = 0; i < values.Length; i++)
{
string? value = values[i];
if (!IsNullOrEmpty(value))
{
int valueLen = value.Length;
if (valueLen > totalLength - copiedLength)
{
copiedLength = -1;
break;
}
CopyStringContent(result, copiedLength, value);
copiedLength += valueLen;
}
}
// If we copied exactly the right amount, return the new string. Otherwise,
// something changed concurrently to mutate the input array: fall back to
// doing the concatenation again, but this time with a defensive copy. This
// fall back should be extremely rare.
return copiedLength == totalLength ? result : Concat((string?[])values.Clone());
}
public static string Format([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, object? arg0)
{
return FormatHelper(null, format, new ReadOnlySpan<object?>(in arg0));
}
public static string Format([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, object? arg0, object? arg1)
{
TwoObjects two = new TwoObjects(arg0, arg1);
return FormatHelper(null, format, MemoryMarshal.CreateReadOnlySpan(ref two.Arg0, 2));
}
public static string Format([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, object? arg0, object? arg1, object? arg2)
{
ThreeObjects three = new ThreeObjects(arg0, arg1, arg2);
return FormatHelper(null, format, MemoryMarshal.CreateReadOnlySpan(ref three.Arg0, 3));
}
public static string Format([StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, params object?[] args)
{
if (args is null)
{
// To preserve the original exception behavior, throw an exception about format if both
// args and format are null. The actual null check for format is in FormatHelper.
ArgumentNullException.Throw(format is null ? nameof(format) : nameof(args));
}
return FormatHelper(null, format, args);
}
public static string Format(IFormatProvider? provider, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, object? arg0)
{
return FormatHelper(provider, format, new ReadOnlySpan<object?>(in arg0));
}
public static string Format(IFormatProvider? provider, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, object? arg0, object? arg1)
{
TwoObjects two = new TwoObjects(arg0, arg1);
return FormatHelper(provider, format, MemoryMarshal.CreateReadOnlySpan(ref two.Arg0, 2));
}
public static string Format(IFormatProvider? provider, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, object? arg0, object? arg1, object? arg2)
{
ThreeObjects three = new ThreeObjects(arg0, arg1, arg2);
return FormatHelper(provider, format, MemoryMarshal.CreateReadOnlySpan(ref three.Arg0, 3));
}
public static string Format(IFormatProvider? provider, [StringSyntax(StringSyntaxAttribute.CompositeFormat)] string format, params object?[] args)
{
if (args is null)
{
// To preserve the original exception behavior, throw an exception about format if both
// args and format are null. The actual null check for format is in FormatHelper.
ArgumentNullException.Throw(format is null ? nameof(format) : nameof(args));
}
return FormatHelper(provider, format, args);
}
private static string FormatHelper(IFormatProvider? provider, string format, ReadOnlySpan<object?> args)
{
ArgumentNullException.ThrowIfNull(format);
var sb = new ValueStringBuilder(stackalloc char[StackallocCharBufferSizeLimit]);
sb.EnsureCapacity(format.Length + args.Length * 8);
sb.AppendFormatHelper(provider, format, args);
return sb.ToString();
}
/// <summary>
/// Replaces the format item or items in a <see cref="CompositeFormat"/> with the string representation of the corresponding objects.
/// A parameter supplies culture-specific formatting information.
/// </summary>
/// <typeparam name="TArg0">The type of the first object to format.</typeparam>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A <see cref="CompositeFormat"/>.</param>
/// <param name="arg0">The first object to format.</param>
/// <returns>The formatted string.</returns>
/// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception>
/// <exception cref="FormatException">The index of a format item is greater than or equal to the number of supplied arguments.</exception>
public static string Format<TArg0>(IFormatProvider? provider, CompositeFormat format, TArg0 arg0)
{
ArgumentNullException.ThrowIfNull(format);
format.ValidateNumberOfArgs(1);
return Format(provider, format, arg0, 0, 0, default);
}
/// <summary>
/// Replaces the format item or items in a <see cref="CompositeFormat"/> with the string representation of the corresponding objects.
/// A parameter supplies culture-specific formatting information.
/// </summary>
/// <typeparam name="TArg0">The type of the first object to format.</typeparam>
/// <typeparam name="TArg1">The type of the second object to format.</typeparam>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A <see cref="CompositeFormat"/>.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <returns>The formatted string.</returns>
/// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception>
/// <exception cref="FormatException">The index of a format item is greater than or equal to the number of supplied arguments.</exception>
public static string Format<TArg0, TArg1>(IFormatProvider? provider, CompositeFormat format, TArg0 arg0, TArg1 arg1)
{
ArgumentNullException.ThrowIfNull(format);
format.ValidateNumberOfArgs(2);
return Format(provider, format, arg0, arg1, 0, default);
}
/// <summary>
/// Replaces the format item or items in a <see cref="CompositeFormat"/> with the string representation of the corresponding objects.
/// A parameter supplies culture-specific formatting information.
/// </summary>
/// <typeparam name="TArg0">The type of the first object to format.</typeparam>
/// <typeparam name="TArg1">The type of the second object to format.</typeparam>
/// <typeparam name="TArg2">The type of the third object to format.</typeparam>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A <see cref="CompositeFormat"/>.</param>
/// <param name="arg0">The first object to format.</param>
/// <param name="arg1">The second object to format.</param>
/// <param name="arg2">The third object to format.</param>
/// <returns>The formatted string.</returns>
/// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception>
/// <exception cref="FormatException">The index of a format item is greater than or equal to the number of supplied arguments.</exception>
public static string Format<TArg0, TArg1, TArg2>(IFormatProvider? provider, CompositeFormat format, TArg0 arg0, TArg1 arg1, TArg2 arg2)
{
ArgumentNullException.ThrowIfNull(format);
format.ValidateNumberOfArgs(3);
return Format(provider, format, arg0, arg1, arg2, default);
}
/// <summary>
/// Replaces the format item or items in a <see cref="CompositeFormat"/> with the string representation of the corresponding objects.
/// A parameter supplies culture-specific formatting information.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A <see cref="CompositeFormat"/>.</param>
/// <param name="args">An array of objects to format.</param>
/// <returns>The formatted string.</returns>
/// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="args"/> is null.</exception>
/// <exception cref="FormatException">The index of a format item is greater than or equal to the number of supplied arguments.</exception>
public static string Format(IFormatProvider? provider, CompositeFormat format, params object?[] args)
{
ArgumentNullException.ThrowIfNull(format);
ArgumentNullException.ThrowIfNull(args);
return Format(provider, format, (ReadOnlySpan<object?>)args);
}
/// <summary>
/// Replaces the format item or items in a <see cref="CompositeFormat"/> with the string representation of the corresponding objects.
/// A parameter supplies culture-specific formatting information.
/// </summary>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <param name="format">A <see cref="CompositeFormat"/>.</param>
/// <param name="args">A span of objects to format.</param>
/// <returns>The formatted string.</returns>
/// <exception cref="ArgumentNullException"><paramref name="format"/> is null.</exception>
/// <exception cref="FormatException">The index of a format item is greater than or equal to the number of supplied arguments.</exception>
public static string Format(IFormatProvider? provider, CompositeFormat format, ReadOnlySpan<object?> args)
{
ArgumentNullException.ThrowIfNull(format);
format.ValidateNumberOfArgs(args.Length);
return args.Length switch
{
0 => format.Format,
1 => Format(provider, format, args[0], 0, 0, args),
2 => Format(provider, format, args[0], args[1], 0, args),
_ => Format(provider, format, args[0], args[1], args[2], args),
};
}
private static string Format<TArg0, TArg1, TArg2>(IFormatProvider? provider, CompositeFormat format, TArg0 arg0, TArg1 arg1, TArg2 arg2, ReadOnlySpan<object?> args)
{
// If there's no formatting to be done, we can just return the original format string as the result.
if (format._formattedCount == 0)
{
return format.Format;
}
// Create the interpolated string handler.
var handler = new DefaultInterpolatedStringHandler(format._literalLength, format._formattedCount, provider, stackalloc char[StackallocCharBufferSizeLimit]);
// Format each segment.
foreach ((string? Literal, int ArgIndex, int Alignment, string? Format) segment in format._segments)
{
if (segment.Literal is string literal)
{
handler.AppendLiteral(literal);
}
else
{
int index = segment.ArgIndex;
switch (index)
{
case 0:
handler.AppendFormatted(arg0, segment.Alignment, segment.Format);
break;
case 1:
handler.AppendFormatted(arg1, segment.Alignment, segment.Format);
break;
case 2:
handler.AppendFormatted(arg2, segment.Alignment, segment.Format);
break;
default:
Debug.Assert(index > 2);
handler.AppendFormatted(args[index], segment.Alignment, segment.Format);
break;
}
}
}
// Complete the operation.
return handler.ToStringAndClear();
}
public string Insert(int startIndex, string value)
{
ArgumentNullException.ThrowIfNull(value);
ArgumentOutOfRangeException.ThrowIfGreaterThan((uint)startIndex, (uint)Length, nameof(startIndex));
int oldLength = Length;
int insertLength = value.Length;
if (oldLength == 0)
return value;
if (insertLength == 0)
return this;
// In case this computation overflows, newLength will be negative and FastAllocateString throws OutOfMemoryException
int newLength = oldLength + insertLength;
string result = FastAllocateString(newLength);
Buffer.Memmove(ref result._firstChar, ref _firstChar, (nuint)startIndex);
Buffer.Memmove(ref Unsafe.Add(ref result._firstChar, startIndex), ref value._firstChar, (nuint)insertLength);
Buffer.Memmove(ref Unsafe.Add(ref result._firstChar, startIndex + insertLength), ref Unsafe.Add(ref _firstChar, startIndex), (nuint)(oldLength - startIndex));
return result;
}
public static string Join(char separator, params string?[] value)
{
if (value == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
return JoinCore(new ReadOnlySpan<char>(in separator), new ReadOnlySpan<string?>(value));
}
public static string Join(string? separator, params string?[] value)
{
if (value == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
return JoinCore(separator.AsSpan(), new ReadOnlySpan<string?>(value));
}
public static string Join(char separator, string?[] value, int startIndex, int count) =>
JoinCore(new ReadOnlySpan<char>(in separator), value, startIndex, count);
public static string Join(string? separator, string?[] value, int startIndex, int count) =>
JoinCore(separator.AsSpan(), value, startIndex, count);
private static string JoinCore(ReadOnlySpan<char> separator, string?[] value, int startIndex, int count)
{
ArgumentNullException.ThrowIfNull(value);
ArgumentOutOfRangeException.ThrowIfNegative(startIndex);
ArgumentOutOfRangeException.ThrowIfNegative(count);
ArgumentOutOfRangeException.ThrowIfGreaterThan(startIndex, value.Length - count);
return JoinCore(separator, new ReadOnlySpan<string?>(value, startIndex, count));
}
public static string Join(string? separator, IEnumerable<string?> values)
{
if (values is List<string?> valuesList)
{
return JoinCore(separator.AsSpan(), CollectionsMarshal.AsSpan(valuesList));
}
if (values is string?[] valuesArray)
{
return JoinCore(separator.AsSpan(), new ReadOnlySpan<string?>(valuesArray));
}
if (values == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
}
using (IEnumerator<string?> en = values.GetEnumerator())
{
if (!en.MoveNext())
{
return Empty;
}
string? firstValue = en.Current;
if (!en.MoveNext())
{
// Only one value available
return firstValue ?? Empty;
}
// Null separator and values are handled by the StringBuilder
var result = new ValueStringBuilder(stackalloc char[StackallocCharBufferSizeLimit]);
result.Append(firstValue);
do
{
result.Append(separator);
result.Append(en.Current);
}
while (en.MoveNext());
return result.ToString();
}
}
public static string Join(char separator, params object?[] values) =>
JoinCore(new ReadOnlySpan<char>(in separator), values);
public static string Join(string? separator, params object?[] values) =>
JoinCore(separator.AsSpan(), values);
private static string JoinCore(ReadOnlySpan<char> separator, object?[] values)
{
if (values == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
}
if (values.Length == 0)
{
return Empty;
}
string? firstString = values[0]?.ToString();
if (values.Length == 1)
{
return firstString ?? Empty;
}
var result = new ValueStringBuilder(stackalloc char[StackallocCharBufferSizeLimit]);
result.Append(firstString);
for (int i = 1; i < values.Length; i++)
{
result.Append(separator);
object? value = values[i];
if (value != null)
{
result.Append(value.ToString());
}
}
return result.ToString();
}
public static string Join<T>(char separator, IEnumerable<T> values) =>
JoinCore(new ReadOnlySpan<char>(in separator), values);
public static string Join<T>(string? separator, IEnumerable<T> values) =>
JoinCore(separator.AsSpan(), values);
private static string JoinCore<T>(ReadOnlySpan<char> separator, IEnumerable<T> values)
{
if (typeof(T) == typeof(string))
{
if (values is List<string?> valuesList)
{
return JoinCore(separator, CollectionsMarshal.AsSpan(valuesList));
}
if (values is string?[] valuesArray)
{
return JoinCore(separator, new ReadOnlySpan<string?>(valuesArray));
}
}
if (values == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
}
using (IEnumerator<T> e = values.GetEnumerator())
{
if (!e.MoveNext())
{
// If the enumerator is empty, just return an empty string.
return Empty;
}
if (typeof(T) == typeof(char))
{
// Special-case T==char, as we can handle that case much more efficiently,
// and string.Concat(IEnumerable<char>) can be used as an efficient
// enumerable-based equivalent of new string(char[]).
IEnumerator<char> en = Unsafe.As<IEnumerator<char>>(e);
char c = en.Current; // save the first value
if (!en.MoveNext())
{
// There was only one char. Return a string from it directly.
return CreateFromChar(c);
}
// Create the builder, add the char we already enumerated,
// add the rest, and then get the resulting string.
var result = new ValueStringBuilder(stackalloc char[StackallocCharBufferSizeLimit]);
result.Append(c); // first value
do
{
if (!separator.IsEmpty)
{
result.Append(separator);
}
c = en.Current;
result.Append(c);
}
while (en.MoveNext());
return result.ToString();
}
else if (typeof(T).IsValueType && default(T) is ISpanFormattable)
{
// Special-case value types that are ISpanFormattable, as we can implement those to avoid
// all string allocations for the individual values. We only do this for value types because
// a) value types are much more likely to implement ISpanFormattable, and b) we can use
// DefaultInterpolatedStringHandler to do all the heavy lifting, and it's more efficient
// for value types as the checks it does for interface implementations are all elided.
T value = e.Current; // save the first value
if (!e.MoveNext())
{
// There was only one value. Return a string from it directly.
return value!.ToString() ?? Empty;
}
var result = new DefaultInterpolatedStringHandler(0, 0, CultureInfo.CurrentCulture, stackalloc char[StackallocCharBufferSizeLimit]);
result.AppendFormatted(value); // first value
do
{
if (!separator.IsEmpty)
{
result.AppendFormatted(separator);
}
result.AppendFormatted(e.Current);
}
while (e.MoveNext());
return result.ToStringAndClear();
}
else
{
// For all other Ts, fall back to calling ToString on each and appending the resulting
// string to a builder.
string? firstString = e.Current?.ToString(); // save the first value
if (!e.MoveNext())
{
return firstString ?? Empty;
}
var result = new ValueStringBuilder(stackalloc char[StackallocCharBufferSizeLimit]);
result.Append(firstString);
do
{
if (!separator.IsEmpty)
{
result.Append(separator);
}
result.Append(e.Current?.ToString());
}
while (e.MoveNext());
return result.ToString();
}
}
}
private static string JoinCore(ReadOnlySpan<char> separator, ReadOnlySpan<string?> values)
{
if (values.Length <= 1)
{
return values.IsEmpty ?
Empty :
values[0] ?? Empty;
}
long totalSeparatorsLength = (long)(values.Length - 1) * separator.Length;
if (totalSeparatorsLength > int.MaxValue)
{
ThrowHelper.ThrowOutOfMemoryException_StringTooLong();
}
int totalLength = (int)totalSeparatorsLength;
// Calculate the length of the resultant string so we know how much space to allocate.
foreach (string? value in values)
{
if (value != null)
{
totalLength += value.Length;
if (totalLength < 0) // Check for overflow
{
ThrowHelper.ThrowOutOfMemoryException_StringTooLong();
}
}
}
if (totalLength == 0)
{
return Empty;
}
// Copy each of the strings into the result buffer, interleaving with the separator.
string result = FastAllocateString(totalLength);
int copiedLength = 0;
for (int i = 0; i < values.Length; i++)
{
// It's possible that another thread may have mutated the input array
// such that our second read of an index will not be the same string
// we got during the first read.
// We range check again to avoid buffer overflows if this happens.
if (values[i] is string value)
{
int valueLen = value.Length;
if (valueLen > totalLength - copiedLength)
{
copiedLength = -1;
break;
}
// Fill in the value.
CopyStringContent(result, copiedLength, value);
copiedLength += valueLen;
}
if (i < values.Length - 1)
{
// Fill in the separator.
// Special-case length 1 to avoid additional overheads of CopyTo.
// This is common due to the char separator overload.
ref char dest = ref Unsafe.Add(ref result._firstChar, copiedLength);
if (separator.Length == 1)
{
dest = separator[0];
}
else
{
separator.CopyTo(new Span<char>(ref dest, separator.Length));
}
copiedLength += separator.Length;
}
}
// If we copied exactly the right amount, return the new string. Otherwise,
// something changed concurrently to mutate the input array: fall back to
// doing the concatenation again, but this time with a defensive copy. This
// fall back should be extremely rare.
return copiedLength == totalLength ?
result :
JoinCore(separator, values.ToArray().AsSpan());