-
Notifications
You must be signed in to change notification settings - Fork 330
/
PeriodPattern.cs
391 lines (362 loc) · 18.6 KB
/
PeriodPattern.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
// Copyright 2012 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Annotations;
using NodaTime.Utility;
using System.Text;
using static NodaTime.NodaConstants;
namespace NodaTime.Text
{
/// <summary>
/// Represents a pattern for parsing and formatting <see cref="Period"/> values.
/// </summary>
/// <threadsafety>This type is immutable reference type. See the thread safety section of the user guide for more information.</threadsafety>
[Immutable]
public sealed class PeriodPattern : IPattern<Period>
{
/// <summary>
/// Pattern which uses the normal ISO format for all the supported ISO
/// fields, but extends the time part with "s" for milliseconds, "t" for ticks and "n" for nanoseconds.
/// No normalization is carried out, and a period may contain weeks as well as years, months and days.
/// Each element may also be negative, independently of other elements. This pattern round-trips its
/// values: a parse/format cycle will produce an identical period, including units.
/// </summary>
/// <value>
/// Pattern which uses the normal ISO format for all the supported ISO
/// fields, but extends the time part with "s" for milliseconds, "t" for ticks and "n" for nanoseconds.
/// </value>
public static PeriodPattern Roundtrip { get; } = new PeriodPattern(new RoundtripPatternImpl());
/// <summary>
/// A "normalizing" pattern which abides by the ISO-8601 duration format as far as possible.
/// Weeks are added to the number of days (after multiplying by 7). Time units are normalized
/// (extending into days where necessary), and fractions of seconds are represented within the
/// seconds part. Unlike ISO-8601, which pattern allows for negative values within a period.
/// </summary>
/// <remarks>
/// Note that normalizing the period when formatting will cause an <see cref="System.OverflowException"/>
/// if the period contains more than <see cref="System.Int64.MaxValue"/> ticks when the
/// combined weeks/days/time portions are considered. Such a period could never
/// be useful anyway, however.
/// </remarks>
/// <value>A "normalizing" pattern which abides by the ISO-8601 duration format as far as possible.</value>
public static PeriodPattern NormalizingIso { get; } = new PeriodPattern(new NormalizingIsoPatternImpl());
private readonly IPattern<Period> pattern;
private PeriodPattern(IPattern<Period> pattern)
{
this.pattern = Preconditions.CheckNotNull(pattern, nameof(pattern));
}
/// <summary>
/// Parses the given text value according to the rules of this pattern.
/// </summary>
/// <remarks>
/// This method never throws an exception (barring a bug in Noda Time itself). Even errors such as
/// the argument being null are wrapped in a parse result.
/// </remarks>
/// <param name="text">The text value to parse.</param>
/// <returns>The result of parsing, which may be successful or unsuccessful.</returns>
public ParseResult<Period> Parse([SpecialNullHandling] string text) => pattern.Parse(text);
/// <summary>
/// Formats the given period as text according to the rules of this pattern.
/// </summary>
/// <param name="value">The period to format.</param>
/// <returns>The period formatted according to this pattern.</returns>
public string Format(Period value) => pattern.Format(value);
/// <summary>
/// Formats the given value as text according to the rules of this pattern,
/// appending to the given <see cref="StringBuilder"/>.
/// </summary>
/// <param name="value">The value to format.</param>
/// <param name="builder">The <c>StringBuilder</c> to append to.</param>
/// <returns>The builder passed in as <paramref name="builder"/>.</returns>
public StringBuilder AppendFormat(Period value, StringBuilder builder) => pattern.AppendFormat(value, builder);
private static void AppendValue(StringBuilder builder, long value, char suffix)
{
// Avoid having a load of conditions in the calling code by checking here
if (value == 0)
{
return;
}
FormatHelper.FormatInvariant(value, builder);
builder.Append(suffix);
}
private static ParseResult<Period> InvalidUnit(ValueCursor cursor, char unitCharacter) => ParseResult<Period>.ForInvalidValue(cursor, TextErrorMessages.InvalidUnitSpecifier, unitCharacter);
private static ParseResult<Period> RepeatedUnit(ValueCursor cursor, char unitCharacter) => ParseResult<Period>.ForInvalidValue(cursor, TextErrorMessages.RepeatedUnitSpecifier, unitCharacter);
private static ParseResult<Period> MisplacedUnit(ValueCursor cursor, char unitCharacter) => ParseResult<Period>.ForInvalidValue(cursor, TextErrorMessages.MisplacedUnitSpecifier, unitCharacter);
private sealed class RoundtripPatternImpl : IPattern<Period>
{
public ParseResult<Period> Parse(string text)
{
if (text is null)
{
return ParseResult<Period>.ArgumentNull(nameof(text));
}
if (text.Length == 0)
{
return ParseResult<Period>.ValueStringEmpty;
}
ValueCursor valueCursor = new ValueCursor(text);
valueCursor.MoveNext();
if (valueCursor.Current != 'P')
{
return ParseResult<Period>.MismatchedCharacter(valueCursor, 'P');
}
bool inDate = true;
PeriodBuilder builder = new PeriodBuilder();
PeriodUnits unitsSoFar = 0;
while (valueCursor.MoveNext())
{
if (inDate && valueCursor.Current == 'T')
{
inDate = false;
continue;
}
var failure = valueCursor.ParseInt64<Period>(out long unitValue);
if (failure != null)
{
return failure;
}
if (valueCursor.Length == valueCursor.Index)
{
return ParseResult<Period>.EndOfString(valueCursor);
}
// Various failure cases:
// - Repeated unit (e.g. P1M2M)
// - Time unit is in date part (e.g. P5M)
// - Date unit is in time part (e.g. PT1D)
// - Unit is in incorrect order (e.g. P5D1Y)
// - Unit is invalid (e.g. P5J)
// - Unit is missing (e.g. P5)
PeriodUnits unit;
switch (valueCursor.Current)
{
case 'Y': unit = PeriodUnits.Years; break;
case 'M': unit = inDate ? PeriodUnits.Months : PeriodUnits.Minutes; break;
case 'W': unit = PeriodUnits.Weeks; break;
case 'D': unit = PeriodUnits.Days; break;
case 'H': unit = PeriodUnits.Hours; break;
case 'S': unit = PeriodUnits.Seconds; break;
case 's': unit = PeriodUnits.Milliseconds; break;
case 't': unit = PeriodUnits.Ticks; break;
case 'n': unit = PeriodUnits.Nanoseconds; break;
default: return InvalidUnit(valueCursor, valueCursor.Current);
}
if ((unit & unitsSoFar) != 0)
{
return RepeatedUnit(valueCursor, valueCursor.Current);
}
// This handles putting months before years, for example. Less significant units
// have higher integer representations.
if (unit < unitsSoFar)
{
return MisplacedUnit(valueCursor, valueCursor.Current);
}
// The result of checking "there aren't any time units in this unit" should be
// equal to "we're still in the date part".
if ((unit & PeriodUnits.AllTimeUnits) == 0 != inDate)
{
return MisplacedUnit(valueCursor, valueCursor.Current);
}
builder[unit] = unitValue;
unitsSoFar |= unit;
}
return ParseResult<Period>.ForValue(builder.Build());
}
public string Format(Period value) => AppendFormat(value, new StringBuilder()).ToString();
public StringBuilder AppendFormat(Period value, StringBuilder builder)
{
Preconditions.CheckNotNull(value, nameof(value));
Preconditions.CheckNotNull(builder, nameof(builder));
// Always ensure we've got *some* unit to ensure the result is valid in ISO-8601; arbitrarily pick days.
// Note: "P0S" might be nicer here, but NormalizingIsoPatternImpl picked "P0D" a
// long time ago and we want to be consistent between the two.
// We might want to make both pattern implementations configurable at some point.
if (value.Equals(Period.Zero))
{
builder.Append("P0D");
return builder;
}
builder.Append('P');
AppendValue(builder, value.Years, 'Y');
AppendValue(builder, value.Months, 'M');
AppendValue(builder, value.Weeks, 'W');
AppendValue(builder, value.Days, 'D');
if (value.HasTimeComponent)
{
builder.Append('T');
AppendValue(builder, value.Hours, 'H');
AppendValue(builder, value.Minutes, 'M');
AppendValue(builder, value.Seconds, 'S');
AppendValue(builder, value.Milliseconds, 's');
AppendValue(builder, value.Ticks, 't');
AppendValue(builder, value.Nanoseconds, 'n');
}
return builder;
}
}
private sealed class NormalizingIsoPatternImpl : IPattern<Period>
{
// TODO(misc): Tidy this up a *lot*.
public ParseResult<Period> Parse(string text)
{
if (text is null)
{
return ParseResult<Period>.ArgumentNull(nameof(text));
}
if (text.Length == 0)
{
return ParseResult<Period>.ValueStringEmpty;
}
ValueCursor valueCursor = new ValueCursor(text);
valueCursor.MoveNext();
if (valueCursor.Current != 'P')
{
return ParseResult<Period>.MismatchedCharacter(valueCursor, 'P');
}
bool inDate = true;
PeriodBuilder builder = new PeriodBuilder();
PeriodUnits unitsSoFar = 0;
while (valueCursor.MoveNext())
{
if (inDate && valueCursor.Current == 'T')
{
inDate = false;
continue;
}
bool negative = valueCursor.Current == '-';
var failure = valueCursor.ParseInt64<Period>(out long unitValue);
if (failure != null)
{
return failure;
}
if (valueCursor.Length == valueCursor.Index)
{
return ParseResult<Period>.EndOfString(valueCursor);
}
// Various failure cases:
// - Repeated unit (e.g. P1M2M)
// - Time unit is in date part (e.g. P5M)
// - Date unit is in time part (e.g. PT1D)
// - Unit is in incorrect order (e.g. P5D1Y)
// - Unit is invalid (e.g. P5J)
// - Unit is missing (e.g. P5)
PeriodUnits unit;
switch (valueCursor.Current)
{
case 'Y': unit = PeriodUnits.Years; break;
case 'M': unit = inDate ? PeriodUnits.Months : PeriodUnits.Minutes; break;
case 'W': unit = PeriodUnits.Weeks; break;
case 'D': unit = PeriodUnits.Days; break;
case 'H': unit = PeriodUnits.Hours; break;
case 'S': unit = PeriodUnits.Seconds; break;
case ',':
case '.': unit = PeriodUnits.Nanoseconds; break; // Special handling below
default: return InvalidUnit(valueCursor, valueCursor.Current);
}
if ((unit & unitsSoFar) != 0)
{
return RepeatedUnit(valueCursor, valueCursor.Current);
}
// This handles putting months before years, for example. Less significant units
// have higher integer representations.
if (unit < unitsSoFar)
{
return MisplacedUnit(valueCursor, valueCursor.Current);
}
// The result of checking "there aren't any time units in this unit" should be
// equal to "we're still in the date part".
if ((unit & PeriodUnits.AllTimeUnits) == 0 != inDate)
{
return MisplacedUnit(valueCursor, valueCursor.Current);
}
// Seen a . or , which need special handling.
if (unit == PeriodUnits.Nanoseconds)
{
// Check for already having seen seconds, e.g. PT5S0.5
if ((unitsSoFar & PeriodUnits.Seconds) != 0)
{
return MisplacedUnit(valueCursor, valueCursor.Current);
}
builder.Seconds = unitValue;
if (!valueCursor.MoveNext())
{
return ParseResult<Period>.MissingNumber(valueCursor);
}
// Can cope with at most 999999999 nanoseconds
if (!valueCursor.ParseFraction(9, 9, out int totalNanoseconds, 1))
{
return ParseResult<Period>.MissingNumber(valueCursor);
}
// Use whether or not the seconds value was negative (even if 0)
// as the indication of whether this value is negative.
if (negative)
{
totalNanoseconds = -totalNanoseconds;
}
builder.Milliseconds = (totalNanoseconds / NanosecondsPerMillisecond) % MillisecondsPerSecond;
builder.Ticks = (totalNanoseconds / NanosecondsPerTick) % TicksPerMillisecond;
builder.Nanoseconds = totalNanoseconds % NanosecondsPerTick;
if (valueCursor.Current != 'S')
{
return ParseResult<Period>.MismatchedCharacter(valueCursor, 'S');
}
if (valueCursor.MoveNext())
{
return ParseResult<Period>.ExpectedEndOfString(valueCursor);
}
return ParseResult<Period>.ForValue(builder.Build());
}
builder[unit] = unitValue;
unitsSoFar |= unit;
}
if (unitsSoFar == 0)
{
return ParseResult<Period>.ForInvalidValue(valueCursor, TextErrorMessages.EmptyPeriod);
}
return ParseResult<Period>.ForValue(builder.Build());
}
public string Format(Period value) => AppendFormat(value, new StringBuilder()).ToString();
public StringBuilder AppendFormat(Period value, StringBuilder builder)
{
Preconditions.CheckNotNull(value, nameof(value));
Preconditions.CheckNotNull(builder, nameof(builder));
value = value.Normalize();
// Always ensure we've got *some* unit; arbitrarily pick days.
if (value.Equals(Period.Zero))
{
builder.Append("P0D");
return builder;
}
builder.Append('P');
AppendValue(builder, value.Years, 'Y');
AppendValue(builder, value.Months, 'M');
AppendValue(builder, value.Weeks, 'W');
AppendValue(builder, value.Days, 'D');
if (value.HasTimeComponent)
{
builder.Append('T');
AppendValue(builder, value.Hours, 'H');
AppendValue(builder, value.Minutes, 'M');
long nanoseconds = value.Milliseconds * NanosecondsPerMillisecond + value.Ticks * NanosecondsPerTick + value.Nanoseconds;
long seconds = value.Seconds;
if (nanoseconds != 0 || seconds != 0)
{
if (nanoseconds < 0 || seconds < 0)
{
builder.Append('-');
nanoseconds = -nanoseconds;
seconds = -seconds;
}
FormatHelper.FormatInvariant(seconds, builder);
if (nanoseconds != 0)
{
builder.Append('.');
FormatHelper.AppendFractionTruncate((int) nanoseconds, 9, 9, builder);
}
builder.Append('S');
}
}
return builder;
}
}
}
}