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