-
Notifications
You must be signed in to change notification settings - Fork 387
/
Copy pathQuantityGenerator.cs
1297 lines (1107 loc) · 55.7 KB
/
QuantityGenerator.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 under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen ([email protected]). Maintained at https://github.com/angularsen/UnitsNet.
using System;
using System.Linq;
using CodeGen.Helpers;
using CodeGen.JsonTypes;
namespace CodeGen.Generators.UnitsNetGen
{
internal class QuantityGenerator : GeneratorBase
{
private readonly Quantity _quantity;
private readonly bool _isDimensionless;
private readonly string _unitEnumName;
private readonly string _valueType;
private readonly Unit _baseUnit;
public QuantityGenerator(Quantity quantity)
{
_quantity = quantity ?? throw new ArgumentNullException(nameof(quantity));
_baseUnit = quantity.Units.FirstOrDefault(u => u.SingularName == _quantity.BaseUnit) ??
throw new ArgumentException($"No unit found with SingularName equal to BaseUnit [{_quantity.BaseUnit}]. This unit must be defined.",
nameof(quantity));
_valueType = quantity.ValueType;
_unitEnumName = $"{quantity.Name}Unit";
BaseDimensions baseDimensions = quantity.BaseDimensions;
_isDimensionless = baseDimensions is { L: 0, M: 0, T: 0, I: 0, Θ: 0, N: 0, J: 0 };
}
public string Generate()
{
Writer.WL(GeneratedFileHeader);
Writer.WL(@"
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using UnitsNet.InternalHelpers;
using UnitsNet.Units;
#nullable enable
// ReSharper disable once CheckNamespace
namespace UnitsNet
{");
Writer.WL($@"
/// <inheritdoc />
/// <summary>
/// {_quantity.XmlDocSummary}
/// </summary>");
Writer.WLCondition(_quantity.XmlDocRemarks.HasText(), $@"
/// <remarks>
/// {_quantity.XmlDocRemarks}
/// </remarks>");
Writer.WLIfText(1, GetObsoleteAttributeOrNull(_quantity));
Writer.WL(@$"
[DataContract]
public readonly partial struct {_quantity.Name} :
{(_quantity.GenerateArithmetic ? "IArithmeticQuantity" : "IQuantity")}<{_quantity.Name}, {_unitEnumName}, {_quantity.ValueType}>,");
if (_quantity.ValueType == "decimal") Writer.WL(@$"
IDecimalQuantity,");
Writer.WL(@$"
IComparable,
IComparable<{_quantity.Name}>,
IConvertible,
IEquatable<{_quantity.Name}>,
IFormattable");
Writer.WL($@"
{{
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
[DataMember(Name = ""Value"", Order = 0)]
private readonly {_quantity.ValueType} _value;
/// <summary>
/// The unit this quantity was constructed with.
/// </summary>
[DataMember(Name = ""Unit"", Order = 1)]
private readonly {_unitEnumName}? _unit;
");
GenerateStaticConstructor();
GenerateInstanceConstructors();
GenerateStaticProperties();
GenerateProperties();
GenerateConversionProperties();
GenerateStaticMethods();
GenerateStaticFactoryMethods();
GenerateStaticParseMethods();
GenerateArithmeticOperators();
GenerateEqualityAndComparison();
GenerateConversionMethods();
GenerateToString();
GenerateIConvertibleMethods();
Writer.WL($@"
}}
}}");
return Writer.ToString();
}
private void GenerateStaticConstructor()
{
BaseDimensions baseDimensions = _quantity.BaseDimensions;
Writer.WL($@"
static {_quantity.Name}()
{{");
Writer.WL(_isDimensionless ? $@"
BaseDimensions = BaseDimensions.Dimensionless;" : $@"
BaseDimensions = new BaseDimensions({baseDimensions.L}, {baseDimensions.M}, {baseDimensions.T}, {baseDimensions.I}, {baseDimensions.Θ}, {baseDimensions.N}, {baseDimensions.J});");
Writer.WL($@"
BaseUnit = {_unitEnumName}.{_quantity.BaseUnit};
Units = Enum.GetValues(typeof({_unitEnumName})).Cast<{_unitEnumName}>().ToArray();
Zero = new {_quantity.Name}(0, BaseUnit);
Info = new QuantityInfo<{_unitEnumName}>(""{_quantity.Name}"",
new UnitInfo<{_unitEnumName}>[]
{{");
foreach (Unit unit in _quantity.Units)
{
BaseUnits? baseUnits = unit.BaseUnits;
if (baseUnits == null)
{
Writer.WL($@"
new UnitInfo<{_unitEnumName}>({_unitEnumName}.{unit.SingularName}, ""{unit.PluralName}"", BaseUnits.Undefined),");
}
else
{
var baseUnitsCtorArgs = string.Join(", ",
new[]
{
baseUnits.L != null ? $"length: LengthUnit.{baseUnits.L}" : null,
baseUnits.M != null ? $"mass: MassUnit.{baseUnits.M}" : null,
baseUnits.T != null ? $"time: DurationUnit.{baseUnits.T}" : null,
baseUnits.I != null ? $"current: ElectricCurrentUnit.{baseUnits.I}" : null,
baseUnits.Θ != null ? $"temperature: TemperatureUnit.{baseUnits.Θ}" : null,
baseUnits.N != null ? $"amount: AmountOfSubstanceUnit.{baseUnits.N}" : null,
baseUnits.J != null ? $"luminousIntensity: LuminousIntensityUnit.{baseUnits.J}" : null
}.Where(str => str != null));
Writer.WL($@"
new UnitInfo<{_unitEnumName}>({_unitEnumName}.{unit.SingularName}, ""{unit.PluralName}"", new BaseUnits({baseUnitsCtorArgs})),");
}
}
Writer.WL($@"
}},
BaseUnit, Zero, BaseDimensions);
DefaultConversionFunctions = new UnitConverter();
RegisterDefaultConversions(DefaultConversionFunctions);
}}
");
}
private void GenerateInstanceConstructors()
{
Writer.WL($@"
/// <summary>
/// Creates the quantity with the given numeric value and unit.
/// </summary>
/// <param name=""value"">The numeric value to construct this quantity with.</param>
/// <param name=""unit"">The unit representation to construct this quantity with.</param>
/// <exception cref=""ArgumentException"">If value is NaN or Infinity.</exception>
public {_quantity.Name}({_quantity.ValueType} value, {_unitEnumName} unit)
{{");
Writer.WL(_quantity.ValueType == "double"
? @"
_value = Guard.EnsureValidNumber(value, nameof(value));"
: @"
_value = value;");
Writer.WL($@"
_unit = unit;
}}
/// <summary>
/// Creates an instance of the quantity with the given numeric value in units compatible with the given <see cref=""UnitSystem""/>.
/// If multiple compatible units were found, the first match is used.
/// </summary>
/// <param name=""value"">The numeric value to construct this quantity with.</param>
/// <param name=""unitSystem"">The unit system to create the quantity with.</param>
/// <exception cref=""ArgumentNullException"">The given <see cref=""UnitSystem""/> is null.</exception>
/// <exception cref=""ArgumentException"">No unit was found for the given <see cref=""UnitSystem""/>.</exception>
public {_quantity.Name}({_valueType} value, UnitSystem unitSystem)
{{
if (unitSystem is null) throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault();
");
Writer.WL(_quantity.ValueType == "double"
? @"
_value = Guard.EnsureValidNumber(value, nameof(value));"
: @"
_value = value;");
Writer.WL($@"
_unit = firstUnitInfo?.Value ?? throw new ArgumentException(""No units were found for the given UnitSystem."", nameof(unitSystem));
}}
");
}
private void GenerateStaticProperties()
{
Writer.WL($@"
#region Static Properties
/// <summary>
/// The <see cref=""UnitConverter"" /> containing the default generated conversion functions for <see cref=""{_quantity.Name}"" /> instances.
/// </summary>
public static UnitConverter DefaultConversionFunctions {{ get; }}
/// <inheritdoc cref=""IQuantity.QuantityInfo""/>
public static QuantityInfo<{_unitEnumName}> Info {{ get; }}
/// <summary>
/// The <see cref=""BaseDimensions"" /> of this quantity.
/// </summary>
public static BaseDimensions BaseDimensions {{ get; }}
/// <summary>
/// The base unit of {_quantity.Name}, which is {_quantity.BaseUnit}. All conversions go via this value.
/// </summary>
public static {_unitEnumName} BaseUnit {{ get; }}
/// <summary>
/// All units of measurement for the {_quantity.Name} quantity.
/// </summary>
public static {_unitEnumName}[] Units {{ get; }}
/// <summary>
/// Gets an instance of this quantity with a value of 0 in the base unit {_quantity.BaseUnit}.
/// </summary>
public static {_quantity.Name} Zero {{ get; }}
");
if (_quantity.GenerateArithmetic)
{
Writer.WL($@"
/// <inheritdoc cref=""Zero""/>
public static {_quantity.Name} AdditiveIdentity => Zero;
");
}
Writer.WL($@"
#endregion
");
}
private void GenerateProperties()
{
Writer.WL($@"
#region Properties
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
public {_valueType} Value => _value;
/// <inheritdoc />
QuantityValue IQuantity.Value => _value;
Enum IQuantity.Unit => Unit;
/// <inheritdoc />
public {_unitEnumName} Unit => _unit.GetValueOrDefault(BaseUnit);
/// <inheritdoc />
public QuantityInfo<{_unitEnumName}> QuantityInfo => Info;
/// <inheritdoc cref=""IQuantity.QuantityInfo""/>
QuantityInfo IQuantity.QuantityInfo => Info;
/// <summary>
/// The <see cref=""BaseDimensions"" /> of this quantity.
/// </summary>
public BaseDimensions Dimensions => {_quantity.Name}.BaseDimensions;
#endregion
");
}
private void GenerateConversionProperties()
{
Writer.WL(@"
#region Conversion Properties
");
foreach (Unit unit in _quantity.Units)
{
if (unit.SkipConversionGeneration) continue;
Writer.WL($@"
/// <summary>
/// Gets a <see cref=""{_quantity.ValueType}""/> value of this quantity converted into <see cref=""{_unitEnumName}.{unit.SingularName}""/>
/// </summary>");
Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit));
Writer.WL($@"
public {_quantity.ValueType} {unit.PluralName} => As({_unitEnumName}.{unit.SingularName});
");
}
Writer.WL(@"
#endregion
");
}
private void GenerateStaticMethods()
{
Writer.WL($@"
#region Static Methods
/// <summary>
/// Registers the default conversion functions in the given <see cref=""UnitConverter""/> instance.
/// </summary>
/// <param name=""unitConverter"">The <see cref=""UnitConverter""/> to register the default conversion functions in.</param>
internal static void RegisterDefaultConversions(UnitConverter unitConverter)
{{
// Register in unit converter: {_unitEnumName} -> BaseUnit");
foreach (Unit unit in _quantity.Units)
{
if (unit.SingularName == _quantity.BaseUnit) continue;
Writer.WL($@"
unitConverter.SetConversionFunction<{_quantity.Name}>({_unitEnumName}.{unit.SingularName}, {_unitEnumName}.{_quantity.BaseUnit}, quantity => quantity.ToUnit({_unitEnumName}.{_quantity.BaseUnit}));");
}
Writer.WL();
Writer.WL($@"
// Register in unit converter: BaseUnit <-> BaseUnit
unitConverter.SetConversionFunction<{_quantity.Name}>({_unitEnumName}.{_quantity.BaseUnit}, {_unitEnumName}.{_quantity.BaseUnit}, quantity => quantity);
// Register in unit converter: BaseUnit -> {_unitEnumName}");
foreach (Unit unit in _quantity.Units)
{
if (unit.SingularName == _quantity.BaseUnit) continue;
Writer.WL($@"
unitConverter.SetConversionFunction<{_quantity.Name}>({_unitEnumName}.{_quantity.BaseUnit}, {_unitEnumName}.{unit.SingularName}, quantity => quantity.ToUnit({_unitEnumName}.{unit.SingularName}));");
}
Writer.WL($@"
}}
internal static void MapGeneratedLocalizations(UnitAbbreviationsCache unitAbbreviationsCache)
{{");
foreach(Unit unit in _quantity.Units)
{
foreach(Localization localization in unit.Localization)
{
// All units must have a unit abbreviation, so fallback to "" for units with no abbreviations defined in JSON
var abbreviationParams = localization.Abbreviations.Any() ?
string.Join(", ", localization.Abbreviations.Select(abbr => $@"""{abbr}""")) :
$@"""""";
Writer.WL($@"
unitAbbreviationsCache.PerformAbbreviationMapping({_unitEnumName}.{unit.SingularName}, new CultureInfo(""{localization.Culture}""), false, {unit.AllowAbbreviationLookup.ToString().ToLower()}, new string[]{{{abbreviationParams}}});");
}
}
Writer.WL($@"
}}
/// <summary>
/// Get unit abbreviation string.
/// </summary>
/// <param name=""unit"">Unit to get abbreviation for.</param>
/// <returns>Unit abbreviation string.</returns>
public static string GetAbbreviation({_unitEnumName} unit)
{{
return GetAbbreviation(unit, null);
}}
/// <summary>
/// Get unit abbreviation string.
/// </summary>
/// <param name=""unit"">Unit to get abbreviation for.</param>
/// <returns>Unit abbreviation string.</returns>
/// <param name=""provider"">Format to use for localization. Defaults to <see cref=""CultureInfo.CurrentCulture"" /> if null.</param>
public static string GetAbbreviation({_unitEnumName} unit, IFormatProvider? provider)
{{
return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider);
}}
#endregion
");
}
private void GenerateStaticFactoryMethods()
{
Writer.WL(@"
#region Static Factory Methods
");
foreach (Unit unit in _quantity.Units)
{
if (unit.SkipConversionGeneration) continue;
var valueParamName = unit.PluralName.ToLowerInvariant();
Writer.WL($@"
/// <summary>
/// Creates a <see cref=""{_quantity.Name}""/> from <see cref=""{_unitEnumName}.{unit.SingularName}""/>.
/// </summary>
/// <exception cref=""ArgumentException"">If value is NaN or Infinity.</exception>");
Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit));
Writer.WL($@"
public static {_quantity.Name} From{unit.PluralName}(QuantityValue {valueParamName})
{{
{_valueType} value = ({_valueType}) {valueParamName};
return new {_quantity.Name}(value, {_unitEnumName}.{unit.SingularName});
}}
");
}
Writer.WL($@"
/// <summary>
/// Dynamically convert from value and unit enum <see cref=""{_unitEnumName}"" /> to <see cref=""{_quantity.Name}"" />.
/// </summary>
/// <param name=""value"">Value to convert from.</param>
/// <param name=""fromUnit"">Unit to convert from.</param>
/// <returns>{_quantity.Name} unit value.</returns>
public static {_quantity.Name} From(QuantityValue value, {_unitEnumName} fromUnit)
{{
return new {_quantity.Name}(({_valueType})value, fromUnit);
}}
#endregion
");
}
private void GenerateStaticParseMethods()
{
Writer.WL($@"
#region Static Parse Methods
/// <summary>
/// Parse a string with one or two quantities of the format ""<quantity> <unit>"".
/// </summary>
/// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param>
/// <example>
/// Length.Parse(""5.5 m"", new CultureInfo(""en-US""));
/// </example>
/// <exception cref=""ArgumentNullException"">The value of 'str' cannot be null. </exception>
/// <exception cref=""ArgumentException"">
/// Expected string to have one or two pairs of quantity and unit in the format
/// ""<quantity> <unit>"". Eg. ""5.5 m"" or ""1ft 2in""
/// </exception>
/// <exception cref=""AmbiguousUnitParseException"">
/// More than one unit is represented by the specified unit abbreviation.
/// Example: Volume.Parse(""1 cup"") will throw, because it can refer to any of
/// <see cref=""VolumeUnit.MetricCup"" />, <see cref=""VolumeUnit.UsLegalCup"" /> and <see cref=""VolumeUnit.UsCustomaryCup"" />.
/// </exception>
/// <exception cref=""UnitsNetException"">
/// If anything else goes wrong, typically due to a bug or unhandled case.
/// We wrap exceptions in <see cref=""UnitsNetException"" /> to allow you to distinguish
/// Units.NET exceptions from other exceptions.
/// </exception>
public static {_quantity.Name} Parse(string str)
{{
return Parse(str, null);
}}
/// <summary>
/// Parse a string with one or two quantities of the format ""<quantity> <unit>"".
/// </summary>
/// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param>
/// <example>
/// Length.Parse(""5.5 m"", new CultureInfo(""en-US""));
/// </example>
/// <exception cref=""ArgumentNullException"">The value of 'str' cannot be null. </exception>
/// <exception cref=""ArgumentException"">
/// Expected string to have one or two pairs of quantity and unit in the format
/// ""<quantity> <unit>"". Eg. ""5.5 m"" or ""1ft 2in""
/// </exception>
/// <exception cref=""AmbiguousUnitParseException"">
/// More than one unit is represented by the specified unit abbreviation.
/// Example: Volume.Parse(""1 cup"") will throw, because it can refer to any of
/// <see cref=""VolumeUnit.MetricCup"" />, <see cref=""VolumeUnit.UsLegalCup"" /> and <see cref=""VolumeUnit.UsCustomaryCup"" />.
/// </exception>
/// <exception cref=""UnitsNetException"">
/// If anything else goes wrong, typically due to a bug or unhandled case.
/// We wrap exceptions in <see cref=""UnitsNetException"" /> to allow you to distinguish
/// Units.NET exceptions from other exceptions.
/// </exception>
/// <param name=""provider"">Format to use when parsing number and unit. Defaults to <see cref=""CultureInfo.CurrentCulture"" /> if null.</param>
public static {_quantity.Name} Parse(string str, IFormatProvider? provider)
{{
return QuantityParser.Default.Parse<{_quantity.Name}, {_unitEnumName}>(
str,
provider,
From);
}}
/// <summary>
/// Try to parse a string with one or two quantities of the format ""<quantity> <unit>"".
/// </summary>
/// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param>
/// <param name=""result"">Resulting unit quantity if successful.</param>
/// <example>
/// Length.Parse(""5.5 m"", new CultureInfo(""en-US""));
/// </example>
public static bool TryParse(string? str, out {_quantity.Name} result)
{{
return TryParse(str, null, out result);
}}
/// <summary>
/// Try to parse a string with one or two quantities of the format ""<quantity> <unit>"".
/// </summary>
/// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param>
/// <param name=""result"">Resulting unit quantity if successful.</param>
/// <returns>True if successful, otherwise false.</returns>
/// <example>
/// Length.Parse(""5.5 m"", new CultureInfo(""en-US""));
/// </example>
/// <param name=""provider"">Format to use when parsing number and unit. Defaults to <see cref=""CultureInfo.CurrentCulture"" /> if null.</param>
public static bool TryParse(string? str, IFormatProvider? provider, out {_quantity.Name} result)
{{
return QuantityParser.Default.TryParse<{_quantity.Name}, {_unitEnumName}>(
str,
provider,
From,
out result);
}}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param>
/// <example>
/// Length.ParseUnit(""m"", new CultureInfo(""en-US""));
/// </example>
/// <exception cref=""ArgumentNullException"">The value of 'str' cannot be null. </exception>
/// <exception cref=""UnitsNetException"">Error parsing string.</exception>
public static {_unitEnumName} ParseUnit(string str)
{{
return ParseUnit(str, null);
}}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param>
/// <param name=""provider"">Format to use when parsing number and unit. Defaults to <see cref=""CultureInfo.CurrentCulture"" /> if null.</param>
/// <example>
/// Length.ParseUnit(""m"", new CultureInfo(""en-US""));
/// </example>
/// <exception cref=""ArgumentNullException"">The value of 'str' cannot be null. </exception>
/// <exception cref=""UnitsNetException"">Error parsing string.</exception>
public static {_unitEnumName} ParseUnit(string str, IFormatProvider? provider)
{{
return UnitParser.Default.Parse<{_unitEnumName}>(str, provider);
}}
/// <inheritdoc cref=""TryParseUnit(string,IFormatProvider,out UnitsNet.Units.{_unitEnumName})""/>
public static bool TryParseUnit(string str, out {_unitEnumName} unit)
{{
return TryParseUnit(str, null, out unit);
}}
/// <summary>
/// Parse a unit string.
/// </summary>
/// <param name=""str"">String to parse. Typically in the form: {{number}} {{unit}}</param>
/// <param name=""unit"">The parsed unit if successful.</param>
/// <returns>True if successful, otherwise false.</returns>
/// <example>
/// Length.TryParseUnit(""m"", new CultureInfo(""en-US""));
/// </example>
/// <param name=""provider"">Format to use when parsing number and unit. Defaults to <see cref=""CultureInfo.CurrentCulture"" /> if null.</param>
public static bool TryParseUnit(string str, IFormatProvider? provider, out {_unitEnumName} unit)
{{
return UnitParser.Default.TryParse<{_unitEnumName}>(str, provider, out unit);
}}
#endregion
");
}
private void GenerateArithmeticOperators()
{
if (!_quantity.GenerateArithmetic) return;
// Logarithmic units required different arithmetic
if (_quantity.Logarithmic)
{
GenerateLogarithmicArithmeticOperators();
return;
}
Writer.WL($@"
#region Arithmetic Operators
/// <summary>Negate the value.</summary>
public static {_quantity.Name} operator -({_quantity.Name} right)
{{
return new {_quantity.Name}(-right.Value, right.Unit);
}}
/// <summary>Get <see cref=""{_quantity.Name}""/> from adding two <see cref=""{_quantity.Name}""/>.</summary>
public static {_quantity.Name} operator +({_quantity.Name} left, {_quantity.Name} right)
{{
return new {_quantity.Name}(left.Value + right.ToUnit(left.Unit).Value, left.Unit);
}}
/// <summary>Get <see cref=""{_quantity.Name}""/> from subtracting two <see cref=""{_quantity.Name}""/>.</summary>
public static {_quantity.Name} operator -({_quantity.Name} left, {_quantity.Name} right)
{{
return new {_quantity.Name}(left.Value - right.ToUnit(left.Unit).Value, left.Unit);
}}
/// <summary>Get <see cref=""{_quantity.Name}""/> from multiplying value and <see cref=""{_quantity.Name}""/>.</summary>
public static {_quantity.Name} operator *({_valueType} left, {_quantity.Name} right)
{{
return new {_quantity.Name}(left * right.Value, right.Unit);
}}
/// <summary>Get <see cref=""{_quantity.Name}""/> from multiplying value and <see cref=""{_quantity.Name}""/>.</summary>
public static {_quantity.Name} operator *({_quantity.Name} left, {_valueType} right)
{{
return new {_quantity.Name}(left.Value * right, left.Unit);
}}
/// <summary>Get <see cref=""{_quantity.Name}""/> from dividing <see cref=""{_quantity.Name}""/> by value.</summary>
public static {_quantity.Name} operator /({_quantity.Name} left, {_valueType} right)
{{
return new {_quantity.Name}(left.Value / right, left.Unit);
}}
/// <summary>Get ratio value from dividing <see cref=""{_quantity.Name}""/> by <see cref=""{_quantity.Name}""/>.</summary>
public static {_quantity.ValueType} operator /({_quantity.Name} left, {_quantity.Name} right)
{{
return left.{_baseUnit.PluralName} / right.{_baseUnit.PluralName};
}}
#endregion
");
}
private void GenerateLogarithmicArithmeticOperators()
{
var scalingFactor = _quantity.LogarithmicScalingFactor;
// Most logarithmic operators need a simple scaling factor of 10. However, certain units such as voltage ratio need to use 20 instead.
var x = (10 * scalingFactor).ToString();
Writer.WL($@"
#region Logarithmic Arithmetic Operators
/// <summary>Negate the value.</summary>
public static {_quantity.Name} operator -({_quantity.Name} right)
{{
return new {_quantity.Name}(-right.Value, right.Unit);
}}
/// <summary>Get <see cref=""{_quantity.Name}""/> from logarithmic addition of two <see cref=""{_quantity.Name}""/>.</summary>
public static {_quantity.Name} operator +({_quantity.Name} left, {_quantity.Name} right)
{{
// Logarithmic addition
// Formula: {x} * log10(10^(x/{x}) + 10^(y/{x}))
return new {_quantity.Name}({x} * Math.Log10(Math.Pow(10, left.Value / {x}) + Math.Pow(10, right.ToUnit(left.Unit).Value / {x})), left.Unit);
}}
/// <summary>Get <see cref=""{_quantity.Name}""/> from logarithmic subtraction of two <see cref=""{_quantity.Name}""/>.</summary>
public static {_quantity.Name} operator -({_quantity.Name} left, {_quantity.Name} right)
{{
// Logarithmic subtraction
// Formula: {x} * log10(10^(x/{x}) - 10^(y/{x}))
return new {_quantity.Name}({x} * Math.Log10(Math.Pow(10, left.Value / {x}) - Math.Pow(10, right.ToUnit(left.Unit).Value / {x})), left.Unit);
}}
/// <summary>Get <see cref=""{_quantity.Name}""/> from logarithmic multiplication of value and <see cref=""{_quantity.Name}""/>.</summary>
public static {_quantity.Name} operator *({_valueType} left, {_quantity.Name} right)
{{
// Logarithmic multiplication = addition
return new {_quantity.Name}(left + right.Value, right.Unit);
}}
/// <summary>Get <see cref=""{_quantity.Name}""/> from logarithmic multiplication of value and <see cref=""{_quantity.Name}""/>.</summary>
public static {_quantity.Name} operator *({_quantity.Name} left, double right)
{{
// Logarithmic multiplication = addition
return new {_quantity.Name}(left.Value + ({_valueType})right, left.Unit);
}}
/// <summary>Get <see cref=""{_quantity.Name}""/> from logarithmic division of <see cref=""{_quantity.Name}""/> by value.</summary>
public static {_quantity.Name} operator /({_quantity.Name} left, double right)
{{
// Logarithmic division = subtraction
return new {_quantity.Name}(left.Value - ({_valueType})right, left.Unit);
}}
/// <summary>Get ratio value from logarithmic division of <see cref=""{_quantity.Name}""/> by <see cref=""{_quantity.Name}""/>.</summary>
public static double operator /({_quantity.Name} left, {_quantity.Name} right)
{{
// Logarithmic division = subtraction
return Convert.ToDouble(left.Value - right.ToUnit(left.Unit).Value);
}}
#endregion
" );
}
private void GenerateEqualityAndComparison()
{
Writer.WL($@"
#region Equality / IComparable
/// <summary>Returns true if less or equal to.</summary>
public static bool operator <=({_quantity.Name} left, {_quantity.Name} right)
{{
return left.Value <= right.ToUnit(left.Unit).Value;
}}
/// <summary>Returns true if greater than or equal to.</summary>
public static bool operator >=({_quantity.Name} left, {_quantity.Name} right)
{{
return left.Value >= right.ToUnit(left.Unit).Value;
}}
/// <summary>Returns true if less than.</summary>
public static bool operator <({_quantity.Name} left, {_quantity.Name} right)
{{
return left.Value < right.ToUnit(left.Unit).Value;
}}
/// <summary>Returns true if greater than.</summary>
public static bool operator >({_quantity.Name} left, {_quantity.Name} right)
{{
return left.Value > right.ToUnit(left.Unit).Value;
}}
// We use obsolete attribute to communicate the preferred equality members to use.
// CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'.
#pragma warning disable CS0809
/// <summary>Indicates strict equality of two <see cref=""{_quantity.Name}""/> quantities, where both <see cref=""Value"" /> and <see cref=""Unit"" /> are exactly equal.</summary>
[Obsolete(""For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals({_quantity.Name} other, {_quantity.Name} tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units."")]
public static bool operator ==({_quantity.Name} left, {_quantity.Name} right)
{{
return left.Equals(right);
}}
/// <summary>Indicates strict inequality of two <see cref=""{_quantity.Name}""/> quantities, where both <see cref=""Value"" /> and <see cref=""Unit"" /> are exactly equal.</summary>
[Obsolete(""For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals({_quantity.Name} other, {_quantity.Name} tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units."")]
public static bool operator !=({_quantity.Name} left, {_quantity.Name} right)
{{
return !(left == right);
}}
/// <inheritdoc />
/// <summary>Indicates strict equality of two <see cref=""{_quantity.Name}""/> quantities, where both <see cref=""Value"" /> and <see cref=""Unit"" /> are exactly equal.</summary>
[Obsolete(""Use Equals({_quantity.Name} other, {_quantity.Name} tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units."")]
public override bool Equals(object? obj)
{{
if (obj is null || !(obj is {_quantity.Name} otherQuantity))
return false;
return Equals(otherQuantity);
}}
/// <inheritdoc />
/// <summary>Indicates strict equality of two <see cref=""{_quantity.Name}""/> quantities, where both <see cref=""Value"" /> and <see cref=""Unit"" /> are exactly equal.</summary>
[Obsolete(""Use Equals({_quantity.Name} other, {_quantity.Name} tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units."")]
public bool Equals({_quantity.Name} other)
{{
return new {{ Value, Unit }}.Equals(new {{ other.Value, other.Unit }});
}}
#pragma warning restore CS0809
/// <summary>Compares the current <see cref=""{_quantity.Name}""/> with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary>
/// <param name=""obj"">An object to compare with this instance.</param>
/// <exception cref=""T:System.ArgumentException"">
/// <paramref name=""obj"" /> is not the same type as this instance.
/// </exception>
/// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings:
/// <list type=""table"">
/// <listheader><term> Value</term><description> Meaning</description></listheader>
/// <item><term> Less than zero</term><description> This instance precedes <paramref name=""obj"" /> in the sort order.</description></item>
/// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name=""obj"" />.</description></item>
/// <item><term> Greater than zero</term><description> This instance follows <paramref name=""obj"" /> in the sort order.</description></item>
/// </list>
/// </returns>
public int CompareTo(object? obj)
{{
if (obj is null) throw new ArgumentNullException(nameof(obj));
if (!(obj is {_quantity.Name} otherQuantity)) throw new ArgumentException(""Expected type {_quantity.Name}."", nameof(obj));
return CompareTo(otherQuantity);
}}
/// <summary>Compares the current <see cref=""{_quantity.Name}""/> with another <see cref=""{_quantity.Name}""/> and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit.</summary>
/// <param name=""other"">A quantity to compare with this instance.</param>
/// <returns>A value that indicates the relative order of the quantities being compared. The return value has these meanings:
/// <list type=""table"">
/// <listheader><term> Value</term><description> Meaning</description></listheader>
/// <item><term> Less than zero</term><description> This instance precedes <paramref name=""other"" /> in the sort order.</description></item>
/// <item><term> Zero</term><description> This instance occurs in the same position in the sort order as <paramref name=""other"" />.</description></item>
/// <item><term> Greater than zero</term><description> This instance follows <paramref name=""other"" /> in the sort order.</description></item>
/// </list>
/// </returns>
public int CompareTo({_quantity.Name} other)
{{
return _value.CompareTo(other.ToUnit(this.Unit).Value);
}}
/// <summary>
/// <para>
/// Compare equality to another {_quantity.Name} within the given absolute or relative tolerance.
/// </para>
/// <para>
/// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and
/// <paramref name=""other""/> as a percentage of this quantity's value. <paramref name=""other""/> will be converted into
/// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of
/// this quantity's value to be considered equal.
/// <example>
/// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm).
/// <code>
/// var a = Length.FromMeters(2.0);
/// var b = Length.FromInches(50.0);
/// a.Equals(b, 0.01, ComparisonType.Relative);
/// </code>
/// </example>
/// </para>
/// <para>
/// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and
/// <paramref name=""other""/> as a fixed number in this quantity's unit. <paramref name=""other""/> will be converted into
/// this quantity's unit for comparison.
/// <example>
/// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm).
/// <code>
/// var a = Length.FromMeters(2.0);
/// var b = Length.FromInches(50.0);
/// a.Equals(b, 0.01, ComparisonType.Absolute);
/// </code>
/// </example>
/// </para>
/// <para>
/// Note that it is advised against specifying zero difference, due to the nature
/// of floating-point operations and using {_valueType} internally.
/// </para>
/// </summary>
/// <param name=""other"">The other quantity to compare to.</param>
/// <param name=""tolerance"">The absolute or relative tolerance value. Must be greater than or equal to 0.</param>
/// <param name=""comparisonType"">The comparison type: either relative or absolute.</param>
/// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns>
[Obsolete(""Use Equals({_quantity.Name} other, {_quantity.Name} tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units."")]
public bool Equals({_quantity.Name} other, {_quantity.ValueType} tolerance, ComparisonType comparisonType)
{{
if (tolerance < 0)
throw new ArgumentOutOfRangeException(nameof(tolerance), ""Tolerance must be greater than or equal to 0."");
return UnitsNet.Comparison.Equals(
referenceValue: this.Value,
otherValue: other.As(this.Unit),
tolerance: tolerance,
comparisonType: ComparisonType.Absolute);
}}
/// <inheritdoc />
public bool Equals(IQuantity? other, IQuantity tolerance)
{{
return other is {_quantity.Name} otherTyped
&& (tolerance is {_quantity.Name} toleranceTyped
? true
: throw new ArgumentException($""Tolerance quantity ({{tolerance.QuantityInfo.Name}}) did not match the other quantities of type '{_quantity.Name}'."", nameof(tolerance)))
&& Equals(otherTyped, toleranceTyped);
}}
/// <inheritdoc />
public bool Equals({_quantity.Name} other, {_quantity.Name} tolerance)
{{
return UnitsNet.Comparison.Equals(
referenceValue: this.Value,
otherValue: other.As(this.Unit),
tolerance: tolerance.As(this.Unit),
comparisonType: ComparisonType.Absolute);
}}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A hash code for the current {_quantity.Name}.</returns>
public override int GetHashCode()
{{
return new {{ Info.Name, Value, Unit }}.GetHashCode();
}}
#endregion
");
}
private void GenerateConversionMethods()
{
Writer.WL($@"
#region Conversion Methods
/// <summary>
/// Convert to the unit representation <paramref name=""unit"" />.
/// </summary>
/// <returns>Value converted to the specified unit.</returns>
public {_quantity.ValueType} As({_unitEnumName} unit)
{{
if (Unit == unit)
return Value;
return ToUnit(unit).Value;
}}
");
if (_quantity.ValueType == "decimal")
{
Writer.WL($@"
double IQuantity<{_unitEnumName}>.As({_unitEnumName} unit)
{{
return (double)As(unit);
}}
");
}
Writer.WL($@"
/// <inheritdoc cref=""IQuantity.As(UnitSystem)""/>
public {_quantity.ValueType} As(UnitSystem unitSystem)
{{
if (unitSystem is null)
throw new ArgumentNullException(nameof(unitSystem));
var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault();
if (firstUnitInfo == null)
throw new ArgumentException(""No units were found for the given UnitSystem."", nameof(unitSystem));
return As(firstUnitInfo.Value);
}}
");
if (_quantity.ValueType == "decimal")
{
Writer.WL($@"
/// <inheritdoc cref=""IQuantity.As(UnitSystem)""/>
double IQuantity.As(UnitSystem unitSystem)
{{
return (double)As(unitSystem);
}}
");
}
Writer.WL($@"
/// <inheritdoc />
double IQuantity.As(Enum unit)
{{
if (!(unit is {_unitEnumName} typedUnit))
throw new ArgumentException($""The given unit is of type {{unit.GetType()}}. Only {{typeof({_unitEnumName})}} is supported."", nameof(unit));
return (double)As(typedUnit);
}}
/// <inheritdoc />
{_quantity.ValueType} IValueQuantity<{_quantity.ValueType}>.As(Enum unit)
{{
if (!(unit is {_unitEnumName} typedUnit))
throw new ArgumentException($""The given unit is of type {{unit.GetType()}}. Only {{typeof({_unitEnumName})}} is supported."", nameof(unit));
return As(typedUnit);
}}
/// <summary>
/// Converts this {_quantity.Name} to another {_quantity.Name} with the unit representation <paramref name=""unit"" />.
/// </summary>
/// <param name=""unit"">The unit to convert to.</param>
/// <returns>A {_quantity.Name} with the specified unit.</returns>
public {_quantity.Name} ToUnit({_unitEnumName} unit)
{{
return ToUnit(unit, DefaultConversionFunctions);
}}
/// <summary>
/// Converts this <see cref=""{_quantity.Name}""/> to another <see cref=""{_quantity.Name}""/> using the given <paramref name=""unitConverter""/> with the unit representation <paramref name=""unit"" />.
/// </summary>
/// <param name=""unit"">The unit to convert to.</param>
/// <param name=""unitConverter"">The <see cref=""UnitConverter""/> to use for the conversion.</param>
/// <returns>A {_quantity.Name} with the specified unit.</returns>