forked from angularsen/UnitsNet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuantityParser.cs
More file actions
317 lines (271 loc) · 13.6 KB
/
QuantityParser.cs
File metadata and controls
317 lines (271 loc) · 13.6 KB
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
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
// ReSharper disable once CheckNamespace
namespace UnitsNet;
/// <summary>
/// A method signature for creating a quantity given a numeric value and a strongly typed unit, for example 1.0 and
/// <see cref="LengthUnit.Meter" />.
/// </summary>
/// <typeparam name="TQuantity">The type of quantity to create, such as <see cref="Length" />.</typeparam>
/// <typeparam name="TUnitType">
/// The type of unit enum that belongs to this quantity, such as <see cref="LengthUnit" /> for
/// <see cref="Length" />.
/// </typeparam>
public delegate TQuantity QuantityFromDelegate<out TQuantity, in TUnitType>(double value, TUnitType fromUnit)
where TQuantity : IQuantity
where TUnitType : struct, Enum;
/// <summary>
/// Parses quantities from strings, such as "1.2 kg" to <see cref="Length" /> or "100 cm" to <see cref="Mass" />.
/// </summary>
public class QuantityParser
{
/// <summary>
/// Allow integer, floating point or exponential number formats.
/// </summary>
private const NumberStyles ParseNumberStyles = NumberStyles.Number | NumberStyles.Float | NumberStyles.AllowExponent;
private readonly UnitParser _unitParser;
/// <summary>
/// Initializes a new instance of the <see cref="QuantityParser" /> class using the specified
/// <see cref="UnitAbbreviationsCache" />.
/// </summary>
/// <param name="unitAbbreviationsCache">
/// The cache containing mappings of units to their abbreviations, used for parsing quantities.
/// </param>
public QuantityParser(UnitAbbreviationsCache unitAbbreviationsCache)
: this(new UnitParser(unitAbbreviationsCache))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="QuantityParser" /> class using the specified <see cref="UnitParser" />.
/// </summary>
/// <param name="unitParser">
/// The unit parser to use for parsing units.
/// </param>
public QuantityParser(UnitParser unitParser)
{
_unitParser = unitParser ?? throw new ArgumentNullException(nameof(unitParser));
}
/// <summary>
/// The default instance of <see cref="QuantityParser" />, which uses the default
/// <see cref="UnitsNetSetup.UnitAbbreviations" /> unit abbreviations.
/// </summary>
public static QuantityParser Default
{
get => UnitsNetSetup.Default.QuantityParser;
}
/// <summary>
/// Parses a quantity from a string, such as "1.2 kg" to <see cref="Length" /> or "100 cm" to <see cref="Mass" />.
/// </summary>
/// <param name="str">The string to parse, such as "1.2 kg".</param>
/// <param name="formatProvider">
/// The culture for looking up localized unit abbreviations for a language, and for parsing
/// the number formatted in this culture. Defaults to <see cref="CultureInfo.CurrentCulture" />.
/// </param>
/// <param name="fromDelegate">A function to create a quantity given a numeric value and a unit enum value.</param>
/// <typeparam name="TQuantity">The type of quantity to create, such as <see cref="Length" />.</typeparam>
/// <typeparam name="TUnitType">
/// The type of unit enum that belongs to this quantity, such as <see cref="LengthUnit" /> for
/// <see cref="Length" />.
/// </typeparam>
/// <returns>The parsed quantity if successful.</returns>
/// <exception cref="ArgumentNullException">The string was null.</exception>
/// <exception cref="FormatException">Failed to parse quantity.</exception>
public TQuantity Parse<TQuantity, TUnitType>(string str, IFormatProvider? formatProvider, QuantityFromDelegate<TQuantity, TUnitType> fromDelegate)
where TQuantity : IQuantity
where TUnitType : struct, Enum
{
if (str == null) throw new ArgumentNullException(nameof(str));
str = str.Trim();
Regex regex = CreateRegexForQuantity<TUnitType>(formatProvider);
if (!TryExtractValueAndUnit(regex, str, out var valueString, out var unitString))
{
throw new FormatException(
"Unable to parse quantity. Expected the form \"{value} {unit abbreviation}\", such as \"5.5 m\". The spacing is optional.")
{
Data = { ["input"] = str }
};
}
return ParseWithRegex(valueString, unitString, fromDelegate, formatProvider);
}
/// <inheritdoc cref="Parse{TQuantity,TUnitType}" />
internal IQuantity Parse(string str, IFormatProvider? formatProvider, QuantityInfo quantityInfo)
{
if (str == null) throw new ArgumentNullException(nameof(str));
str = str.Trim();
Regex regex = CreateRegexForQuantity(quantityInfo.UnitType, formatProvider);
if (!TryExtractValueAndUnit(regex, str, out var valueString, out var unitString))
{
throw new FormatException(
"Unable to parse quantity. Expected the form \"{value} {unit abbreviation}\", such as \"5.5 m\". The spacing is optional.")
{
Data = { ["input"] = str }
};
}
return ParseWithRegex(valueString, unitString, quantityInfo.UnitInfos, formatProvider);
}
/// <summary>
/// Tries to parse a quantity from a string, such as "1.2 kg" to <see cref="Length" /> or "100 cm" to
/// <see cref="Mass" />.
/// </summary>
/// <param name="str">The string to parse, such as "1.2 kg".</param>
/// <param name="formatProvider">
/// The culture for looking up localized unit abbreviations for a language, and for parsing
/// the number formatted in this culture. Defaults to <see cref="CultureInfo.CurrentCulture" />.
/// </param>
/// <param name="fromDelegate">A function to create a quantity given a numeric value and a unit enum value.</param>
/// <param name="result">The parsed quantity if successful, otherwise null.</param>
/// <typeparam name="TQuantity">The type of quantity to create, such as <see cref="Length" />.</typeparam>
/// <typeparam name="TUnitType">
/// The type of unit enum that belongs to this quantity, such as <see cref="LengthUnit" /> for
/// <see cref="Length" />.
/// </typeparam>
/// <returns>True if successful.</returns>
/// <exception cref="ArgumentNullException">The string was null.</exception>
/// <exception cref="FormatException">Failed to parse quantity.</exception>
public bool TryParse<TQuantity, TUnitType>(string? str, IFormatProvider? formatProvider, QuantityFromDelegate<TQuantity, TUnitType> fromDelegate,
[NotNullWhen(true)] out TQuantity? result)
where TQuantity : IQuantity
where TUnitType : struct, Enum
{
result = default;
if (string.IsNullOrWhiteSpace(str)) return false;
str = str!.Trim(); // netstandard2.0 nullable quirk
Regex regex = CreateRegexForQuantity<TUnitType>(formatProvider);
return TryExtractValueAndUnit(regex, str, out var valueString, out var unitString) &&
TryParseWithRegex(valueString, unitString, fromDelegate, formatProvider, out result);
}
/// <inheritdoc cref="TryParse{TQuantity,TUnitType}" />
internal bool TryParse(string? str, IFormatProvider? formatProvider, QuantityInfo quantityInfo, [NotNullWhen(true)] out IQuantity? result)
{
result = null;
if (string.IsNullOrWhiteSpace(str)) return false;
str = str!.Trim(); // netstandard2.0 nullable quirk
Regex regex = CreateRegexForQuantity(quantityInfo.UnitType, formatProvider);
return TryExtractValueAndUnit(regex, str, out var valueString, out var unitString) &&
TryParseWithRegex(valueString, unitString, quantityInfo.UnitInfos, formatProvider, out result);
}
internal string CreateRegexPatternForUnit<TUnitType>(TUnitType unit, IFormatProvider? formatProvider, bool matchEntireString = true)
where TUnitType : struct, Enum
{
IReadOnlyList<string> unitAbbreviations = _unitParser.Abbreviations.GetUnitAbbreviations(unit, formatProvider);
var pattern = GetRegexPatternForUnitAbbreviations(unitAbbreviations);
return matchEntireString ? $"^{pattern}$" : pattern;
}
private static string GetRegexPatternForUnitAbbreviations(IEnumerable<string> abbreviations)
{
var orderedAbbreviations = abbreviations
.OrderByDescending(s => s.Length) // Important to order by length -- if "m" is before "mm" and the input is "mm", it will match just "m"
.Select(Regex.Escape) // Escape special regex characters
.ToArray();
var abbreviationsPiped = $"{string.Join("|", orderedAbbreviations)}";
return $@"(?<value>.*?)\s?(?<unit>{abbreviationsPiped})";
}
/// <summary>
/// Parse a string given a particular regular expression.
/// </summary>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
private TQuantity ParseWithRegex<TQuantity, TUnitType>(string valueString, string unitString, QuantityFromDelegate<TQuantity, TUnitType> fromDelegate,
IFormatProvider? formatProvider)
where TQuantity : IQuantity
where TUnitType : struct, Enum
{
var value = double.Parse(valueString, ParseNumberStyles, formatProvider);
TUnitType parsedUnit = _unitParser.Parse<TUnitType>(unitString, formatProvider);
return fromDelegate(value, parsedUnit);
}
/// <summary>
/// Parse a string given a particular regular expression.
/// </summary>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
private IQuantity ParseWithRegex(string valueString, string unitString, IReadOnlyList<UnitInfo> units, IFormatProvider? formatProvider)
{
var value = double.Parse(valueString, ParseNumberStyles, formatProvider);
UnitInfo unitInfo = _unitParser.Parse(unitString, units, formatProvider);
return unitInfo.From(value);
}
/// <summary>
/// Parse a string given a particular regular expression.
/// </summary>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
private bool TryParseWithRegex<TQuantity, TUnitType>(string? valueString, string? unitString, QuantityFromDelegate<TQuantity, TUnitType> fromDelegate,
IFormatProvider? formatProvider, [NotNullWhen(true)] out TQuantity? result)
where TQuantity : IQuantity
where TUnitType : struct, Enum
{
result = default;
if (!double.TryParse(valueString, ParseNumberStyles, formatProvider, out var value))
{
return false;
}
if (!_unitParser.TryParse(unitString, formatProvider, out TUnitType parsedUnit))
{
return false;
}
result = fromDelegate(value, parsedUnit);
return true;
}
/// <summary>
/// Parse a string given a particular regular expression.
/// </summary>
/// <exception cref="UnitsNetException">Error parsing string.</exception>
private bool TryParseWithRegex(string? valueString, string? unitString, IReadOnlyList<UnitInfo> units, IFormatProvider? formatProvider,
[NotNullWhen(true)] out IQuantity? result)
{
result = null;
if (!double.TryParse(valueString, ParseNumberStyles, formatProvider, out var value))
{
return false;
}
if (!_unitParser.TryParse(unitString, units, formatProvider, out UnitInfo? parsedUnit))
{
return false;
}
result = parsedUnit.From(value);
return true;
}
private static bool TryExtractValueAndUnit(Regex regex, string str, [NotNullWhen(true)] out string? valueString, [NotNullWhen(true)] out string? unitString)
{
Match match = regex.Match(str);
// the regex coming in contains all allowed units as strings.
// That means if the unit in str is not formatted right
// the regex.Match will either put str or string.empty into Groups[0] and Groups[1]
// Therefore a mismatch can be detected by comparing the values of this two groups.
if (match.Groups[0].Value == match.Groups[1].Value)
{
str = UnitParser.NormalizeUnitString(str);
match = regex.Match(str);
}
GroupCollection groups = match.Groups;
Group valueGroup = groups["value"];
Group unitGroup = groups["unit"];
if (!valueGroup.Success || !unitGroup.Success)
{
valueString = null;
unitString = null;
return false;
}
valueString = valueGroup.Value;
unitString = unitGroup.Value;
return true;
}
private string CreateRegexPatternForQuantity(Type unitType, IFormatProvider? formatProvider)
{
IReadOnlyList<string> unitAbbreviations = _unitParser.Abbreviations.GetAllUnitAbbreviationsForQuantity(unitType, formatProvider);
var pattern = GetRegexPatternForUnitAbbreviations(unitAbbreviations);
// Match entire string exactly
return $"^{pattern}$";
}
private Regex CreateRegexForQuantity(Type unitType, IFormatProvider? formatProvider)
{
var pattern = CreateRegexPatternForQuantity(unitType, formatProvider);
return new Regex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
}
private Regex CreateRegexForQuantity<TUnitType>(IFormatProvider? formatProvider)
where TUnitType : struct, Enum
{
return CreateRegexForQuantity(typeof(TUnitType), formatProvider);
}
}