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(MeasureUnit inputUnit,StringPiece region,StringPiece usage,UErrorCode & status)46 UnitsRouter::UnitsRouter(MeasureUnit inputUnit, StringPiece region, StringPiece usage,
47                          UErrorCode &status) {
48     // TODO: do we want to pass in ConversionRates and UnitPreferences instead
49     // of loading in each UnitsRouter instance? (Or make global?)
50     ConversionRates conversionRates(status);
51     UnitPreferences prefs(status);
52 
53     MeasureUnitImpl inputUnitImpl = MeasureUnitImpl::forMeasureUnitMaybeCopy(inputUnit, status);
54     MeasureUnit baseUnit =
55         (extractCompoundBaseUnit(inputUnitImpl, conversionRates, status)).build(status);
56     CharString category = getUnitCategory(baseUnit.getIdentifier(), status);
57 
58     const UnitPreference *const *unitPreferences;
59     int32_t preferencesCount;
60     prefs.getPreferencesFor(category.data(), usage, region, unitPreferences, preferencesCount, status);
61 
62     for (int i = 0; i < preferencesCount; ++i) {
63         const auto &preference = *unitPreferences[i];
64 
65         MeasureUnitImpl complexTargetUnitImpl =
66             MeasureUnitImpl::forIdentifier(preference.unit.data(), status);
67         if (U_FAILURE(status)) {
68             return;
69         }
70 
71         UnicodeString precision = preference.skeleton;
72 
73         // For now, we only have "precision-increment" in Units Preferences skeleton.
74         // Therefore, we check if the skeleton starts with "precision-increment" and force the program to
75         // fail otherwise.
76         // NOTE:
77         //  It is allowed to have an empty precision.
78         if (!precision.isEmpty() && !precision.startsWith(u"precision-increment", 19)) {
79             status = U_INTERNAL_PROGRAM_ERROR;
80             return;
81         }
82 
83         outputUnits_.emplaceBackAndCheckErrorCode(status,
84                                                   complexTargetUnitImpl.copy(status).build(status));
85         converterPreferences_.emplaceBackAndCheckErrorCode(status, inputUnitImpl, complexTargetUnitImpl,
86                                                            preference.geq, std::move(precision),
87                                                            conversionRates, status);
88 
89         if (U_FAILURE(status)) {
90             return;
91         }
92     }
93 }
94 
route(double quantity,icu::number::impl::RoundingImpl * rounder,UErrorCode & status) const95 RouteResult UnitsRouter::route(double quantity, icu::number::impl::RoundingImpl *rounder, UErrorCode &status) const {
96     // Find the matching preference
97     const ConverterPreference *converterPreference = nullptr;
98     for (int32_t i = 0, n = converterPreferences_.length(); i < n; i++) {
99         converterPreference = converterPreferences_[i];
100         if (converterPreference->converter.greaterThanOrEqual(std::abs(quantity) * (1 + DBL_EPSILON),
101                                                               converterPreference->limit)) {
102             break;
103         }
104     }
105     U_ASSERT(converterPreference != nullptr);
106 
107     // Set up the rounder for this preference's precision
108     if (rounder != nullptr && rounder->fPrecision.isBogus()) {
109         if (converterPreference->precision.length() > 0) {
110             rounder->fPrecision = parseSkeletonToPrecision(converterPreference->precision, status);
111         } else {
112             // We use the same rounding mode as COMPACT notation: known to be a
113             // human-friendly rounding mode: integers, but add a decimal digit
114             // as needed to ensure we have at least 2 significant digits.
115             rounder->fPrecision = Precision::integer().withMinDigits(2);
116         }
117     }
118 
119     return RouteResult(converterPreference->converter.convert(quantity, rounder, status),
120                        converterPreference->targetUnit.copy(status));
121 }
122 
getOutputUnits() const123 const MaybeStackVector<MeasureUnit> *UnitsRouter::getOutputUnits() const {
124     // TODO: consider pulling this from converterPreferences_ and dropping
125     // outputUnits_?
126     return &outputUnits_;
127 }
128 
129 } // namespace units
130 U_NAMESPACE_END
131 
132 #endif /* #if !UCONFIG_NO_FORMATTING */
133