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
/
Copy pathTimeSpanParse.cs
1704 lines (1460 loc) · 63.9 KB
/
TimeSpanParse.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.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
// Purpose: Used by TimeSpan to parse a time interval string.
//
// Standard Format:
// -=-=-=-=-=-=-=-
// "c": Constant format. [-][d'.']hh':'mm':'ss['.'fffffff]
// Not culture sensitive. Default format (and null/empty format string) map to this format.
//
// "g": General format, short: [-][d':']h':'mm':'ss'.'FFFFFFF
// Only print what's needed. Localized (if you want Invariant, pass in Invariant).
// The fractional seconds separator is localized, equal to the culture's DecimalSeparator.
//
// "G": General format, long: [-]d':'hh':'mm':'ss'.'fffffff
// Always print days and 7 fractional digits. Localized (if you want Invariant, pass in Invariant).
// The fractional seconds separator is localized, equal to the culture's DecimalSeparator.
//
// * "TryParseTimeSpan" is the main method for Parse/TryParse
//
// - TimeSpanTokenizer.GetNextToken() is used to split the input string into number and literal tokens.
// - TimeSpanRawInfo.ProcessToken() adds the next token into the parsing intermediary state structure
// - ProcessTerminalState() uses the fully initialized TimeSpanRawInfo to find a legal parse match.
// The terminal states are attempted as follows:
// foreach (+InvariantPattern, -InvariantPattern, +LocalizedPattern, -LocalizedPattern) try
// 1 number => d
// 2 numbers => h:m
// 3 numbers => h:m:s | d.h:m | h:m:.f
// 4 numbers => h:m:s.f | d.h:m:s | d.h:m:.f
// 5 numbers => d.h:m:s.f
//
// Custom Format:
// -=-=-=-=-=-=-=
//
// * "TryParseExactTimeSpan" is the main method for ParseExact/TryParseExact methods
// * "TryParseExactMultipleTimeSpan" is the main method for ParseExact/TryparseExact
// methods that take a string[] of formats
//
// - For single-letter formats "TryParseTimeSpan" is called (see above)
// - For multi-letter formats "TryParseByFormat" is called
// - TryParseByFormat uses helper methods (ParseExactLiteral, ParseExactDigits, etc)
// which drive the underlying TimeSpanTokenizer. However, unlike standard formatting which
// operates on whole-tokens, ParseExact operates at the character-level. As such,
// TimeSpanTokenizer.NextChar and TimeSpanTokenizer.BackOne() are called directly.
//
////////////////////////////////////////////////////////////////////////////
using System.Diagnostics;
using System.Text;
namespace System.Globalization
{
internal static class TimeSpanParse
{
private const int MaxFractionDigits = 7;
private const int MaxDays = 10675199;
private const int MaxHours = 23;
private const int MaxMinutes = 59;
private const int MaxSeconds = 59;
private const int MaxFraction = 9999999;
[Flags]
private enum TimeSpanStandardStyles : byte
{
// Standard Format Styles
None = 0x00000000,
Invariant = 0x00000001, //Allow Invariant Culture
Localized = 0x00000002, //Allow Localized Culture
RequireFull = 0x00000004, //Require the input to be in DHMSF format
Any = Invariant | Localized,
}
// TimeSpan Token Types
private enum TTT : byte
{
None = 0, // None of the TimeSpanToken fields are set
End = 1, // '\0'
Num = 2, // Number
Sep = 3, // literal
NumOverflow = 4, // Number that overflowed
}
private ref struct TimeSpanToken
{
internal TTT _ttt;
internal int _num; // Store the number that we are parsing (if any)
internal int _zeroes; // Store the number of leading zeroes (if any)
internal ReadOnlySpan<char> _sep; // Store the literal that we are parsing (if any)
public TimeSpanToken(TTT type) : this(type, 0, 0, default) { }
public TimeSpanToken(int number) : this(TTT.Num, number, 0, default) { }
public TimeSpanToken(int number, int leadingZeroes) : this(TTT.Num, number, leadingZeroes, default) { }
public TimeSpanToken(TTT type, int number, int leadingZeroes, ReadOnlySpan<char> separator)
{
_ttt = type;
_num = number;
_zeroes = leadingZeroes;
_sep = separator;
}
public bool IsInvalidFraction()
{
Debug.Assert(_ttt == TTT.Num);
Debug.Assert(_num > -1);
if (_num > MaxFraction || _zeroes > MaxFractionDigits)
return true;
if (_num == 0 || _zeroes == 0)
return false;
// num > 0 && zeroes > 0 && num <= maxValue && zeroes <= maxPrecision
return _num >= MaxFraction / Pow10(_zeroes - 1);
}
}
private ref struct TimeSpanTokenizer
{
private ReadOnlySpan<char> _value;
private int _pos;
internal TimeSpanTokenizer(ReadOnlySpan<char> input) : this(input, 0) { }
internal TimeSpanTokenizer(ReadOnlySpan<char> input, int startPosition)
{
_value = input;
_pos = startPosition;
}
/// <summary>Returns the next token in the input string</summary>
/// <remarks>Used by the parsing routines that operate on standard-formats.</remarks>
internal TimeSpanToken GetNextToken()
{
// Get the position of the next character to be processed. If there is no
// next character, we're at the end.
int pos = _pos;
Debug.Assert(pos > -1);
if (pos >= _value.Length)
{
return new TimeSpanToken(TTT.End);
}
// Now retrieve that character. If it's a digit, we're processing a number.
int num = _value[pos] - '0';
if ((uint)num <= 9)
{
int zeroes = 0;
if (num == 0)
{
// Read all leading zeroes.
zeroes = 1;
while (true)
{
int digit;
if (++_pos >= _value.Length || (uint)(digit = _value[_pos] - '0') > 9)
{
return new TimeSpanToken(TTT.Num, 0, zeroes, default);
}
if (digit == 0)
{
zeroes++;
continue;
}
num = digit;
break;
}
}
// Continue to read as long as we're reading digits.
while (++_pos < _value.Length)
{
int digit = _value[_pos] - '0';
if ((uint)digit > 9)
{
break;
}
num = num * 10 + digit;
if ((num & 0xF0000000) != 0)
{
return new TimeSpanToken(TTT.NumOverflow);
}
}
return new TimeSpanToken(TTT.Num, num, zeroes, default);
}
// Otherwise, we're processing a separator, and we've already processed the first
// character of it. Continue processing characters as long as they're not digits.
int length = 1;
while (true)
{
if (++_pos >= _value.Length || (uint)(_value[_pos] - '0') <= 9)
{
break;
}
length++;
}
// Return the separator.
return new TimeSpanToken(TTT.Sep, 0, 0, _value.Slice(pos, length));
}
internal bool EOL => _pos >= (_value.Length - 1);
internal void BackOne()
{
if (_pos > 0) --_pos;
}
internal char NextChar
{
get
{
int pos = ++_pos;
return (uint)pos < (uint)_value.Length ?
_value[pos] :
(char)0;
}
}
}
/// <summary>Stores intermediary parsing state for the standard formats.</summary>
private ref struct TimeSpanRawInfo
{
internal TimeSpanFormat.FormatLiterals PositiveInvariant => TimeSpanFormat.PositiveInvariantFormatLiterals;
internal TimeSpanFormat.FormatLiterals NegativeInvariant => TimeSpanFormat.NegativeInvariantFormatLiterals;
internal TimeSpanFormat.FormatLiterals PositiveLocalized
{
get
{
if (!_posLocInit)
{
_posLoc = new TimeSpanFormat.FormatLiterals();
_posLoc.Init(_fullPosPattern, false);
_posLocInit = true;
}
return _posLoc;
}
}
internal TimeSpanFormat.FormatLiterals NegativeLocalized
{
get
{
if (!_negLocInit)
{
_negLoc = new TimeSpanFormat.FormatLiterals();
_negLoc.Init(_fullNegPattern, false);
_negLocInit = true;
}
return _negLoc;
}
}
internal bool FullAppCompatMatch(TimeSpanFormat.FormatLiterals pattern) =>
_sepCount == 5
&& _numCount == 4
&& _literals0.EqualsOrdinal(pattern.Start)
&& _literals1.EqualsOrdinal(pattern.DayHourSep)
&& _literals2.EqualsOrdinal(pattern.HourMinuteSep)
&& _literals3.EqualsOrdinal(pattern.AppCompatLiteral)
&& _literals4.EqualsOrdinal(pattern.End);
internal bool PartialAppCompatMatch(TimeSpanFormat.FormatLiterals pattern) =>
_sepCount == 4
&& _numCount == 3
&& _literals0.EqualsOrdinal(pattern.Start)
&& _literals1.EqualsOrdinal(pattern.HourMinuteSep)
&& _literals2.EqualsOrdinal(pattern.AppCompatLiteral)
&& _literals3.EqualsOrdinal(pattern.End);
/// <summary>DHMSF (all values matched)</summary>
internal bool FullMatch(TimeSpanFormat.FormatLiterals pattern) =>
_sepCount == MaxLiteralTokens
&& _numCount == MaxNumericTokens
&& _literals0.EqualsOrdinal(pattern.Start)
&& _literals1.EqualsOrdinal(pattern.DayHourSep)
&& _literals2.EqualsOrdinal(pattern.HourMinuteSep)
&& _literals3.EqualsOrdinal(pattern.MinuteSecondSep)
&& _literals4.EqualsOrdinal(pattern.SecondFractionSep)
&& _literals5.EqualsOrdinal(pattern.End);
/// <summary>D (no hours, minutes, seconds, or fractions)</summary>
internal bool FullDMatch(TimeSpanFormat.FormatLiterals pattern) =>
_sepCount == 2
&& _numCount == 1
&& _literals0.EqualsOrdinal(pattern.Start)
&& _literals1.EqualsOrdinal(pattern.End);
/// <summary>HM (no days, seconds, or fractions)</summary>
internal bool FullHMMatch(TimeSpanFormat.FormatLiterals pattern) =>
_sepCount == 3
&& _numCount == 2
&& _literals0.EqualsOrdinal(pattern.Start)
&& _literals1.EqualsOrdinal(pattern.HourMinuteSep)
&& _literals2.EqualsOrdinal(pattern.End);
/// <summary>DHM (no seconds or fraction)</summary>
internal bool FullDHMMatch(TimeSpanFormat.FormatLiterals pattern) =>
_sepCount == 4
&& _numCount == 3
&& _literals0.EqualsOrdinal(pattern.Start)
&& _literals1.EqualsOrdinal(pattern.DayHourSep)
&& _literals2.EqualsOrdinal(pattern.HourMinuteSep)
&& _literals3.EqualsOrdinal(pattern.End);
/// <summary>HMS (no days or fraction)</summary>
internal bool FullHMSMatch(TimeSpanFormat.FormatLiterals pattern) =>
_sepCount == 4
&& _numCount == 3
&& _literals0.EqualsOrdinal(pattern.Start)
&& _literals1.EqualsOrdinal(pattern.HourMinuteSep)
&& _literals2.EqualsOrdinal(pattern.MinuteSecondSep)
&& _literals3.EqualsOrdinal(pattern.End);
/// <summary>DHMS (no fraction)</summary>
internal bool FullDHMSMatch(TimeSpanFormat.FormatLiterals pattern) =>
_sepCount == 5
&& _numCount == 4
&& _literals0.EqualsOrdinal(pattern.Start)
&& _literals1.EqualsOrdinal(pattern.DayHourSep)
&& _literals2.EqualsOrdinal(pattern.HourMinuteSep)
&& _literals3.EqualsOrdinal(pattern.MinuteSecondSep)
&& _literals4.EqualsOrdinal(pattern.End);
/// <summary>HMSF (no days)</summary>
internal bool FullHMSFMatch(TimeSpanFormat.FormatLiterals pattern) =>
_sepCount == 5
&& _numCount == 4
&& _literals0.EqualsOrdinal(pattern.Start)
&& _literals1.EqualsOrdinal(pattern.HourMinuteSep)
&& _literals2.EqualsOrdinal(pattern.MinuteSecondSep)
&& _literals3.EqualsOrdinal(pattern.SecondFractionSep)
&& _literals4.EqualsOrdinal(pattern.End);
internal TTT _lastSeenTTT;
internal int _tokenCount;
internal int _sepCount;
internal int _numCount;
private TimeSpanFormat.FormatLiterals _posLoc;
private TimeSpanFormat.FormatLiterals _negLoc;
private bool _posLocInit;
private bool _negLocInit;
private string _fullPosPattern;
private string _fullNegPattern;
private const int MaxTokens = 11;
private const int MaxLiteralTokens = 6;
private const int MaxNumericTokens = 5;
internal TimeSpanToken _numbers0, _numbers1, _numbers2, _numbers3, _numbers4; // MaxNumbericTokens = 5
internal ReadOnlySpan<char> _literals0, _literals1, _literals2, _literals3, _literals4, _literals5; // MaxLiteralTokens=6
internal void Init(DateTimeFormatInfo dtfi)
{
Debug.Assert(dtfi != null);
_lastSeenTTT = TTT.None;
_tokenCount = 0;
_sepCount = 0;
_numCount = 0;
_fullPosPattern = dtfi.FullTimeSpanPositivePattern;
_fullNegPattern = dtfi.FullTimeSpanNegativePattern;
_posLocInit = false;
_negLocInit = false;
}
internal bool ProcessToken(ref TimeSpanToken tok, ref TimeSpanResult result)
{
switch (tok._ttt)
{
case TTT.Num:
if ((_tokenCount == 0 && !AddSep(default, ref result)) || !AddNum(tok, ref result))
{
return false;
}
break;
case TTT.Sep:
if (!AddSep(tok._sep, ref result))
{
return false;
}
break;
case TTT.NumOverflow:
return result.SetOverflowFailure();
default:
// Some unknown token or a repeat token type in the input
return result.SetBadTimeSpanFailure();
}
_lastSeenTTT = tok._ttt;
Debug.Assert(_tokenCount == (_sepCount + _numCount), "tokenCount == (SepCount + NumCount)");
return true;
}
private bool AddSep(ReadOnlySpan<char> sep, ref TimeSpanResult result)
{
if (_sepCount >= MaxLiteralTokens || _tokenCount >= MaxTokens)
{
return result.SetBadTimeSpanFailure();
}
switch (_sepCount++)
{
case 0: _literals0 = sep; break;
case 1: _literals1 = sep; break;
case 2: _literals2 = sep; break;
case 3: _literals3 = sep; break;
case 4: _literals4 = sep; break;
default: _literals5 = sep; break;
}
_tokenCount++;
return true;
}
private bool AddNum(TimeSpanToken num, ref TimeSpanResult result)
{
if (_numCount >= MaxNumericTokens || _tokenCount >= MaxTokens)
{
return result.SetBadTimeSpanFailure();
}
switch (_numCount++)
{
case 0: _numbers0 = num; break;
case 1: _numbers1 = num; break;
case 2: _numbers2 = num; break;
case 3: _numbers3 = num; break;
default: _numbers4 = num; break;
}
_tokenCount++;
return true;
}
}
/// <summary>Store the result of the parsing.</summary>
private ref struct TimeSpanResult
{
internal TimeSpan parsedTimeSpan;
private readonly bool _throwOnFailure;
private readonly ReadOnlySpan<char> _originalTimeSpanString;
internal TimeSpanResult(bool throwOnFailure, ReadOnlySpan<char> originalTimeSpanString)
{
parsedTimeSpan = default;
_throwOnFailure = throwOnFailure;
_originalTimeSpanString = originalTimeSpanString;
}
internal bool SetNoFormatSpecifierFailure()
{
if (!_throwOnFailure)
{
return false;
}
throw new FormatException(SR.Format_NoFormatSpecifier);
}
internal bool SetBadQuoteFailure(char failingCharacter)
{
if (!_throwOnFailure)
{
return false;
}
throw new FormatException(SR.Format(SR.Format_BadQuote, failingCharacter));
}
internal bool SetInvalidStringFailure()
{
if (!_throwOnFailure)
{
return false;
}
throw new FormatException(SR.Format_InvalidString);
}
internal bool SetArgumentNullFailure(string argumentName)
{
if (!_throwOnFailure)
{
return false;
}
Debug.Assert(argumentName != null);
throw new ArgumentNullException(argumentName, SR.ArgumentNull_String);
}
internal bool SetOverflowFailure()
{
if (!_throwOnFailure)
{
return false;
}
throw new OverflowException(SR.Format(SR.Overflow_TimeSpanElementTooLarge, new string(_originalTimeSpanString)));
}
internal bool SetBadTimeSpanFailure()
{
if (!_throwOnFailure)
{
return false;
}
throw new FormatException(SR.Format(SR.Format_BadTimeSpan, new string(_originalTimeSpanString)));
}
internal bool SetBadFormatSpecifierFailure(char? formatSpecifierCharacter = null)
{
if (!_throwOnFailure)
{
return false;
}
throw new FormatException(SR.Format(SR.Format_BadFormatSpecifier, formatSpecifierCharacter));
}
}
internal static long Pow10(int pow)
{
switch (pow)
{
case 0: return 1;
case 1: return 10;
case 2: return 100;
case 3: return 1000;
case 4: return 10000;
case 5: return 100000;
case 6: return 1000000;
case 7: return 10000000;
default: return (long)Math.Pow(10, pow);
}
}
private static bool TryTimeToTicks(bool positive, TimeSpanToken days, TimeSpanToken hours, TimeSpanToken minutes, TimeSpanToken seconds, TimeSpanToken fraction, out long result)
{
if (days._num > MaxDays ||
hours._num > MaxHours ||
minutes._num > MaxMinutes ||
seconds._num > MaxSeconds ||
fraction.IsInvalidFraction())
{
result = 0;
return false;
}
long ticks = ((long)days._num * 3600 * 24 + (long)hours._num * 3600 + (long)minutes._num * 60 + seconds._num) * 1000;
if (ticks > InternalGlobalizationHelper.MaxMilliSeconds || ticks < InternalGlobalizationHelper.MinMilliSeconds)
{
result = 0;
return false;
}
// Normalize the fraction component
//
// string representation => (zeroes,num) => resultant fraction ticks
// --------------------- ------------ ------------------------
// ".9999999" => (0,9999999) => 9,999,999 ticks (same as constant maxFraction)
// ".1" => (0,1) => 1,000,000 ticks
// ".01" => (1,1) => 100,000 ticks
// ".001" => (2,1) => 10,000 ticks
long f = fraction._num;
if (f != 0)
{
long lowerLimit = InternalGlobalizationHelper.TicksPerTenthSecond;
if (fraction._zeroes > 0)
{
long divisor = Pow10(fraction._zeroes);
lowerLimit = lowerLimit / divisor;
}
while (f < lowerLimit)
{
f *= 10;
}
}
result = ticks * TimeSpan.TicksPerMillisecond + f;
if (positive && result < 0)
{
result = 0;
return false;
}
return true;
}
internal static TimeSpan Parse(ReadOnlySpan<char> input, IFormatProvider formatProvider)
{
var parseResult = new TimeSpanResult(throwOnFailure: true, originalTimeSpanString: input);
bool success = TryParseTimeSpan(input, TimeSpanStandardStyles.Any, formatProvider, ref parseResult);
Debug.Assert(success, "Should have thrown on failure");
return parseResult.parsedTimeSpan;
}
internal static bool TryParse(ReadOnlySpan<char> input, IFormatProvider formatProvider, out TimeSpan result)
{
var parseResult = new TimeSpanResult(throwOnFailure: false, originalTimeSpanString: input);
if (TryParseTimeSpan(input, TimeSpanStandardStyles.Any, formatProvider, ref parseResult))
{
result = parseResult.parsedTimeSpan;
return true;
}
result = default;
return false;
}
internal static TimeSpan ParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, TimeSpanStyles styles)
{
var parseResult = new TimeSpanResult(throwOnFailure: true, originalTimeSpanString: input);
bool success = TryParseExactTimeSpan(input, format, formatProvider, styles, ref parseResult);
Debug.Assert(success, "Should have thrown on failure");
return parseResult.parsedTimeSpan;
}
internal static bool TryParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
{
var parseResult = new TimeSpanResult(throwOnFailure: false, originalTimeSpanString: input);
if (TryParseExactTimeSpan(input, format, formatProvider, styles, ref parseResult))
{
result = parseResult.parsedTimeSpan;
return true;
}
result = default;
return false;
}
internal static TimeSpan ParseExactMultiple(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles)
{
var parseResult = new TimeSpanResult(throwOnFailure: true, originalTimeSpanString: input);
bool success = TryParseExactMultipleTimeSpan(input, formats, formatProvider, styles, ref parseResult);
Debug.Assert(success, "Should have thrown on failure");
return parseResult.parsedTimeSpan;
}
internal static bool TryParseExactMultiple(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
{
var parseResult = new TimeSpanResult(throwOnFailure: false, originalTimeSpanString: input);
if (TryParseExactMultipleTimeSpan(input, formats, formatProvider, styles, ref parseResult))
{
result = parseResult.parsedTimeSpan;
return true;
}
result = default;
return false;
}
/// <summary>Common private Parse method called by both Parse and TryParse.</summary>
private static bool TryParseTimeSpan(ReadOnlySpan<char> input, TimeSpanStandardStyles style, IFormatProvider formatProvider, ref TimeSpanResult result)
{
input = input.Trim();
if (input.IsEmpty)
{
return result.SetBadTimeSpanFailure();
}
var tokenizer = new TimeSpanTokenizer(input);
var raw = new TimeSpanRawInfo();
raw.Init(DateTimeFormatInfo.GetInstance(formatProvider));
TimeSpanToken tok = tokenizer.GetNextToken();
// The following loop will break out when we reach the end of the str or
// when we can determine that the input is invalid.
while (tok._ttt != TTT.End)
{
if (!raw.ProcessToken(ref tok, ref result))
{
return result.SetBadTimeSpanFailure();
}
tok = tokenizer.GetNextToken();
}
Debug.Assert(tokenizer.EOL);
if (!ProcessTerminalState(ref raw, style, ref result))
{
return result.SetBadTimeSpanFailure();
}
return true;
}
/// <summary>
/// Validate the terminal state of a standard format parse.
/// Sets result.parsedTimeSpan on success.
/// Calculates the resultant TimeSpan from the TimeSpanRawInfo.
/// </summary>
/// <remarks>
/// try => +InvariantPattern, -InvariantPattern, +LocalizedPattern, -LocalizedPattern
/// 1) Verify Start matches
/// 2) Verify End matches
/// 3) 1 number => d
/// 2 numbers => h:m
/// 3 numbers => h:m:s | d.h:m | h:m:.f
/// 4 numbers => h:m:s.f | d.h:m:s | d.h:m:.f
/// 5 numbers => d.h:m:s.f
/// </remarks>
private static bool ProcessTerminalState(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
{
if (raw._lastSeenTTT == TTT.Num)
{
TimeSpanToken tok = new TimeSpanToken();
tok._ttt = TTT.Sep;
if (!raw.ProcessToken(ref tok, ref result))
{
return result.SetBadTimeSpanFailure();
}
}
switch (raw._numCount)
{
case 1: return ProcessTerminal_D(ref raw, style, ref result);
case 2: return ProcessTerminal_HM(ref raw, style, ref result);
case 3: return ProcessTerminal_HM_S_D(ref raw, style, ref result);
case 4: return ProcessTerminal_HMS_F_D(ref raw, style, ref result);
case 5: return ProcessTerminal_DHMSF(ref raw, style, ref result);
default: return result.SetBadTimeSpanFailure();
}
}
/// <summary>Validate the 5-number "Days.Hours:Minutes:Seconds.Fraction" terminal case.</summary>
private static bool ProcessTerminal_DHMSF(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
{
if (raw._sepCount != 6)
{
return result.SetBadTimeSpanFailure();
}
Debug.Assert(raw._numCount == 5);
bool inv = (style & TimeSpanStandardStyles.Invariant) != 0;
bool loc = (style & TimeSpanStandardStyles.Localized) != 0;
bool positive = false;
bool match = false;
if (inv)
{
if (raw.FullMatch(raw.PositiveInvariant))
{
match = true;
positive = true;
}
if (!match && raw.FullMatch(raw.NegativeInvariant))
{
match = true;
positive = false;
}
}
if (loc)
{
if (!match && raw.FullMatch(raw.PositiveLocalized))
{
match = true;
positive = true;
}
if (!match && raw.FullMatch(raw.NegativeLocalized))
{
match = true;
positive = false;
}
}
if (match)
{
long ticks;
if (!TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, raw._numbers4, out ticks))
{
return result.SetOverflowFailure();
}
if (!positive)
{
ticks = -ticks;
if (ticks > 0)
{
return result.SetOverflowFailure();
}
}
result.parsedTimeSpan = new TimeSpan(ticks);
return true;
}
return result.SetBadTimeSpanFailure();
}
/// <summary>
/// Validate the ambiguous 4-number "Hours:Minutes:Seconds.Fraction", "Days.Hours:Minutes:Seconds",
/// or "Days.Hours:Minutes:.Fraction" terminal case.
/// </summary>
private static bool ProcessTerminal_HMS_F_D(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
{
if (raw._sepCount != 5 || (style & TimeSpanStandardStyles.RequireFull) != 0)
{
return result.SetBadTimeSpanFailure();
}
Debug.Assert(raw._numCount == 4);
bool inv = ((style & TimeSpanStandardStyles.Invariant) != 0);
bool loc = ((style & TimeSpanStandardStyles.Localized) != 0);
long ticks = 0;
bool positive = false, match = false, overflow = false;
var zero = new TimeSpanToken(0);
if (inv)
{
if (raw.FullHMSFMatch(raw.PositiveInvariant))
{
positive = true;
match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, out ticks);
overflow = overflow || !match;
}
if (!match && raw.FullDHMSMatch(raw.PositiveInvariant))
{
positive = true;
match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, zero, out ticks);
overflow = overflow || !match;
}
if (!match && raw.FullAppCompatMatch(raw.PositiveInvariant))
{
positive = true;
match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, raw._numbers3, out ticks);
overflow = overflow || !match;
}
if (!match && raw.FullHMSFMatch(raw.NegativeInvariant))
{
positive = false;
match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, out ticks);
overflow = overflow || !match;
}
if (!match && raw.FullDHMSMatch(raw.NegativeInvariant))
{
positive = false;
match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, zero, out ticks);
overflow = overflow || !match;
}
if (!match && raw.FullAppCompatMatch(raw.NegativeInvariant))
{
positive = false;
match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, raw._numbers3, out ticks);
overflow = overflow || !match;
}
}
if (loc)
{
if (!match && raw.FullHMSFMatch(raw.PositiveLocalized))
{
positive = true;
match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, out ticks);
overflow = overflow || !match;
}
if (!match && raw.FullDHMSMatch(raw.PositiveLocalized))
{
positive = true;
match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, zero, out ticks);
overflow = overflow || !match;
}
if (!match && raw.FullAppCompatMatch(raw.PositiveLocalized))
{
positive = true;
match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, raw._numbers3, out ticks);
overflow = overflow || !match;
}
if (!match && raw.FullHMSFMatch(raw.NegativeLocalized))
{
positive = false;
match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, out ticks);
overflow = overflow || !match;
}
if (!match && raw.FullDHMSMatch(raw.NegativeLocalized))
{
positive = false;
match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, zero, out ticks);
overflow = overflow || !match;
}
if (!match && raw.FullAppCompatMatch(raw.NegativeLocalized))
{
positive = false;
match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, raw._numbers3, out ticks);
overflow = overflow || !match;
}
}
if (match)
{
if (!positive)
{
ticks = -ticks;
if (ticks > 0)
{
return result.SetOverflowFailure();
}
}
result.parsedTimeSpan = new TimeSpan(ticks);
return true;
}
return overflow ?
result.SetOverflowFailure() : // we found at least one literal pattern match but the numbers just didn't fit
result.SetBadTimeSpanFailure(); // we couldn't find a thing
}
/// <summary>Validate the ambiguous 3-number "Hours:Minutes:Seconds", "Days.Hours:Minutes", or "Hours:Minutes:.Fraction" terminal case.</summary>
private static bool ProcessTerminal_HM_S_D(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
{
if (raw._sepCount != 4 || (style & TimeSpanStandardStyles.RequireFull) != 0)
{
return result.SetBadTimeSpanFailure();
}
Debug.Assert(raw._numCount == 3);
bool inv = ((style & TimeSpanStandardStyles.Invariant) != 0);
bool loc = ((style & TimeSpanStandardStyles.Localized) != 0);
bool positive = false, match = false, overflow = false;
var zero = new TimeSpanToken(0);
long ticks = 0;
if (inv)
{
if (raw.FullHMSMatch(raw.PositiveInvariant))
{
positive = true;
match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, zero, out ticks);
overflow = overflow || !match;
}
if (!match && raw.FullDHMMatch(raw.PositiveInvariant))
{
positive = true;
match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, zero, out ticks);
overflow = overflow || !match;
}
if (!match && raw.PartialAppCompatMatch(raw.PositiveInvariant))
{
positive = true;
match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, zero, raw._numbers2, out ticks);
overflow = overflow || !match;
}
if (!match && raw.FullHMSMatch(raw.NegativeInvariant))
{
positive = false;
match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, zero, out ticks);
overflow = overflow || !match;
}
if (!match && raw.FullDHMMatch(raw.NegativeInvariant))
{
positive = false;
match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, zero, out ticks);
overflow = overflow || !match;
}
if (!match && raw.PartialAppCompatMatch(raw.NegativeInvariant))
{
positive = false;
match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, zero, raw._numbers2, out ticks);