1 // © 2020 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3
4 #include "unicode/utypes.h"
5
6 #if !UCONFIG_NO_FORMATTING
7
8 #include "charstr.h"
9 #include "cmemory.h"
10 #include "cstring.h"
11 #include "measunit_impl.h"
12 #include "number_decimalquantity.h"
13 #include "number_roundingutils.h"
14 #include "resource.h"
15 #include "unicode/measure.h"
16 #include "units_data.h"
17 #include "units_router.h"
18 #include <cmath>
19
20 U_NAMESPACE_BEGIN
21 namespace units {
22
23 using number::Precision;
24 using number::impl::parseIncrementOption;
25
parseSkeletonToPrecision(icu::UnicodeString precisionSkeleton,UErrorCode & status)26 Precision UnitsRouter::parseSkeletonToPrecision(icu::UnicodeString precisionSkeleton,
27 UErrorCode &status) {
28 if (U_FAILURE(status)) {
29 // As a member of UsagePrefsHandler, which is a friend of Precision, we
30 // get access to the default constructor.
31 return {};
32 }
33 constexpr int32_t kSkelPrefixLen = 20;
34 if (!precisionSkeleton.startsWith(UNICODE_STRING_SIMPLE("precision-increment/"))) {
35 status = U_INVALID_FORMAT_ERROR;
36 return {};
37 }
38 U_ASSERT(precisionSkeleton[kSkelPrefixLen - 1] == u'/');
39 StringSegment segment(precisionSkeleton, false);
40 segment.adjustOffset(kSkelPrefixLen);
41 Precision result;
42 parseIncrementOption(segment, result, status);
43 return result;
44 }
45
UnitsRouter(StringPiece inputUnitIdentifier,StringPiece region,StringPiece usage,UErrorCode & status)46 UnitsRouter::UnitsRouter(StringPiece inputUnitIdentifier, StringPiece region, StringPiece usage,
47 UErrorCode &status) {
48 this->init(MeasureUnit::forIdentifier(inputUnitIdentifier, status), region, usage, status);
49 }
50
UnitsRouter(const MeasureUnit & inputUnit,StringPiece region,StringPiece usage,UErrorCode & status)51 UnitsRouter::UnitsRouter(const MeasureUnit &inputUnit, StringPiece region, StringPiece usage,
52 UErrorCode &status) {
53 this->init(std::move(inputUnit), region, usage, status);
54 }
55
init(const MeasureUnit & inputUnit,StringPiece region,StringPiece usage,UErrorCode & status)56 void UnitsRouter::init(const MeasureUnit &inputUnit, StringPiece region, StringPiece usage,
57 UErrorCode &status) {
58
59 if (U_FAILURE(status)) {
60 return;
61 }
62
63 // TODO: do we want to pass in ConversionRates and UnitPreferences instead
64 // of loading in each UnitsRouter instance? (Or make global?)
65 ConversionRates conversionRates(status);
66 UnitPreferences prefs(status);
67
68 MeasureUnitImpl inputUnitImpl = MeasureUnitImpl::forMeasureUnitMaybeCopy(inputUnit, status);
69 MeasureUnit baseUnit =
70 (extractCompoundBaseUnit(inputUnitImpl, conversionRates, status)).build(status);
71 CharString category = getUnitQuantity(baseUnit.getIdentifier(), status);
72 if (U_FAILURE(status)) {
73 return;
74 }
75
76 const UnitPreference *const *unitPreferences;
77 int32_t preferencesCount = 0;
78 prefs.getPreferencesFor(category.toStringPiece(), usage, region, unitPreferences, preferencesCount,
79 status);
80
81 for (int i = 0; i < preferencesCount; ++i) {
82 U_ASSERT(unitPreferences[i] != nullptr);
83 const auto &preference = *unitPreferences[i];
84
85 MeasureUnitImpl complexTargetUnitImpl =
86 MeasureUnitImpl::forIdentifier(preference.unit.data(), status);
87 if (U_FAILURE(status)) {
88 return;
89 }
90
91 UnicodeString precision = preference.skeleton;
92
93 // For now, we only have "precision-increment" in Units Preferences skeleton.
94 // Therefore, we check if the skeleton starts with "precision-increment" and force the program to
95 // fail otherwise.
96 // NOTE:
97 // It is allowed to have an empty precision.
98 if (!precision.isEmpty() && !precision.startsWith(u"precision-increment", 19)) {
99 status = U_INTERNAL_PROGRAM_ERROR;
100 return;
101 }
102
103 outputUnits_.emplaceBackAndCheckErrorCode(status,
104 complexTargetUnitImpl.copy(status).build(status));
105 converterPreferences_.emplaceBackAndCheckErrorCode(status, inputUnitImpl, complexTargetUnitImpl,
106 preference.geq, std::move(precision),
107 conversionRates, status);
108
109 if (U_FAILURE(status)) {
110 return;
111 }
112 }
113 }
114
route(double quantity,icu::number::impl::RoundingImpl * rounder,UErrorCode & status) const115 RouteResult UnitsRouter::route(double quantity, icu::number::impl::RoundingImpl *rounder, UErrorCode &status) const {
116 // Find the matching preference
117 const ConverterPreference *converterPreference = nullptr;
118 for (int32_t i = 0, n = converterPreferences_.length(); i < n; i++) {
119 converterPreference = converterPreferences_[i];
120 if (converterPreference->converter.greaterThanOrEqual(std::abs(quantity) * (1 + DBL_EPSILON),
121 converterPreference->limit)) {
122 break;
123 }
124 }
125 U_ASSERT(converterPreference != nullptr);
126
127 // Set up the rounder for this preference's precision
128 if (rounder != nullptr && rounder->fPrecision.isBogus()) {
129 if (converterPreference->precision.length() > 0) {
130 rounder->fPrecision = parseSkeletonToPrecision(converterPreference->precision, status);
131 } else {
132 // We use the same rounding mode as COMPACT notation: known to be a
133 // human-friendly rounding mode: integers, but add a decimal digit
134 // as needed to ensure we have at least 2 significant digits.
135 rounder->fPrecision = Precision::integer().withMinDigits(2);
136 }
137 }
138
139 return RouteResult(converterPreference->converter.convert(quantity, rounder, status),
140 converterPreference->targetUnit.copy(status));
141 }
142
getOutputUnits() const143 const MaybeStackVector<MeasureUnit> *UnitsRouter::getOutputUnits() const {
144 // TODO: consider pulling this from converterPreferences_ and dropping
145 // outputUnits_?
146 return &outputUnits_;
147 }
148
149 } // namespace units
150 U_NAMESPACE_END
151
152 #endif /* #if !UCONFIG_NO_FORMATTING */
153