Debian Codegraph @

intl/icu/source/i18n/units_converter.cpp

raw
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 #ifdef JS_HAS_INTL_API
11 #include "double-conversion/string-to-double.h"
12 #else
13 #include "double-conversion-string-to-double.h"
14 #endif
15 #include "measunit_impl.h"
16 #include "putilimp.h"
17 #include "uassert.h"
18 #include "unicode/errorcode.h"
19 #include "unicode/localpointer.h"
20 #include "unicode/stringpiece.h"
21 #include "units_converter.h"
22 #include <algorithm>
23 #include <cmath>
24 #include <stdlib.h>
25 #include <utility>
26
27 U_NAMESPACE_BEGIN
28 namespace units {
29
30 void U_I18N_API Factor::multiplyBy(const Factor &rhs) {
31 factorNum *= rhs.factorNum;
32 factorDen *= rhs.factorDen;
33 for (int i = 0; i < CONSTANTS_COUNT; i++) {
34 constantExponents[i] += rhs.constantExponents[i];
35 }
36
37 // NOTE
38 // We need the offset when the source and the target are simple units. e.g. the source is
39 // celsius and the target is Fahrenheit. Therefore, we just keep the value using `std::max`.
40 offset = std::max(rhs.offset, offset);
41 }
42
43 void U_I18N_API Factor::divideBy(const Factor &rhs) {
44 factorNum *= rhs.factorDen;
45 factorDen *= rhs.factorNum;
46 for (int i = 0; i < CONSTANTS_COUNT; i++) {
47 constantExponents[i] -= rhs.constantExponents[i];
48 }
49
50 // NOTE
51 // We need the offset when the source and the target are simple units. e.g. the source is
52 // celsius and the target is Fahrenheit. Therefore, we just keep the value using `std::max`.
53 offset = std::max(rhs.offset, offset);
54 }
55
56 void U_I18N_API Factor::divideBy(const uint64_t constant) { factorDen *= constant; }
57
58 void U_I18N_API Factor::power(int32_t power) {
59 // multiply all the constant by the power.
60 for (int i = 0; i < CONSTANTS_COUNT; i++) {
61 constantExponents[i] *= power;
62 }
63
64 bool shouldFlip = power < 0; // This means that after applying the absolute power, we should flip
65 // the Numerator and Denominator.
66
67 factorNum = std::pow(factorNum, std::abs(power));
68 factorDen = std::pow(factorDen, std::abs(power));
69
70 if (shouldFlip) {
71 // Flip Numerator and Denominator.
72 std::swap(factorNum, factorDen);
73 }
74 }
75
76 void U_I18N_API Factor::applyPrefix(UMeasurePrefix unitPrefix) {
77 if (unitPrefix == UMeasurePrefix::UMEASURE_PREFIX_ONE) {
78 // No need to do anything
79 return;
80 }
81
82 int32_t prefixPower = umeas_getPrefixPower(unitPrefix);
83 double prefixFactor = std::pow(static_cast<double>(umeas_getPrefixBase(unitPrefix)),
84 static_cast<double>(std::abs(prefixPower)));
85 if (prefixPower >= 0) {
86 factorNum *= prefixFactor;
87 } else {
88 factorDen *= prefixFactor;
89 }
90 }
91
92 void U_I18N_API Factor::substituteConstants() {
93 for (int i = 0; i < CONSTANTS_COUNT; i++) {
94 if (this->constantExponents[i] == 0) {
95 continue;
96 }
97
98 auto absPower = std::abs(this->constantExponents[i]);
99 Signum powerSig = this->constantExponents[i] < 0 ? Signum::NEGATIVE : Signum::POSITIVE;
100 double absConstantValue = std::pow(constantsValues[i], absPower);
101
102 if (powerSig == Signum::NEGATIVE) {
103 this->factorDen *= absConstantValue;
104 } else {
105 this->factorNum *= absConstantValue;
106 }
107
108 this->constantExponents[i] = 0;
109 }
110 }
111
112 namespace {
113
114 /* Helpers */
115
116 #ifdef JS_HAS_INTL_API
117 using double_conversion::StringToDoubleConverter;
118 #else
119 using icu::double_conversion::StringToDoubleConverter;
120 #endif
121
122 // TODO: Make this a shared-utility function.
123 // Returns `double` from a scientific number(i.e. "1", "2.01" or "3.09E+4")
124 double strToDouble(StringPiece strNum, UErrorCode &status) {
125 // We are processing well-formed input, so we don't need any special options to
126 // StringToDoubleConverter.
127 StringToDoubleConverter converter(0, 0, 0, "", "");
128 int32_t count;
129 double result = converter.StringToDouble(strNum.data(), strNum.length(), &count);
130 if (count != strNum.length()) {
131 status = U_INVALID_FORMAT_ERROR;
132 }
133
134 return result;
135 }
136
137 // Returns `double` from a scientific number that could has a division sign (i.e. "1", "2.01", "3.09E+4"
138 // or "2E+2/3")
139 double strHasDivideSignToDouble(StringPiece strWithDivide, UErrorCode &status) {
140 int divisionSignInd = -1;
141 for (int i = 0, n = strWithDivide.length(); i < n; ++i) {
142 if (strWithDivide.data()[i] == '/') {
143 divisionSignInd = i;
144 break;
145 }
146 }
147
148 if (divisionSignInd >= 0) {
149 return strToDouble(strWithDivide.substr(0, divisionSignInd), status) /
150 strToDouble(strWithDivide.substr(divisionSignInd + 1), status);
151 }
152
153 return strToDouble(strWithDivide, status);
154 }
155
156 /*
157 Adds single factor to a `Factor` object. Single factor means "23^2", "23.3333", "ft2m^3" ...etc.
158 However, complex factor are not included, such as "ft2m^3*200/3"
159 */
160 void addFactorElement(Factor &factor, StringPiece elementStr, Signum signum, UErrorCode &status) {
161 StringPiece baseStr;
162 StringPiece powerStr;
163 int32_t power =
164 1; // In case the power is not written, then, the power is equal 1 ==> `ft2m^1` == `ft2m`
165
166 // Search for the power part
167 int32_t powerInd = -1;
168 for (int32_t i = 0, n = elementStr.length(); i < n; ++i) {
169 if (elementStr.data()[i] == '^') {
170 powerInd = i;
171 break;
172 }
173 }
174
175 if (powerInd > -1) {
176 // There is power
177 baseStr = elementStr.substr(0, powerInd);
178 powerStr = elementStr.substr(powerInd + 1);
179
180 power = static_cast<int32_t>(strToDouble(powerStr, status));
181 } else {
182 baseStr = elementStr;
183 }
184
185 addSingleFactorConstant(baseStr, power, signum, factor, status);
186 }
187
188 /*
189 * Extracts `Factor` from a complete string factor. e.g. "ft2m^3*1007/cup2m3*3"
190 */
191 Factor extractFactorConversions(StringPiece stringFactor, UErrorCode &status) {
192 Factor result;
193 Signum signum = Signum::POSITIVE;
194 const auto* factorData = stringFactor.data();
195 for (int32_t i = 0, start = 0, n = stringFactor.length(); i < n; i++) {
196 if (factorData[i] == '*' || factorData[i] == '/') {
197 StringPiece factorElement = stringFactor.substr(start, i - start);
198 addFactorElement(result, factorElement, signum, status);
199
200 start = i + 1; // Set `start` to point to the start of the new element.
201 } else if (i == n - 1) {
202 // Last element
203 addFactorElement(result, stringFactor.substr(start, i + 1), signum, status);
204 }
205
206 if (factorData[i] == '/') {
207 signum = Signum::NEGATIVE; // Change the signum because we reached the Denominator.
208 }
209 }
210
211 return result;
212 }
213
214 // Load factor for a single source
215 Factor loadSingleFactor(StringPiece source, const ConversionRates &ratesInfo, UErrorCode &status) {
216 const auto* const conversionUnit = ratesInfo.extractConversionInfo(source, status);
217 if (U_FAILURE(status)) return {};
218 if (conversionUnit == nullptr) {
219 status = U_INTERNAL_PROGRAM_ERROR;
220 return {};
221 }
222
223 Factor result = extractFactorConversions(conversionUnit->factor.toStringPiece(), status);
224 result.offset = strHasDivideSignToDouble(conversionUnit->offset.toStringPiece(), status);
225
226 return result;
227 }
228
229 // Load Factor of a compound source unit.
230 // In ICU4J, this is a pair of ConversionRates.getFactorToBase() functions.
231 Factor loadCompoundFactor(const MeasureUnitImpl &source, const ConversionRates &ratesInfo,
232 UErrorCode &status) {
233
234 Factor result;
235 for (int32_t i = 0, n = source.singleUnits.length(); i < n; i++) {
236 SingleUnitImpl singleUnit = *source.singleUnits[i];
237
238 Factor singleFactor = loadSingleFactor(singleUnit.getSimpleUnitID(), ratesInfo, status);
239 if (U_FAILURE(status)) return result;
240
241 // Prefix before power, because:
242 // - square-kilometer to square-meter: (1000)^2
243 // - square-kilometer to square-foot (approximate): (3.28*1000)^2
244 singleFactor.applyPrefix(singleUnit.unitPrefix);
245
246 // Apply the power of the `dimensionality`
247 singleFactor.power(singleUnit.dimensionality);
248
249 result.multiplyBy(singleFactor);
250 }
251
252 // If the source has a constant denominator, then we need to divide the
253 // factor by the constant denominator.
254 if (source.constantDenominator != 0) {
255 result.divideBy(source.constantDenominator);
256 }
257
258 return result;
259 }
260
261 /**
262 * Checks if the source unit and the target unit are simple. For example celsius or fahrenheit. But not
263 * square-celsius or square-fahrenheit.
264 *
265 * NOTE:
266 * Empty unit means simple unit.
267 *
268 * In ICU4J, this is ConversionRates.checkSimpleUnit().
269 */
270 UBool checkSimpleUnit(const MeasureUnitImpl &unit, UErrorCode &status) {
271 if (U_FAILURE(status)) return false;
272
273 if (unit.complexity != UMEASURE_UNIT_SINGLE) {
274 return false;
275 }
276 if (unit.singleUnits.length() == 0) {
277 // Empty units means simple unit.
278 return true;
279 }
280
281 auto singleUnit = *(unit.singleUnits[0]);
282
283 if (singleUnit.dimensionality != 1 || singleUnit.unitPrefix != UMEASURE_PREFIX_ONE) {
284 return false;
285 }
286
287 return true;
288 }
289
290 // Map the MeasureUnitImpl for a simpleUnit to a SingleUnitImpl, then use that
291 // SingleUnitImpl's simpleUnitID to get the corresponding ConversionRateInfo;
292 // from that we get the specialMappingName (which may be empty if the simple unit
293 // converts to base using factor + offset instelad of a special mapping).
294 CharString getSpecialMappingName(const MeasureUnitImpl &simpleUnit, const ConversionRates &ratesInfo,
295 UErrorCode &status) {
296 if (!checkSimpleUnit(simpleUnit, status)) {
297 return {};
298 }
299 SingleUnitImpl singleUnit = *simpleUnit.singleUnits[0];
300 const auto* const conversionUnit =
301 ratesInfo.extractConversionInfo(singleUnit.getSimpleUnitID(), status);
302 if (U_FAILURE(status)) {
303 return {};
304 }
305 if (conversionUnit == nullptr) {
306 status = U_INTERNAL_PROGRAM_ERROR;
307 return {};
308 }
309 CharString result;
310 result.copyFrom(conversionUnit->specialMappingName, status);
311 return result;
312 }
313
314 /**
315 * Extract conversion rate from `source` to `target`
316 */
317 // In ICU4J, this function is partially inlined in the UnitsConverter constructor.
318 // TODO ICU-22683: Consider splitting handling of special mappings into separate class
319 void loadConversionRate(ConversionRate &conversionRate, const MeasureUnitImpl &source,
320 const MeasureUnitImpl &target, Convertibility unitsState,
321 const ConversionRates &ratesInfo, UErrorCode &status) {
322
323 conversionRate.specialSource = getSpecialMappingName(source, ratesInfo, status);
324 conversionRate.specialTarget = getSpecialMappingName(target, ratesInfo, status);
325
326 if (conversionRate.specialSource.isEmpty() && conversionRate.specialTarget.isEmpty()) {
327 // Represents the conversion factor from the source to the target.
328 Factor finalFactor;
329
330 // Represents the conversion factor from the source to the base unit that specified in the conversion
331 // data which is considered as the root of the source and the target.
332 Factor sourceToBase = loadCompoundFactor(source, ratesInfo, status);
333 Factor targetToBase = loadCompoundFactor(target, ratesInfo, status);
334
335 // Merger Factors
336 finalFactor.multiplyBy(sourceToBase);
337 if (unitsState == Convertibility::CONVERTIBLE) {
338 finalFactor.divideBy(targetToBase);
339 } else if (unitsState == Convertibility::RECIPROCAL) {
340 finalFactor.multiplyBy(targetToBase);
341 } else {
342 status = UErrorCode::U_ARGUMENT_TYPE_MISMATCH;
343 return;
344 }
345
346 finalFactor.substituteConstants();
347
348 conversionRate.factorNum = finalFactor.factorNum;
349 conversionRate.factorDen = finalFactor.factorDen;
350
351 // This code corresponds to ICU4J's ConversionRates.getOffset().
352 // In case of simple units (such as: celsius or fahrenheit), offsets are considered.
353 if (checkSimpleUnit(source, status) && checkSimpleUnit(target, status)) {
354 conversionRate.sourceOffset =
355 sourceToBase.offset * sourceToBase.factorDen / sourceToBase.factorNum;
356 conversionRate.targetOffset =
357 targetToBase.offset * targetToBase.factorDen / targetToBase.factorNum;
358 }
359 // TODO(icu-units#127): should we consider failure if there's an offset for
360 // a not-simple-unit? What about kilokelvin / kilocelsius?
361
362 conversionRate.reciprocal = unitsState == Convertibility::RECIPROCAL;
363 } else if (conversionRate.specialSource.isEmpty() || conversionRate.specialTarget.isEmpty()) {
364 // Still need to set factorNum/factorDen for either source to base or base to target
365 if (unitsState != Convertibility::CONVERTIBLE) {
366 status = UErrorCode::U_ARGUMENT_TYPE_MISMATCH;
367 return;
368 }
369 Factor finalFactor;
370 if (conversionRate.specialSource.isEmpty()) {
371 // factorNum/factorDen is for source to base only
372 finalFactor = loadCompoundFactor(source, ratesInfo, status);
373 } else {
374 // factorNum/factorDen is for base to target only
375 finalFactor = loadCompoundFactor(target, ratesInfo, status);
376 }
377 finalFactor.substituteConstants();
378 conversionRate.factorNum = finalFactor.factorNum;
379 conversionRate.factorDen = finalFactor.factorDen;
380 }
381 }
382
383 struct UnitIndexAndDimension : UMemory {
384 int32_t index = 0;
385 int32_t dimensionality = 0;
386
387 UnitIndexAndDimension(const SingleUnitImpl &singleUnit, int32_t multiplier) {
388 index = singleUnit.index;
389 dimensionality = singleUnit.dimensionality * multiplier;
390 }
391 };
392
393 void mergeSingleUnitWithDimension(MaybeStackVector<UnitIndexAndDimension> &unitIndicesWithDimension,
394 const SingleUnitImpl &shouldBeMerged, int32_t multiplier) {
395 for (int32_t i = 0; i < unitIndicesWithDimension.length(); i++) {
396 auto &unitWithIndex = *unitIndicesWithDimension[i];
397 if (unitWithIndex.index == shouldBeMerged.index) {
398 unitWithIndex.dimensionality += shouldBeMerged.dimensionality * multiplier;
399 return;
400 }
401 }
402
403 unitIndicesWithDimension.emplaceBack(shouldBeMerged, multiplier);
404 }
405
406 void mergeUnitsAndDimensions(MaybeStackVector<UnitIndexAndDimension> &unitIndicesWithDimension,
407 const MeasureUnitImpl &shouldBeMerged, int32_t multiplier) {
408 for (int32_t unit_i = 0; unit_i < shouldBeMerged.singleUnits.length(); unit_i++) {
409 auto singleUnit = *shouldBeMerged.singleUnits[unit_i];
410 mergeSingleUnitWithDimension(unitIndicesWithDimension, singleUnit, multiplier);
411 }
412 }
413
414 UBool checkAllDimensionsAreZeros(const MaybeStackVector<UnitIndexAndDimension> &dimensionVector) {
415 for (int32_t i = 0; i < dimensionVector.length(); i++) {
416 if (dimensionVector[i]->dimensionality != 0) {
417 return false;
418 }
419 }
420
421 return true;
422 }
423
424 } // namespace
425
426 // Conceptually, this modifies factor: factor *= baseStr^(signum*power).
427 //
428 // baseStr must be a known constant or a value that strToDouble() is able to
429 // parse.
430 void U_I18N_API addSingleFactorConstant(StringPiece baseStr, int32_t power, Signum signum,
431 Factor &factor, UErrorCode &status) {
432 if (baseStr == "ft_to_m") {
433 factor.constantExponents[CONSTANT_FT2M] += power * signum;
434 } else if (baseStr == "ft2_to_m2") {
435 factor.constantExponents[CONSTANT_FT2M] += 2 * power * signum;
436 } else if (baseStr == "ft3_to_m3") {
437 factor.constantExponents[CONSTANT_FT2M] += 3 * power * signum;
438 } else if (baseStr == "in3_to_m3") {
439 factor.constantExponents[CONSTANT_FT2M] += 3 * power * signum;
440 factor.factorDen *= std::pow(12 * 12 * 12, power * signum);
441 } else if (baseStr == "gal_to_m3") {
442 factor.constantExponents[CONSTANT_FT2M] += 3 * power * signum;
443 factor.factorNum *= std::pow(231, power * signum);
444 factor.factorDen *= std::pow(12 * 12 * 12, power * signum);
445 } else if (baseStr == "gal_imp_to_m3") {
446 factor.constantExponents[CONSTANT_GAL_IMP2M3] += power * signum;
447 } else if (baseStr == "G") {
448 factor.constantExponents[CONSTANT_G] += power * signum;
449 } else if (baseStr == "gravity") {
450 factor.constantExponents[CONSTANT_GRAVITY] += power * signum;
451 } else if (baseStr == "lb_to_kg") {
452 factor.constantExponents[CONSTANT_LB2KG] += power * signum;
453 } else if (baseStr == "glucose_molar_mass") {
454 factor.constantExponents[CONSTANT_GLUCOSE_MOLAR_MASS] += power * signum;
455 } else if (baseStr == "item_per_mole") {
456 factor.constantExponents[CONSTANT_ITEM_PER_MOLE] += power * signum;
457 } else if (baseStr == "meters_per_AU") {
458 factor.constantExponents[CONSTANT_METERS_PER_AU] += power * signum;
459 } else if (baseStr == "PI") {
460 factor.constantExponents[CONSTANT_PI] += power * signum;
461 } else if (baseStr == "sec_per_julian_year") {
462 factor.constantExponents[CONSTANT_SEC_PER_JULIAN_YEAR] += power * signum;
463 } else if (baseStr == "speed_of_light_meters_per_second") {
464 factor.constantExponents[CONSTANT_SPEED_OF_LIGHT_METERS_PER_SECOND] += power * signum;
465 } else if (baseStr == "sho_to_m3") {
466 factor.constantExponents[CONSTANT_SHO_TO_M3] += power * signum;
467 } else if (baseStr == "tsubo_to_m2") {
468 factor.constantExponents[CONSTANT_TSUBO_TO_M2] += power * signum;
469 } else if (baseStr == "shaku_to_m") {
470 factor.constantExponents[CONSTANT_SHAKU_TO_M] += power * signum;
471 } else if (baseStr == "AMU") {
472 factor.constantExponents[CONSTANT_AMU] += power * signum;
473 } else {
474 if (signum == Signum::NEGATIVE) {
475 factor.factorDen *= std::pow(strToDouble(baseStr, status), power);
476 } else {
477 factor.factorNum *= std::pow(strToDouble(baseStr, status), power);
478 }
479 }
480 }
481
482 /**
483 * Extracts the compound base unit of a compound unit (`source`). For example, if the source unit is
484 * `square-mile-per-hour`, the compound base unit will be `square-meter-per-second`
485 */
486 MeasureUnitImpl U_I18N_API extractCompoundBaseUnit(const MeasureUnitImpl &source,
487 const ConversionRates &conversionRates,
488 UErrorCode &status) {
489
490 MeasureUnitImpl result;
491 if (U_FAILURE(status)) return result;
492
493 const auto &singleUnits = source.singleUnits;
494 for (int i = 0, count = singleUnits.length(); i < count; ++i) {
495 const auto &singleUnit = *singleUnits[i];
496 // Extract `ConversionRateInfo` using the absolute unit. For example: in case of `square-meter`,
497 // we will use `meter`
498 const auto* const rateInfo =
499 conversionRates.extractConversionInfo(singleUnit.getSimpleUnitID(), status);
500 if (U_FAILURE(status)) {
501 return result;
502 }
503 if (rateInfo == nullptr) {
504 status = U_INTERNAL_PROGRAM_ERROR;
505 return result;
506 }
507
508 // Multiply the power of the singleUnit by the power of the baseUnit. For example, square-hectare
509 // must be pow4-meter. (NOTE: hectare --> square-meter)
510 auto baseUnits =
511 MeasureUnitImpl::forIdentifier(rateInfo->baseUnit.toStringPiece(), status).singleUnits;
512 for (int32_t i = 0, baseUnitsCount = baseUnits.length(); i < baseUnitsCount; i++) {
513 baseUnits[i]->dimensionality *= singleUnit.dimensionality;
514 // TODO: Deal with SI-prefix
515 result.appendSingleUnit(*baseUnits[i], status);
516
517 if (U_FAILURE(status)) {
518 return result;
519 }
520 }
521 }
522
523 return result;
524 }
525
526 /**
527 * Determine the convertibility between `source` and `target`.
528 * For example:
529 * `meter` and `foot` are `CONVERTIBLE`.
530 * `meter-per-second` and `second-per-meter` are `RECIPROCAL`.
531 * `meter` and `pound` are `UNCONVERTIBLE`.
532 *
533 * NOTE:
534 * Only works with SINGLE and COMPOUND units. If one of the units is a
535 * MIXED unit, an error will occur. For more information, see UMeasureUnitComplexity.
536 */
537 Convertibility U_I18N_API extractConvertibility(const MeasureUnitImpl &source,
538 const MeasureUnitImpl &target,
539 const ConversionRates &conversionRates,
540 UErrorCode &status) {
541
542 if (source.complexity == UMeasureUnitComplexity::UMEASURE_UNIT_MIXED ||
543 target.complexity == UMeasureUnitComplexity::UMEASURE_UNIT_MIXED) {
544 status = U_ARGUMENT_TYPE_MISMATCH;
545 return UNCONVERTIBLE;
546 }
547
548 MeasureUnitImpl sourceBaseUnit = extractCompoundBaseUnit(source, conversionRates, status);
549 MeasureUnitImpl targetBaseUnit = extractCompoundBaseUnit(target, conversionRates, status);
550 if (U_FAILURE(status)) return UNCONVERTIBLE;
551
552 MaybeStackVector<UnitIndexAndDimension> convertible;
553 MaybeStackVector<UnitIndexAndDimension> reciprocal;
554
555 mergeUnitsAndDimensions(convertible, sourceBaseUnit, 1);
556 mergeUnitsAndDimensions(reciprocal, sourceBaseUnit, 1);
557
558 mergeUnitsAndDimensions(convertible, targetBaseUnit, -1);
559 mergeUnitsAndDimensions(reciprocal, targetBaseUnit, 1);
560
561 if (checkAllDimensionsAreZeros(convertible)) {
562 return CONVERTIBLE;
563 }
564
565 if (checkAllDimensionsAreZeros(reciprocal)) {
566 return RECIPROCAL;
567 }
568
569 return UNCONVERTIBLE;
570 }
571
572 UnitsConverter::UnitsConverter(const MeasureUnitImpl &source, const MeasureUnitImpl &target,
573 const ConversionRates &ratesInfo, UErrorCode &status)
574 : conversionRate_(source.copy(status), target.copy(status)) {
575 this->init(ratesInfo, status);
576 }
577
578 UnitsConverter::UnitsConverter(StringPiece sourceIdentifier, StringPiece targetIdentifier,
579 UErrorCode &status)
580 : conversionRate_(MeasureUnitImpl::forIdentifier(sourceIdentifier, status),
581 MeasureUnitImpl::forIdentifier(targetIdentifier, status)) {
582 if (U_FAILURE(status)) {
583 return;
584 }
585
586 ConversionRates ratesInfo(status);
587 this->init(ratesInfo, status);
588 }
589
590 void UnitsConverter::init(const ConversionRates &ratesInfo, UErrorCode &status) {
591 if (U_FAILURE(status)) {
592 return;
593 }
594
595 if (this->conversionRate_.source.complexity == UMeasureUnitComplexity::UMEASURE_UNIT_MIXED ||
596 this->conversionRate_.target.complexity == UMeasureUnitComplexity::UMEASURE_UNIT_MIXED) {
597 status = U_ARGUMENT_TYPE_MISMATCH;
598 return;
599 }
600
601 Convertibility unitsState = extractConvertibility(this->conversionRate_.source,
602 this->conversionRate_.target, ratesInfo, status);
603 if (U_FAILURE(status)) return;
604 if (unitsState == Convertibility::UNCONVERTIBLE) {
605 status = U_ARGUMENT_TYPE_MISMATCH;
606 return;
607 }
608
609 loadConversionRate(conversionRate_, conversionRate_.source, conversionRate_.target, unitsState,
610 ratesInfo, status);
611
612 }
613
614 int32_t UnitsConverter::compareTwoUnits(const MeasureUnitImpl &firstUnit,
615 const MeasureUnitImpl &secondUnit,
616 const ConversionRates &ratesInfo, UErrorCode &status) {
617 if (U_FAILURE(status)) {
618 return 0;
619 }
620
621 if (firstUnit.complexity == UMeasureUnitComplexity::UMEASURE_UNIT_MIXED ||
622 secondUnit.complexity == UMeasureUnitComplexity::UMEASURE_UNIT_MIXED) {
623 status = U_ARGUMENT_TYPE_MISMATCH;
624 return 0;
625 }
626
627 Convertibility unitsState = extractConvertibility(firstUnit, secondUnit, ratesInfo, status);
628 if (U_FAILURE(status)) {
629 return 0;
630 }
631
632 if (unitsState == Convertibility::UNCONVERTIBLE || unitsState == Convertibility::RECIPROCAL) {
633 status = U_ARGUMENT_TYPE_MISMATCH;
634 return 0;
635 }
636
637 CharString firstSpecial = getSpecialMappingName(firstUnit, ratesInfo, status);
638 CharString secondSpecial = getSpecialMappingName(secondUnit, ratesInfo, status);
639 if (!firstSpecial.isEmpty() || !secondSpecial.isEmpty()) {
640 if (firstSpecial.isEmpty()) {
641 // non-specials come first
642 return -1;
643 }
644 if (secondSpecial.isEmpty()) {
645 // non-specials come first
646 return 1;
647 }
648 // both are specials, compare lexicographically
649 StringPiece firstSpecialPiece = firstSpecial.toStringPiece();
650 StringPiece secondSpecialPiece = secondSpecial.toStringPiece();
651 return firstSpecialPiece.compare(secondSpecialPiece);
652 }
653
654 // Represents the conversion factor from the firstUnit to the base
655 // unit that specified in the conversion data which is considered as
656 // the root of the firstUnit and the secondUnit.
657 Factor firstUnitToBase = loadCompoundFactor(firstUnit, ratesInfo, status);
658 Factor secondUnitToBase = loadCompoundFactor(secondUnit, ratesInfo, status);
659
660 firstUnitToBase.substituteConstants();
661 secondUnitToBase.substituteConstants();
662
663 double firstUnitToBaseConversionRate = firstUnitToBase.factorNum / firstUnitToBase.factorDen;
664 double secondUnitToBaseConversionRate = secondUnitToBase.factorNum / secondUnitToBase.factorDen;
665
666 double diff = firstUnitToBaseConversionRate - secondUnitToBaseConversionRate;
667 if (diff > 0) {
668 return 1;
669 }
670
671 if (diff < 0) {
672 return -1;
673 }
674
675 return 0;
676 }
677
678 // TODO per CLDR-17421 and ICU-22683: consider getting the data below from CLDR
679 static double minMetersPerSecForBeaufort[] = {
680 // Minimum m/s (base) values for each Bft value, plus an extra artificial value;
681 // when converting from Bft to m/s, the middle of the range will be used
682 // (Values from table in Wikipedia, except for artificial value).
683 // Since this is 0 based, max Beaufort value is thus array dimension minus 2.
684 0.0, // 0 Bft
685 0.3, // 1
686 1.6, // 2
687 3.4, // 3
688 5.5, // 4
689 8.0, // 5
690 10.8, // 6
691 13.9, // 7
692 17.2, // 8
693 20.8, // 9
694 24.5, // 10
695 28.5, // 11
696 32.7, // 12
697 36.9, // 13
698 41.4, // 14
699 46.1, // 15
700 51.1, // 16
701 55.8, // 17
702 61.4, // artificial end of range 17 to give reasonable midpoint
703 };
704
705 static int maxBeaufort = UPRV_LENGTHOF(minMetersPerSecForBeaufort) - 2;
706
707 // Convert from what should be discrete scale values for a particular unit like beaufort
708 // to a corresponding value in the base unit (which can have any decimal value, like meters/sec).
709 // First we round the scale value to the nearest integer (in case it is specified with a fractional value),
710 // then we map that to a value in middle of the range of corresponding base values.
711 // This can handle different scales, specified by minBaseForScaleValues[].
712 double UnitsConverter::scaleToBase(double scaleValue, double minBaseForScaleValues[], int scaleMax) const {
713 if (scaleValue < 0) {
714 scaleValue = -scaleValue;
715 }
716 scaleValue += 0.5; // adjust up for later truncation
717 if (scaleValue > static_cast<double>(scaleMax)) {
718 scaleValue = static_cast<double>(scaleMax);
719 }
720 int scaleInt = static_cast<int>(scaleValue);
721 return (minBaseForScaleValues[scaleInt] + minBaseForScaleValues[scaleInt+1])/2.0;
722 }
723
724 // Binary search to find the range that includes key;
725 // if key (non-negative) is in the range rangeStarts[i] to just under rangeStarts[i+1],
726 // then we return i; if key is >= rangeStarts[max] then we return max.
727 // Note that max is the maximum scale value, not the number of elements in the array
728 // (which should be larger than max).
729 // The ranges for index 0 start at 0.0.
730 static int bsearchRanges(double rangeStarts[], int max, double key) {
731 if (key >= rangeStarts[max]) {
732 return max;
733 }
734 int beg = 0, mid = 0, end = max + 1;
735 while (beg < end) {
736 mid = (beg + end) / 2;
737 if (key < rangeStarts[mid]) {
738 end = mid;
739 } else if (key > rangeStarts[mid+1]) {
740 beg = mid+1;
741 } else {
742 break;
743 }
744 }
745 return mid;
746 }
747
748 // Convert from a value in the base unit (which can have any decimal value, like meters/sec) to a corresponding
749 // discrete value in a scale (like beaufort), where each scale value represents a range of base values.
750 // We binary-search the ranges to find the one that contains the specified base value, and return its index.
751 // This can handle different scales, specified by minBaseForScaleValues[].
752 double UnitsConverter::baseToScale(double baseValue, double minBaseForScaleValues[], int scaleMax) const {
753 if (baseValue < 0) {
754 baseValue = -baseValue;
755 }
756 int scaleIndex = bsearchRanges(minBaseForScaleValues, scaleMax, baseValue);
757 return static_cast<double>(scaleIndex);
758 }
759
760 double UnitsConverter::convert(double inputValue) const {
761 double result = inputValue;
762 if (!conversionRate_.specialSource.isEmpty() || !conversionRate_.specialTarget.isEmpty()) {
763 double base = inputValue;
764 // convert input (=source) to base
765 if (!conversionRate_.specialSource.isEmpty()) {
766 // We have a special mapping from source to base (not using factor, offset).
767 // Currently the only supported mapping is a scale-based mapping for beaufort.
768 base = (conversionRate_.specialSource == StringPiece("beaufort"))?
769 scaleToBase(inputValue, minMetersPerSecForBeaufort, maxBeaufort): inputValue;
770 } else {
771 // Standard mapping (using factor) from source to base.
772 base = inputValue * conversionRate_.factorNum / conversionRate_.factorDen;
773 }
774 // convert base to result (=target)
775 if (!conversionRate_.specialTarget.isEmpty()) {
776 // We have a special mapping from base to target (not using factor, offset).
777 // Currently the only supported mapping is a scale-based mapping for beaufort.
778 result = (conversionRate_.specialTarget == StringPiece("beaufort"))?
779 baseToScale(base, minMetersPerSecForBeaufort, maxBeaufort): base;
780 } else {
781 // Standard mapping (using factor) from base to target.
782 result = base * conversionRate_.factorDen / conversionRate_.factorNum;
783 }
784 return result;
785 }
786 result =
787 inputValue + conversionRate_.sourceOffset; // Reset the input to the target zero index.
788 // Convert the quantity to from the source scale to the target scale.
789 result *= conversionRate_.factorNum / conversionRate_.factorDen;
790
791 result -= conversionRate_.targetOffset; // Set the result to its index.
792
793 if (conversionRate_.reciprocal) {
794 if (result == 0) {
795 return uprv_getInfinity();
796 }
797 result = 1.0 / result;
798 }
799
800 return result;
801 }
802
803 double UnitsConverter::convertInverse(double inputValue) const {
804 double result = inputValue;
805 if (!conversionRate_.specialSource.isEmpty() || !conversionRate_.specialTarget.isEmpty()) {
806 double base = inputValue;
807 // convert input (=target) to base
808 if (!conversionRate_.specialTarget.isEmpty()) {
809 // We have a special mapping from target to base (not using factor).
810 // Currently the only supported mapping is a scale-based mapping for beaufort.
811 base = (conversionRate_.specialTarget == StringPiece("beaufort"))?
812 scaleToBase(inputValue, minMetersPerSecForBeaufort, maxBeaufort): inputValue;
813 } else {
814 // Standard mapping (using factor) from target to base.
815 base = inputValue * conversionRate_.factorNum / conversionRate_.factorDen;
816 }
817 // convert base to result (=source)
818 if (!conversionRate_.specialSource.isEmpty()) {
819 // We have a special mapping from base to source (not using factor).
820 // Currently the only supported mapping is a scale-based mapping for beaufort.
821 result = (conversionRate_.specialSource == StringPiece("beaufort"))?
822 baseToScale(base, minMetersPerSecForBeaufort, maxBeaufort): base;
823 } else {
824 // Standard mapping (using factor) from base to source.
825 result = base * conversionRate_.factorDen / conversionRate_.factorNum;
826 }
827 return result;
828 }
829 if (conversionRate_.reciprocal) {
830 if (result == 0) {
831 return uprv_getInfinity();
832 }
833 result = 1.0 / result;
834 }
835 result += conversionRate_.targetOffset;
836 result *= conversionRate_.factorDen / conversionRate_.factorNum;
837 result -= conversionRate_.sourceOffset;
838 return result;
839 }
840
841 ConversionInfo UnitsConverter::getConversionInfo() const {
842 ConversionInfo result;
843 result.conversionRate = conversionRate_.factorNum / conversionRate_.factorDen;
844 result.offset =
845 (conversionRate_.sourceOffset * (conversionRate_.factorNum / conversionRate_.factorDen)) -
846 conversionRate_.targetOffset;
847 result.reciprocal = conversionRate_.reciprocal;
848
849 return result;
850 }
851
852 } // namespace units
853 U_NAMESPACE_END
854
855 #endif /* #if !UCONFIG_NO_FORMATTING */