This repository has been archived by the owner on May 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
StringFormatter.cs
2466 lines (2131 loc) · 96.5 KB
/
StringFormatter.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) 2015-2017 Michael Popoloski
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace System.Text.Formatting {
/// <summary>
/// Specifies an interface for types that act as a set of formatting arguments.
/// </summary>
public interface IArgSet {
/// <summary>
/// The number of arguments in the set.
/// </summary>
int Count { get; }
/// <summary>
/// Format one of the arguments in the set into the given string buffer.
/// </summary>
/// <param name="buffer">The buffer to which to append the argument.</param>
/// <param name="index">The index of the argument to format.</param>
/// <param name="format">A specifier indicating how the argument should be formatted.</param>
void Format (StringBuffer buffer, int index, StringView format);
}
/// <summary>
/// Defines an interface for types that can be formatted into a string buffer.
/// </summary>
public interface IStringFormattable {
/// <summary>
/// Format the current instance into the given string buffer.
/// </summary>
/// <param name="buffer">The buffer to which to append.</param>
/// <param name="format">A specifier indicating how the argument should be formatted.</param>
void Format (StringBuffer buffer, StringView format);
}
/// <summary>
/// A low-allocation version of the built-in <see cref="StringBuilder"/> type.
/// </summary>
public unsafe sealed partial class StringBuffer {
CachedCulture culture;
char[] buffer;
int currentCount;
/// <summary>
/// The number of characters in the buffer.
/// </summary>
public int Count {
get { return currentCount; }
}
/// <summary>
/// The culture used to format string data.
/// </summary>
public CultureInfo Culture {
get { return culture.Culture; }
set {
if (culture.Culture == value)
return;
if (value == CultureInfo.InvariantCulture)
culture = CachedInvariantCulture;
else if (value == CachedCurrentCulture.Culture)
culture = CachedCurrentCulture;
else
culture = new CachedCulture(value);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="StringBuffer"/> class.
/// </summary>
public StringBuffer ()
: this(DefaultCapacity) {
}
/// <summary>
/// Initializes a new instance of the <see cref="StringBuffer"/> class.
/// </summary>
/// <param name="capacity">The initial size of the string buffer.</param>
public StringBuffer (int capacity) {
buffer = new char[capacity];
culture = CachedCurrentCulture;
}
/// <summary>
/// Sets a custom formatter to use when converting instances of a given type to a string.
/// </summary>
/// <typeparam name="T">The type for which to set the formatter.</typeparam>
/// <param name="formatter">A delegate that will be called to format instances of the specified type.</param>
public static void SetCustomFormatter<T>(Action<StringBuffer, T, StringView> formatter) {
ValueHelper<T>.Formatter = formatter;
}
/// <summary>
/// Clears the buffer.
/// </summary>
public void Clear () {
currentCount = 0;
}
/// <summary>
/// Copies the contents of the buffer to the given array.
/// </summary>
/// <param name="sourceIndex">The index within the buffer to begin copying.</param>
/// <param name="destination">The destination array.</param>
/// <param name="destinationIndex">The index within the destination array to which to begin copying.</param>
/// <param name="count">The number of characters to copy.</param>
public void CopyTo (int sourceIndex, char[] destination, int destinationIndex, int count) {
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (destinationIndex + count > destination.Length || destinationIndex < 0)
throw new ArgumentOutOfRangeException(nameof(destinationIndex));
fixed (char* destPtr = &destination[destinationIndex])
CopyTo(destPtr, sourceIndex, count);
}
/// <summary>
/// Copies the contents of the buffer to the given array.
/// </summary>
/// <param name="dest">A pointer to the destination array.</param>
/// <param name="sourceIndex">The index within the buffer to begin copying.</param>
/// <param name="count">The number of characters to copy.</param>
public void CopyTo (char* dest, int sourceIndex, int count) {
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (sourceIndex + count > currentCount || sourceIndex < 0)
throw new ArgumentOutOfRangeException(nameof(sourceIndex));
fixed (char* s = buffer)
{
var src = s + sourceIndex;
for (int i = 0; i < count; i++)
*dest++ = *src++;
}
}
/// <summary>
/// Copies the contents of the buffer to the given byte array.
/// </summary>
/// <param name="dest">A pointer to the destination byte array.</param>
/// <param name="sourceIndex">The index within the buffer to begin copying.</param>
/// <param name="count">The number of characters to copy.</param>
/// <param name="encoding">The encoding to use to convert characters to bytes.</param>
/// <returns>The number of bytes written to the destination.</returns>
public int CopyTo (byte* dest, int sourceIndex, int count, Encoding encoding) {
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (sourceIndex + count > currentCount || sourceIndex < 0)
throw new ArgumentOutOfRangeException(nameof(sourceIndex));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
fixed (char* s = buffer)
return encoding.GetBytes(s, count, dest, count);
}
/// <summary>
/// Converts the buffer to a string instance.
/// </summary>
/// <returns>A new string representing the characters currently in the buffer.</returns>
public override string ToString () {
return new string(buffer, 0, currentCount);
}
/// <summary>
/// Appends a character to the current buffer.
/// </summary>
/// <param name="c">The character to append.</param>
public void Append (char c) {
Append(c, 1);
}
/// <summary>
/// Appends a character to the current buffer several times.
/// </summary>
/// <param name="c">The character to append.</param>
/// <param name="count">The number of times to append the character.</param>
public void Append (char c, int count) {
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
CheckCapacity(count);
fixed (char* b = &buffer[currentCount])
{
var ptr = b;
for (int i = 0; i < count; i++)
*ptr++ = c;
currentCount += count;
}
}
/// <summary>
/// Appends the specified string to the current buffer.
/// </summary>
/// <param name="value">The value to append.</param>
public void Append (string value) {
if (value == null)
throw new ArgumentNullException(nameof(value));
Append(value, 0, value.Length);
}
/// <summary>
/// Appends a string subset to the current buffer.
/// </summary>
/// <param name="value">The string to append.</param>
/// <param name="startIndex">The starting index within the string to begin reading characters.</param>
/// <param name="count">The number of characters to append.</param>
public void Append (string value, int startIndex, int count) {
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex < 0 || startIndex + count > value.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex));
fixed (char* s = value)
Append(s + startIndex, count);
}
/// <summary>
/// Appends an array of characters to the current buffer.
/// </summary>
/// <param name="values">The characters to append.</param>
/// <param name="startIndex">The starting index within the array to begin reading characters.</param>
/// <param name="count">The number of characters to append.</param>
public void Append (char[] values, int startIndex, int count) {
if (values == null)
throw new ArgumentNullException(nameof(values));
if (startIndex < 0 || startIndex + count > values.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex));
fixed (char* s = &values[startIndex])
Append(s, count);
}
/// <summary>
/// Appends an array of characters to the current buffer.
/// </summary>
/// <param name="str">A pointer to the array of characters to append.</param>
/// <param name="count">The number of characters to append.</param>
public void Append (char* str, int count) {
CheckCapacity(count);
fixed (char* b = &buffer[currentCount])
{
var dest = b;
for (int i = 0; i < count; i++)
*dest++ = *str++;
currentCount += count;
}
}
/// <summary>
/// Appends the specified value as a string to the current buffer.
/// </summary>
/// <param name="value">The value to append.</param>
public void Append (bool value) {
if (value)
Append(TrueLiteral);
else
Append(FalseLiteral);
}
/// <summary>
/// Appends the specified value as a string to the current buffer.
/// </summary>
/// <param name="value">The value to append.</param>
/// <param name="format">A format specifier indicating how to convert <paramref name="value"/> to a string.</param>
public void Append (sbyte value, StringView format) {
Numeric.FormatSByte(this, value, format, culture);
}
/// <summary>
/// Appends the specified value as a string to the current buffer.
/// </summary>
/// <param name="value">The value to append.</param>
/// <param name="format">A format specifier indicating how to convert <paramref name="value"/> to a string.</param>
public void Append (byte value, StringView format) {
// widening here is fine
Numeric.FormatUInt32(this, value, format, culture);
}
/// <summary>
/// Appends the specified value as a string to the current buffer.
/// </summary>
/// <param name="value">The value to append.</param>
/// <param name="format">A format specifier indicating how to convert <paramref name="value"/> to a string.</param>
public void Append (short value, StringView format) {
Numeric.FormatInt16(this, value, format, culture);
}
/// <summary>
/// Appends the specified value as a string to the current buffer.
/// </summary>
/// <param name="value">The value to append.</param>
/// <param name="format">A format specifier indicating how to convert <paramref name="value"/> to a string.</param>
public void Append (ushort value, StringView format) {
// widening here is fine
Numeric.FormatUInt32(this, value, format, culture);
}
/// <summary>
/// Appends the specified value as a string to the current buffer.
/// </summary>
/// <param name="value">The value to append.</param>
/// <param name="format">A format specifier indicating how to convert <paramref name="value"/> to a string.</param>
public void Append (int value, StringView format) {
Numeric.FormatInt32(this, value, format, culture);
}
/// <summary>
/// Appends the specified value as a string to the current buffer.
/// </summary>
/// <param name="value">The value to append.</param>
/// <param name="format">A format specifier indicating how to convert <paramref name="value"/> to a string.</param>
public void Append (uint value, StringView format) {
Numeric.FormatUInt32(this, value, format, culture);
}
/// <summary>
/// Appends the specified value as a string to the current buffer.
/// </summary>
/// <param name="value">The value to append.</param>
/// <param name="format">A format specifier indicating how to convert <paramref name="value"/> to a string.</param>
public void Append (long value, StringView format) {
Numeric.FormatInt64(this, value, format, culture);
}
/// <summary>
/// Appends the specified value as a string to the current buffer.
/// </summary>
/// <param name="value">The value to append.</param>
/// <param name="format">A format specifier indicating how to convert <paramref name="value"/> to a string.</param>
public void Append (ulong value, StringView format) {
Numeric.FormatUInt64(this, value, format, culture);
}
/// <summary>
/// Appends the specified value as a string to the current buffer.
/// </summary>
/// <param name="value">The value to append.</param>
/// <param name="format">A format specifier indicating how to convert <paramref name="value"/> to a string.</param>
public void Append (float value, StringView format) {
Numeric.FormatSingle(this, value, format, culture);
}
/// <summary>
/// Appends the specified value as a string to the current buffer.
/// </summary>
/// <param name="value">The value to append.</param>
/// <param name="format">A format specifier indicating how to convert <paramref name="value"/> to a string.</param>
public void Append (double value, StringView format) {
Numeric.FormatDouble(this, value, format, culture);
}
/// <summary>
/// Appends the specified value as a string to the current buffer.
/// </summary>
/// <param name="value">The value to append.</param>
/// <param name="format">A format specifier indicating how to convert <paramref name="value"/> to a string.</param>
public void Append (decimal value, StringView format) {
Numeric.FormatDecimal(this, (uint*)&value, format, culture);
}
/// <summary>
/// Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance.
/// Each format item is replaced by the string representation of a single argument.
/// </summary>
/// <typeparam name="T">The type of argument set being formatted.</typeparam>
/// <param name="format">A composite format string.</param>
/// <param name="args">The set of args to insert into the format string.</param>
public void AppendArgSet<T>(string format, ref T args) where T : IArgSet {
if (format == null)
throw new ArgumentNullException(nameof(format));
fixed (char* formatPtr = format)
{
var curr = formatPtr;
var end = curr + format.Length;
var segmentsLeft = false;
var prevArgIndex = 0;
do {
CheckCapacity((int)(end - curr));
fixed (char* bufferPtr = &buffer[currentCount])
segmentsLeft = AppendSegment(ref curr, end, bufferPtr, ref prevArgIndex, ref args);
}
while (segmentsLeft);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void CheckCapacity (int count) {
if (currentCount + count > buffer.Length)
Array.Resize(ref buffer, buffer.Length * 2);
}
bool AppendSegment<T>(ref char* currRef, char* end, char* dest, ref int prevArgIndex, ref T args) where T : IArgSet {
char* curr = currRef;
char c = '\x0';
while (curr < end) {
c = *curr++;
if (c == '}') {
// check for escape character for }}
if (curr < end && *curr == '}')
curr++;
else
ThrowError();
}
else if (c == '{') {
// check for escape character for {{
if (curr == end)
ThrowError();
else if (*curr == '{')
curr++;
else
break;
}
*dest++ = c;
currentCount++;
}
if (curr == end)
return false;
int index;
if (*curr == '}')
index = prevArgIndex;
else
index = ParseNum(ref curr, end, MaxArgs);
if (index >= args.Count)
throw new FormatException(string.Format(SR.ArgIndexOutOfRange, index));
// check for a spacing specifier
c = SkipWhitespace(ref curr, end);
var width = 0;
var leftJustify = false;
var oldCount = currentCount;
if (c == ',') {
curr++;
c = SkipWhitespace(ref curr, end);
// spacing can be left-justified
if (c == '-') {
leftJustify = true;
curr++;
if (curr == end)
ThrowError();
}
width = ParseNum(ref curr, end, MaxSpacing);
c = SkipWhitespace(ref curr, end);
}
// check for format specifier
curr++;
if (c == ':') {
var specifierBuffer = stackalloc char[MaxSpecifierSize];
var specifierEnd = specifierBuffer + MaxSpecifierSize;
var specifierPtr = specifierBuffer;
while (true) {
if (curr == end)
ThrowError();
c = *curr++;
if (c == '{') {
// check for escape character for {{
if (curr < end && *curr == '{')
curr++;
else
ThrowError();
}
else if (c == '}') {
// check for escape character for }}
if (curr < end && *curr == '}')
curr++;
else {
// found the end of the specifier
// kick off the format job
var specifier = new StringView(specifierBuffer, (int)(specifierPtr - specifierBuffer));
args.Format(this, index, specifier);
break;
}
}
if (specifierPtr == specifierEnd)
ThrowError();
*specifierPtr++ = c;
}
}
else {
// no specifier. make sure we're at the end of the format block
if (c != '}')
ThrowError();
// format without any specifier
args.Format(this, index, StringView.Empty);
}
// finish off padding, if necessary
var padding = width - (currentCount - oldCount);
if (padding > 0) {
if (leftJustify)
Append(' ', padding);
else {
// copy the recently placed chars up in memory to make room for padding
CheckCapacity(padding);
for (int i = currentCount - 1; i >= oldCount; i--)
buffer[i + padding] = buffer[i];
// fill in padding
for (int i = 0; i < padding; i++)
buffer[i + oldCount] = ' ';
currentCount += padding;
}
}
prevArgIndex = index + 1;
currRef = curr;
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void AppendGeneric<T>(T value, StringView format) {
// this looks gross, but T is known at JIT-time so this call tree
// gets compiled down to a direct call with no branching
if (typeof(T) == typeof(sbyte))
Append(*(sbyte*)Unsafe.AsPointer(ref value), format);
else if (typeof(T) == typeof(byte))
Append(*(byte*)Unsafe.AsPointer(ref value), format);
else if (typeof(T) == typeof(short))
Append(*(short*)Unsafe.AsPointer(ref value), format);
else if (typeof(T) == typeof(ushort))
Append(*(ushort*)Unsafe.AsPointer(ref value), format);
else if (typeof(T) == typeof(int))
Append(*(int*)Unsafe.AsPointer(ref value), format);
else if (typeof(T) == typeof(uint))
Append(*(uint*)Unsafe.AsPointer(ref value), format);
else if (typeof(T) == typeof(long))
Append(*(long*)Unsafe.AsPointer(ref value), format);
else if (typeof(T) == typeof(ulong))
Append(*(ulong*)Unsafe.AsPointer(ref value), format);
else if (typeof(T) == typeof(float))
Append(*(float*)Unsafe.AsPointer(ref value), format);
else if (typeof(T) == typeof(double))
Append(*(double*)Unsafe.AsPointer(ref value), format);
else if (typeof(T) == typeof(decimal))
Append(*(decimal*)Unsafe.AsPointer(ref value), format);
else if (typeof(T) == typeof(bool))
Append(*(bool*)Unsafe.AsPointer(ref value));
else if (typeof(T) == typeof(char))
Append(*(char*)Unsafe.AsPointer(ref value), format);
else if (typeof(T) == typeof(string))
Append(Unsafe.As<string>(value));
else {
// first, check to see if it's a value type implementing IStringFormattable
var formatter = ValueHelper<T>.Formatter;
if (formatter != null)
formatter(this, value, format);
else {
// We could handle this case by calling ToString() on the object and paying the
// allocation, but presumably if the user is using us instead of the built-in
// formatting utilities they would rather be notified of this case, so we'll throw.
throw new InvalidOperationException(string.Format(SR.TypeNotFormattable, typeof(T)));
}
}
}
static int ParseNum (ref char* currRef, char* end, int maxValue) {
char* curr = currRef;
char c = *curr;
if (c < '0' || c > '9')
ThrowError();
int value = 0;
do {
value = value * 10 + c - '0';
curr++;
if (curr == end)
ThrowError();
c = *curr;
} while (c >= '0' && c <= '9' && value < maxValue);
currRef = curr;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static char SkipWhitespace (ref char* currRef, char* end) {
char* curr = currRef;
while (curr < end && *curr == ' ') curr++;
if (curr == end)
ThrowError();
currRef = curr;
return *curr;
}
static void ThrowError () {
throw new FormatException(SR.InvalidFormatString);
}
static StringBuffer Acquire (int capacity) {
if (capacity <= MaxCachedSize) {
var buffer = CachedInstance;
if (buffer != null) {
CachedInstance = null;
buffer.Clear();
buffer.CheckCapacity(capacity);
return buffer;
}
}
return new StringBuffer(capacity);
}
static void Release (StringBuffer buffer) {
if (buffer.buffer.Length <= MaxCachedSize)
CachedInstance = buffer;
}
[ThreadStatic]
static StringBuffer CachedInstance;
static readonly CachedCulture CachedInvariantCulture = new CachedCulture(CultureInfo.InvariantCulture);
static readonly CachedCulture CachedCurrentCulture = new CachedCulture(CultureInfo.CurrentCulture);
const int DefaultCapacity = 32;
const int MaxCachedSize = 360; // same as BCL's StringBuilderCache
const int MaxArgs = 256;
const int MaxSpacing = 1000000;
const int MaxSpecifierSize = 32;
const string TrueLiteral = "True";
const string FalseLiteral = "False";
// The point of this class is to allow us to generate a direct call to a known
// method on an unknown, unconstrained generic value type. Normally this would
// be impossible; you'd have to cast the generic argument and introduce boxing.
// Instead we pay a one-time startup cost to create a delegate that will forward
// the parameter to the appropriate method in a strongly typed fashion.
static class ValueHelper<T> {
public static Action<StringBuffer, T, StringView> Formatter = Prepare();
static Action<StringBuffer, T, StringView> Prepare () {
// we only use this class for value types that also implement IStringFormattable
var type = typeof(T);
if (!typeof(IStringFormattable).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
return null;
var result = typeof(ValueHelper<T>)
.GetTypeInfo()
.GetDeclaredMethod("Assign")
.MakeGenericMethod(type)
.Invoke(null, null);
return (Action<StringBuffer, T, StringView>)result;
}
public static Action<StringBuffer, U, StringView> Assign<U>() where U : IStringFormattable {
return (f, u, v) => u.Format(f, v);
}
}
}
// TODO: clean this up
public unsafe struct StringView {
public static readonly StringView Empty = new StringView();
public readonly char* Data;
public readonly int Length;
public bool IsEmpty {
get { return Length == 0; }
}
public StringView (char* data, int length) {
Data = data;
Length = length;
}
public static bool operator ==(StringView lhs, string rhs) {
var count = lhs.Length;
if (count != rhs.Length)
return false;
fixed (char* r = rhs)
{
var lhsPtr = lhs.Data;
var rhsPtr = r;
for (int i = 0; i < count; i++) {
if (*lhsPtr++ != *rhsPtr++)
return false;
}
}
return true;
}
public static bool operator !=(StringView lhs, string rhs) {
return !(lhs == rhs);
}
}
// caches formatting information from culture data
// some of the accessors on NumberFormatInfo allocate copies of their data
sealed class CachedCulture {
public readonly CultureInfo Culture;
public readonly NumberFormatData CurrencyData;
public readonly NumberFormatData FixedData;
public readonly NumberFormatData NumberData;
public readonly NumberFormatData ScientificData;
public readonly NumberFormatData PercentData;
public readonly string CurrencyNegativePattern;
public readonly string CurrencyPositivePattern;
public readonly string CurrencySymbol;
public readonly string NumberNegativePattern;
public readonly string NumberPositivePattern;
public readonly string PercentNegativePattern;
public readonly string PercentPositivePattern;
public readonly string PercentSymbol;
public readonly string NegativeSign;
public readonly string PositiveSign;
public readonly string NaN;
public readonly string PositiveInfinity;
public readonly string NegativeInfinity;
public readonly int DecimalBufferSize;
public CachedCulture (CultureInfo culture) {
Culture = culture;
var info = culture.NumberFormat;
CurrencyData = new NumberFormatData(
info.CurrencyDecimalDigits,
info.NegativeSign,
info.CurrencyDecimalSeparator,
info.CurrencyGroupSeparator,
info.CurrencyGroupSizes,
info.CurrencySymbol.Length
);
FixedData = new NumberFormatData(
info.NumberDecimalDigits,
info.NegativeSign,
info.NumberDecimalSeparator,
null,
null,
0
);
NumberData = new NumberFormatData(
info.NumberDecimalDigits,
info.NegativeSign,
info.NumberDecimalSeparator,
info.NumberGroupSeparator,
info.NumberGroupSizes,
0
);
ScientificData = new NumberFormatData(
6,
info.NegativeSign,
info.NumberDecimalSeparator,
null,
null,
info.NegativeSign.Length + info.PositiveSign.Length * 2 // for number and exponent
);
PercentData = new NumberFormatData(
info.PercentDecimalDigits,
info.NegativeSign,
info.PercentDecimalSeparator,
info.PercentGroupSeparator,
info.PercentGroupSizes,
info.PercentSymbol.Length
);
CurrencyNegativePattern = NegativeCurrencyFormats[info.CurrencyNegativePattern];
CurrencyPositivePattern = PositiveCurrencyFormats[info.CurrencyPositivePattern];
CurrencySymbol = info.CurrencySymbol;
NumberNegativePattern = NegativeNumberFormats[info.NumberNegativePattern];
NumberPositivePattern = PositiveNumberFormat;
PercentNegativePattern = NegativePercentFormats[info.PercentNegativePattern];
PercentPositivePattern = PositivePercentFormats[info.PercentPositivePattern];
PercentSymbol = info.PercentSymbol;
NegativeSign = info.NegativeSign;
PositiveSign = info.PositiveSign;
NaN = info.NaNSymbol;
PositiveInfinity = info.PositiveInfinitySymbol;
NegativeInfinity = info.NegativeInfinitySymbol;
DecimalBufferSize =
NumberFormatData.MinBufferSize +
info.NumberDecimalSeparator.Length +
(NegativeSign.Length + PositiveSign.Length) * 2;
}
static readonly string[] PositiveCurrencyFormats = {
"$#", "#$", "$ #", "# $"
};
static readonly string[] NegativeCurrencyFormats = {
"($#)", "-$#", "$-#", "$#-",
"(#$)", "-#$", "#-$", "#$-",
"-# $", "-$ #", "# $-", "$ #-",
"$ -#", "#- $", "($ #)", "(# $)"
};
static readonly string[] PositivePercentFormats = {
"# %", "#%", "%#", "% #"
};
static readonly string[] NegativePercentFormats = {
"-# %", "-#%", "-%#",
"%-#", "%#-",
"#-%", "#%-",
"-% #", "# %-", "% #-",
"% -#", "#- %"
};
static readonly string[] NegativeNumberFormats = {
"(#)", "-#", "- #", "#-", "# -",
};
static readonly string PositiveNumberFormat = "#";
}
// contains format information for a specific kind of format string
// e.g. (fixed, number, currency)
sealed class NumberFormatData {
readonly int bufferLength;
readonly int perDigitLength;
public readonly int DecimalDigits;
public readonly string NegativeSign;
public readonly string DecimalSeparator;
public readonly string GroupSeparator;
public readonly int[] GroupSizes;
public NumberFormatData (int decimalDigits, string negativeSign, string decimalSeparator, string groupSeparator, int[] groupSizes, int extra) {
DecimalDigits = decimalDigits;
NegativeSign = negativeSign;
DecimalSeparator = decimalSeparator;
GroupSeparator = groupSeparator;
GroupSizes = groupSizes;
bufferLength = MinBufferSize;
bufferLength += NegativeSign.Length;
bufferLength += DecimalSeparator.Length;
bufferLength += extra;
if (GroupSeparator != null)
perDigitLength = GroupSeparator.Length;
}
public int GetBufferSize (ref int maxDigits, int scale) {
if (maxDigits < 0)
maxDigits = DecimalDigits;
var digitCount = scale >= 0 ? scale + maxDigits : 0;
long len = bufferLength;
// calculate buffer size
len += digitCount;
len += perDigitLength * digitCount;
return checked((int)len);
}
internal const int MinBufferSize = 105;
}
// this file contains the custom numeric formatting routines split out from the Numeric.cs file
partial class Numeric {
static void NumberToCustomFormatString (StringBuffer formatter, ref Number number, StringView specifier, CachedCulture culture) {
}
}
// Most of the implementation of this file was ported from the native versions built into the CLR
// See: https://github.com/dotnet/coreclr/blob/838807429a0828a839958e3b7d392d65886c8f2e/src/classlibnative/bcltype/number.cpp
// Also see: https://github.com/dotnet/coreclr/blob/02084af832c2900cf6eac2a168c41f261409be97/src/mscorlib/src/System/Number.cs
// Standard numeric format string reference: https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx
unsafe static partial class Numeric {
public static void FormatSByte (StringBuffer formatter, sbyte value, StringView specifier, CachedCulture culture) {
if (value < 0 && !specifier.IsEmpty) {
// if we're negative and doing a hex format, mask out the bits for the conversion
char c = specifier.Data[0];
if (c == 'X' || c == 'x') {
FormatUInt32(formatter, (uint)(value & 0xFF), specifier, culture);
return;
}
}
FormatInt32(formatter, value, specifier, culture);
}
public static void FormatInt16 (StringBuffer formatter, short value, StringView specifier, CachedCulture culture) {
if (value < 0 && !specifier.IsEmpty) {
// if we're negative and doing a hex format, mask out the bits for the conversion
char c = specifier.Data[0];
if (c == 'X' || c == 'x') {
FormatUInt32(formatter, (uint)(value & 0xFFFF), specifier, culture);
return;
}
}
FormatInt32(formatter, value, specifier, culture);
}
public static void FormatInt32 (StringBuffer formatter, int value, StringView specifier, CachedCulture culture) {
int digits;
var fmt = ParseFormatSpecifier(specifier, out digits);
// ANDing with 0xFFDF has the effect of uppercasing the character
switch (fmt & 0xFFDF) {
case 'G':
if (digits > 0)
goto default;
else
goto case 'D';
case 'D':
Int32ToDecStr(formatter, value, digits, culture.NegativeSign);
break;
case 'X':
// fmt-('X'-'A'+1) gives us the base hex character in either
// uppercase or lowercase, depending on the casing of fmt
Int32ToHexStr(formatter, (uint)value, fmt - ('X' - 'A' + 10), digits);
break;
default:
var number = new Number();
var buffer = stackalloc char[MaxNumberDigits + 1];
number.Digits = buffer;
Int32ToNumber(value, ref number);
if (fmt != 0)
NumberToString(formatter, ref number, fmt, digits, culture);
else
NumberToCustomFormatString(formatter, ref number, specifier, culture);
break;
}
}
public static void FormatUInt32 (StringBuffer formatter, uint value, StringView specifier, CachedCulture culture) {
int digits;
var fmt = ParseFormatSpecifier(specifier, out digits);
// ANDing with 0xFFDF has the effect of uppercasing the character
switch (fmt & 0xFFDF) {
case 'G':
if (digits > 0)
goto default;
else
goto case 'D';
case 'D':
UInt32ToDecStr(formatter, value, digits);
break;
case 'X':
// fmt-('X'-'A'+1) gives us the base hex character in either
// uppercase or lowercase, depending on the casing of fmt
Int32ToHexStr(formatter, value, fmt - ('X' - 'A' + 10), digits);
break;
default:
var number = new Number();
var buffer = stackalloc char[MaxNumberDigits + 1];