| 1 |
// © 2017 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 <cstdlib> |
| 9 |
|
| 10 |
#include "unicode/simpleformatter.h" |
| 11 |
#include "unicode/ures.h" |
| 12 |
#include "unicode/plurrule.h" |
| 13 |
#include "unicode/strenum.h" |
| 14 |
#include "ureslocs.h" |
| 15 |
#include "charstr.h" |
| 16 |
#include "uresimp.h" |
| 17 |
#include "measunit_impl.h" |
| 18 |
#include "number_longnames.h" |
| 19 |
#include "number_microprops.h" |
| 20 |
#include <algorithm> |
| 21 |
#include "cstring.h" |
| 22 |
#include "util.h" |
| 23 |
#include "sharedpluralrules.h" |
| 24 |
|
| 25 |
using namespace icu; |
| 26 |
using namespace icu::number; |
| 27 |
using namespace icu::number::impl; |
| 28 |
|
| 29 |
namespace { |
| 30 |
|
| 31 |
/** |
| 32 |
* Display Name (this format has no placeholder). |
| 33 |
* |
| 34 |
* Used as an index into the LongNameHandler::simpleFormats array. Units |
| 35 |
* resources cover the normal set of PluralRules keys, as well as `dnam` and |
| 36 |
* `per` forms. |
| 37 |
*/ |
| 38 |
constexpr int32_t DNAM_INDEX = StandardPlural::Form::COUNT; |
| 39 |
/** |
| 40 |
* "per" form (e.g. "{0} per day" is day's "per" form). |
| 41 |
* |
| 42 |
* Used as an index into the LongNameHandler::simpleFormats array. Units |
| 43 |
* resources cover the normal set of PluralRules keys, as well as `dnam` and |
| 44 |
* `per` forms. |
| 45 |
*/ |
| 46 |
constexpr int32_t PER_INDEX = StandardPlural::Form::COUNT + 1; |
| 47 |
/** |
| 48 |
* Gender of the word, in languages with grammatical gender. |
| 49 |
*/ |
| 50 |
constexpr int32_t GENDER_INDEX = StandardPlural::Form::COUNT + 2; |
| 51 |
/** |
| 52 |
* Denominator constant of the unit. |
| 53 |
*/ |
| 54 |
constexpr int32_t CONSTANT_DENOMINATOR_INDEX = StandardPlural::Form::COUNT + 3; |
| 55 |
// Number of keys in the array populated by PluralTableSink. |
| 56 |
constexpr int32_t ARRAY_LENGTH = StandardPlural::Form::COUNT + 4; |
| 57 |
|
| 58 |
// TODO(icu-units#28): load this list from resources, after creating a "&set" |
| 59 |
// function for use in ldml2icu rules. |
| 60 |
const int32_t GENDER_COUNT = 7; |
| 61 |
const char *gGenders[GENDER_COUNT] = {"animate", "common", "feminine", "inanimate", |
| 62 |
"masculine", "neuter", "personal"}; |
| 63 |
|
| 64 |
// Converts a UnicodeString to a const char*, either pointing to a string in |
| 65 |
// gGenders, or pointing to an empty string if an appropriate string was not |
| 66 |
// found. |
| 67 |
const char *getGenderString(UnicodeString uGender, UErrorCode status) { |
| 68 |
if (uGender.length() == 0) { |
| 69 |
return ""; |
| 70 |
} |
| 71 |
CharString gender; |
| 72 |
gender.appendInvariantChars(uGender, status); |
| 73 |
if (U_FAILURE(status)) { |
| 74 |
return ""; |
| 75 |
} |
| 76 |
int32_t first = 0; |
| 77 |
int32_t last = GENDER_COUNT; |
| 78 |
while (first < last) { |
| 79 |
int32_t mid = (first + last) / 2; |
| 80 |
int32_t cmp = uprv_strcmp(gender.data(), gGenders[mid]); |
| 81 |
if (cmp == 0) { |
| 82 |
return gGenders[mid]; |
| 83 |
} else if (cmp > 0) { |
| 84 |
first = mid + 1; |
| 85 |
} else if (cmp < 0) { |
| 86 |
last = mid; |
| 87 |
} |
| 88 |
} |
| 89 |
// We don't return an error in case our gGenders list is incomplete in |
| 90 |
// production. |
| 91 |
// |
| 92 |
// TODO(icu-units#28): a unit test checking all locales' genders are covered |
| 93 |
// by gGenders? Else load a complete list of genders found in |
| 94 |
// grammaticalFeatures in an initOnce. |
| 95 |
return ""; |
| 96 |
} |
| 97 |
|
| 98 |
// Returns the array index that corresponds to the given pluralKeyword. |
| 99 |
int32_t getIndex(const char* pluralKeyword, UErrorCode& status) { |
| 100 |
// pluralKeyword can also be "dnam", "per", or "gender" |
| 101 |
switch (*pluralKeyword) { |
| 102 |
case 'd': |
| 103 |
if (uprv_strcmp(pluralKeyword + 1, "nam") == 0) { |
| 104 |
return DNAM_INDEX; |
| 105 |
} |
| 106 |
break; |
| 107 |
case 'g': |
| 108 |
if (uprv_strcmp(pluralKeyword + 1, "ender") == 0) { |
| 109 |
return GENDER_INDEX; |
| 110 |
} |
| 111 |
break; |
| 112 |
case 'p': |
| 113 |
if (uprv_strcmp(pluralKeyword + 1, "er") == 0) { |
| 114 |
return PER_INDEX; |
| 115 |
} |
| 116 |
break; |
| 117 |
default: |
| 118 |
break; |
| 119 |
} |
| 120 |
StandardPlural::Form plural = StandardPlural::fromString(pluralKeyword, status); |
| 121 |
return plural; |
| 122 |
} |
| 123 |
|
| 124 |
// Selects a string out of the `strings` array which corresponds to the |
| 125 |
// specified plural form, with fallback to the OTHER form. |
| 126 |
// |
| 127 |
// The `strings` array must have ARRAY_LENGTH items: one corresponding to each |
| 128 |
// of the plural forms, plus a display name ("dnam") and a "per" form. |
| 129 |
UnicodeString getWithPlural( |
| 130 |
const UnicodeString* strings, |
| 131 |
StandardPlural::Form plural, |
| 132 |
UErrorCode& status) { |
| 133 |
UnicodeString result = strings[plural]; |
| 134 |
if (result.isBogus()) { |
| 135 |
result = strings[StandardPlural::Form::OTHER]; |
| 136 |
} |
| 137 |
if (result.isBogus()) { |
| 138 |
// There should always be data in the "other" plural variant. |
| 139 |
status = U_INTERNAL_PROGRAM_ERROR; |
| 140 |
} |
| 141 |
return result; |
| 142 |
} |
| 143 |
|
| 144 |
enum PlaceholderPosition { PH_EMPTY, PH_NONE, PH_BEGINNING, PH_MIDDLE, PH_END }; |
| 145 |
|
| 146 |
/** |
| 147 |
* Returns three outputs extracted from pattern. |
| 148 |
* |
| 149 |
* @param coreUnit is extracted as per Extract(...) in the spec: |
| 150 |
* https://unicode.org/reports/tr35/tr35-general.html#compound-units |
| 151 |
* @param PlaceholderPosition indicates where in the string the placeholder was |
| 152 |
* found. |
| 153 |
* @param joinerChar Iff the placeholder was at the beginning or end, joinerChar |
| 154 |
* contains the space character (if any) that separated the placeholder from |
| 155 |
* the rest of the pattern. Otherwise, joinerChar is set to NUL. Only one |
| 156 |
* space character is considered. |
| 157 |
*/ |
| 158 |
void extractCorePattern(const UnicodeString &pattern, |
| 159 |
UnicodeString &coreUnit, |
| 160 |
PlaceholderPosition &placeholderPosition, |
| 161 |
char16_t &joinerChar) { |
| 162 |
joinerChar = 0; |
| 163 |
int32_t len = pattern.length(); |
| 164 |
if (pattern.startsWith(u"{0}", 3)) { |
| 165 |
placeholderPosition = PH_BEGINNING; |
| 166 |
if (u_isJavaSpaceChar(pattern[3])) { |
| 167 |
joinerChar = pattern[3]; |
| 168 |
coreUnit.setTo(pattern, 4, len - 4); |
| 169 |
} else { |
| 170 |
coreUnit.setTo(pattern, 3, len - 3); |
| 171 |
} |
| 172 |
} else if (pattern.endsWith(u"{0}", 3)) { |
| 173 |
placeholderPosition = PH_END; |
| 174 |
if (u_isJavaSpaceChar(pattern[len - 4])) { |
| 175 |
coreUnit.setTo(pattern, 0, len - 4); |
| 176 |
joinerChar = pattern[len - 4]; |
| 177 |
} else { |
| 178 |
coreUnit.setTo(pattern, 0, len - 3); |
| 179 |
} |
| 180 |
} else if (pattern.indexOf(u"{0}", 3, 1, len - 2) == -1) { |
| 181 |
placeholderPosition = PH_NONE; |
| 182 |
coreUnit = pattern; |
| 183 |
} else { |
| 184 |
placeholderPosition = PH_MIDDLE; |
| 185 |
coreUnit = pattern; |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
////////////////////////// |
| 190 |
/// BEGIN DATA LOADING /// |
| 191 |
////////////////////////// |
| 192 |
|
| 193 |
// Gets the gender of a built-in unit: unit must be a built-in. Returns an empty |
| 194 |
// string both in case of unknown gender and in case of unknown unit. |
| 195 |
UnicodeString |
| 196 |
getGenderForBuiltin(const Locale &locale, const MeasureUnit &builtinUnit, UErrorCode &status) { |
| 197 |
LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_UNIT, locale.getName(), &status)); |
| 198 |
if (U_FAILURE(status)) { return {}; } |
| 199 |
|
| 200 |
// Map duration-year-person, duration-week-person, etc. to duration-year, duration-week, ... |
| 201 |
// TODO(ICU-20400): Get duration-*-person data properly with aliases. |
| 202 |
StringPiece subtypeForResource; |
| 203 |
int32_t subtypeLen = static_cast<int32_t>(uprv_strlen(builtinUnit.getSubtype())); |
| 204 |
if (subtypeLen > 7 && uprv_strcmp(builtinUnit.getSubtype() + subtypeLen - 7, "-person") == 0) { |
| 205 |
subtypeForResource = {builtinUnit.getSubtype(), subtypeLen - 7}; |
| 206 |
} else { |
| 207 |
subtypeForResource = builtinUnit.getSubtype(); |
| 208 |
} |
| 209 |
|
| 210 |
CharString key; |
| 211 |
key.append("units/", status); |
| 212 |
key.append(builtinUnit.getType(), status); |
| 213 |
key.append("/", status); |
| 214 |
key.append(subtypeForResource, status); |
| 215 |
key.append("/gender", status); |
| 216 |
|
| 217 |
UErrorCode localStatus = status; |
| 218 |
int32_t resultLen = 0; |
| 219 |
const char16_t *result = |
| 220 |
ures_getStringByKeyWithFallback(unitsBundle.getAlias(), key.data(), &resultLen, &localStatus); |
| 221 |
if (U_SUCCESS(localStatus)) { |
| 222 |
status = localStatus; |
| 223 |
return UnicodeString(true, result, resultLen); |
| 224 |
} else { |
| 225 |
// TODO(icu-units#28): "$unitRes/gender" does not exist. Do we want to |
| 226 |
// check whether the parent "$unitRes" exists? Then we could return |
| 227 |
// U_MISSING_RESOURCE_ERROR for incorrect usage (e.g. builtinUnit not |
| 228 |
// being a builtin). |
| 229 |
return {}; |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
// Loads data from a resource tree with paths matching |
| 234 |
// $key/$pluralForm/$gender/$case, with lateral inheritance for missing cases |
| 235 |
// and genders. |
| 236 |
// |
| 237 |
// An InflectedPluralSink is configured to load data for a specific gender and |
| 238 |
// case. It loads all plural forms, because selection between plural forms is |
| 239 |
// dependent upon the value being formatted. |
| 240 |
// |
| 241 |
// See data/unit/de.txt and data/unit/fr.txt for examples - take a look at |
| 242 |
// units/compound/power2: German has case, French has differences for gender, |
| 243 |
// but no case. |
| 244 |
// |
| 245 |
// TODO(icu-units#138): Conceptually similar to PluralTableSink, however the |
| 246 |
// tree structures are different. After homogenizing the structures, we may be |
| 247 |
// able to unify the two classes. |
| 248 |
// |
| 249 |
// TODO: Spec violation: expects presence of "count" - does not fallback to an |
| 250 |
// absent "count"! If this fallback were added, getCompoundValue could be |
| 251 |
// superseded? |
| 252 |
class InflectedPluralSink : public ResourceSink { |
| 253 |
public: |
| 254 |
// Accepts `char*` rather than StringPiece because |
| 255 |
// ResourceTable::findValue(...) requires a null-terminated `char*`. |
| 256 |
// |
| 257 |
// NOTE: outArray MUST have a length of at least ARRAY_LENGTH. No bounds |
| 258 |
// checking is performed. |
| 259 |
explicit InflectedPluralSink(const char *gender, const char *caseVariant, UnicodeString *outArray) |
| 260 |
: gender(gender), caseVariant(caseVariant), outArray(outArray) { |
| 261 |
// Initialize the array to bogus strings. |
| 262 |
for (int32_t i = 0; i < ARRAY_LENGTH; i++) { |
| 263 |
outArray[i].setToBogus(); |
| 264 |
} |
| 265 |
} |
| 266 |
|
| 267 |
// See ResourceSink::put(). |
| 268 |
void put(const char *key, ResourceValue &value, UBool /*noFallback*/, UErrorCode &status) override { |
| 269 |
int32_t pluralIndex = getIndex(key, status); |
| 270 |
if (U_FAILURE(status)) { return; } |
| 271 |
if (!outArray[pluralIndex].isBogus()) { |
| 272 |
// We already have a pattern |
| 273 |
return; |
| 274 |
} |
| 275 |
ResourceTable genderTable = value.getTable(status); |
| 276 |
ResourceTable caseTable; // This instance has to outlive `value` |
| 277 |
if (loadForPluralForm(genderTable, caseTable, value, status)) { |
| 278 |
outArray[pluralIndex] = value.getUnicodeString(status); |
| 279 |
} |
| 280 |
} |
| 281 |
|
| 282 |
private: |
| 283 |
// Tries to load data for the configured gender from `genderTable`. Returns |
| 284 |
// true if found, returning the data in `value`. The returned data will be |
| 285 |
// for the configured gender if found, falling back to "neuter" and |
| 286 |
// no-gender if not. The caseTable parameter holds the intermediate |
| 287 |
// ResourceTable for the sake of lifetime management. |
| 288 |
bool loadForPluralForm(const ResourceTable &genderTable, |
| 289 |
ResourceTable &caseTable, |
| 290 |
ResourceValue &value, |
| 291 |
UErrorCode &status) { |
| 292 |
if (uprv_strcmp(gender, "") != 0) { |
| 293 |
if (loadForGender(genderTable, gender, caseTable, value, status)) { |
| 294 |
return true; |
| 295 |
} |
| 296 |
if (uprv_strcmp(gender, "neuter") != 0 && |
| 297 |
loadForGender(genderTable, "neuter", caseTable, value, status)) { |
| 298 |
return true; |
| 299 |
} |
| 300 |
} |
| 301 |
if (loadForGender(genderTable, "_", caseTable, value, status)) { |
| 302 |
return true; |
| 303 |
} |
| 304 |
return false; |
| 305 |
} |
| 306 |
|
| 307 |
// Tries to load data for the given gender from `genderTable`. Returns true |
| 308 |
// if found, returning the data in `value`. The returned data will be for |
| 309 |
// the configured case if found, falling back to "nominative" and no-case if |
| 310 |
// not. |
| 311 |
bool loadForGender(const ResourceTable &genderTable, |
| 312 |
const char *genderVal, |
| 313 |
ResourceTable &caseTable, |
| 314 |
ResourceValue &value, |
| 315 |
UErrorCode &status) { |
| 316 |
if (!genderTable.findValue(genderVal, value)) { |
| 317 |
return false; |
| 318 |
} |
| 319 |
caseTable = value.getTable(status); |
| 320 |
if (uprv_strcmp(caseVariant, "") != 0) { |
| 321 |
if (loadForCase(caseTable, caseVariant, value)) { |
| 322 |
return true; |
| 323 |
} |
| 324 |
if (uprv_strcmp(caseVariant, "nominative") != 0 && |
| 325 |
loadForCase(caseTable, "nominative", value)) { |
| 326 |
return true; |
| 327 |
} |
| 328 |
} |
| 329 |
if (loadForCase(caseTable, "_", value)) { |
| 330 |
return true; |
| 331 |
} |
| 332 |
return false; |
| 333 |
} |
| 334 |
|
| 335 |
// Tries to load data for the given case from `caseTable`. Returns true if |
| 336 |
// found, returning the data in `value`. |
| 337 |
bool loadForCase(const ResourceTable &caseTable, const char *caseValue, ResourceValue &value) { |
| 338 |
if (!caseTable.findValue(caseValue, value)) { |
| 339 |
return false; |
| 340 |
} |
| 341 |
return true; |
| 342 |
} |
| 343 |
|
| 344 |
const char *gender; |
| 345 |
const char *caseVariant; |
| 346 |
UnicodeString *outArray; |
| 347 |
}; |
| 348 |
|
| 349 |
// Fetches localised formatting patterns for the given subKey. See documentation |
| 350 |
// for InflectedPluralSink for details. |
| 351 |
// |
| 352 |
// Data is loaded for the appropriate unit width, with missing data filled in |
| 353 |
// from unitsShort. |
| 354 |
void getInflectedMeasureData(StringPiece subKey, |
| 355 |
const Locale &locale, |
| 356 |
const UNumberUnitWidth &width, |
| 357 |
const char *gender, |
| 358 |
const char *caseVariant, |
| 359 |
UnicodeString *outArray, |
| 360 |
UErrorCode &status) { |
| 361 |
InflectedPluralSink sink(gender, caseVariant, outArray); |
| 362 |
LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_UNIT, locale.getName(), &status)); |
| 363 |
if (U_FAILURE(status)) { return; } |
| 364 |
|
| 365 |
CharString key; |
| 366 |
key.append("units", status); |
| 367 |
if (width == UNUM_UNIT_WIDTH_NARROW) { |
| 368 |
key.append("Narrow", status); |
| 369 |
} else if (width == UNUM_UNIT_WIDTH_SHORT) { |
| 370 |
key.append("Short", status); |
| 371 |
} |
| 372 |
key.append("/", status); |
| 373 |
key.append(subKey, status); |
| 374 |
|
| 375 |
UErrorCode localStatus = status; |
| 376 |
ures_getAllChildrenWithFallback(unitsBundle.getAlias(), key.data(), sink, localStatus); |
| 377 |
if (width == UNUM_UNIT_WIDTH_SHORT) { |
| 378 |
status = localStatus; |
| 379 |
return; |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
class PluralTableSink : public ResourceSink { |
| 384 |
public: |
| 385 |
// NOTE: outArray MUST have a length of at least ARRAY_LENGTH. No bounds |
| 386 |
// checking is performed. |
| 387 |
explicit PluralTableSink(UnicodeString *outArray) : outArray(outArray) { |
| 388 |
// Initialize the array to bogus strings. |
| 389 |
for (int32_t i = 0; i < ARRAY_LENGTH; i++) { |
| 390 |
outArray[i].setToBogus(); |
| 391 |
} |
| 392 |
} |
| 393 |
|
| 394 |
void put(const char *key, ResourceValue &value, UBool /*noFallback*/, UErrorCode &status) override { |
| 395 |
if (uprv_strcmp(key, "case") == 0) { |
| 396 |
return; |
| 397 |
} |
| 398 |
int32_t index = getIndex(key, status); |
| 399 |
if (U_FAILURE(status)) { return; } |
| 400 |
if (!outArray[index].isBogus()) { |
| 401 |
return; |
| 402 |
} |
| 403 |
outArray[index] = value.getUnicodeString(status); |
| 404 |
if (U_FAILURE(status)) { return; } |
| 405 |
} |
| 406 |
|
| 407 |
private: |
| 408 |
UnicodeString *outArray; |
| 409 |
}; |
| 410 |
|
| 411 |
/** |
| 412 |
* Populates outArray with `locale`-specific values for `unit` through use of |
| 413 |
* PluralTableSink. Only the set of basic units are supported! |
| 414 |
* |
| 415 |
* Reading from resources *unitsNarrow* and *unitsShort* (for width |
| 416 |
* UNUM_UNIT_WIDTH_NARROW), or just *unitsShort* (for width |
| 417 |
* UNUM_UNIT_WIDTH_SHORT). For other widths, it reads just "units". |
| 418 |
* |
| 419 |
* @param unit must be a built-in unit, i.e. must have a type and subtype, |
| 420 |
* listed in gTypes and gSubTypes in measunit.cpp. |
| 421 |
* @param unitDisplayCase the empty string and "nominative" are treated the |
| 422 |
* same. For other cases, strings for the requested case are used if found. |
| 423 |
* (For any missing case-specific data, we fall back to nominative.) |
| 424 |
* @param outArray must be of fixed length ARRAY_LENGTH. |
| 425 |
*/ |
| 426 |
void getMeasureData(const Locale &locale, |
| 427 |
const MeasureUnit &unit, |
| 428 |
const UNumberUnitWidth &width, |
| 429 |
const char *unitDisplayCase, |
| 430 |
UnicodeString *outArray, |
| 431 |
UErrorCode &status) { |
| 432 |
PluralTableSink sink(outArray); |
| 433 |
LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_UNIT, locale.getName(), &status)); |
| 434 |
if (U_FAILURE(status)) { return; } |
| 435 |
|
| 436 |
CharString subKey; |
| 437 |
subKey.append("/", status); |
| 438 |
subKey.append(unit.getType(), status); |
| 439 |
subKey.append("/", status); |
| 440 |
|
| 441 |
// Check if unitSubType is an alias or not. |
| 442 |
LocalUResourceBundlePointer aliasBundle(ures_open(U_ICUDATA_ALIAS, "metadata", &status)); |
| 443 |
|
| 444 |
UErrorCode aliasStatus = status; |
| 445 |
StackUResourceBundle aliasFillIn; |
| 446 |
CharString aliasKey; |
| 447 |
aliasKey.append("alias/unit/", aliasStatus); |
| 448 |
aliasKey.append(unit.getSubtype(), aliasStatus); |
| 449 |
aliasKey.append("/replacement", aliasStatus); |
| 450 |
ures_getByKeyWithFallback(aliasBundle.getAlias(), aliasKey.data(), aliasFillIn.getAlias(), |
| 451 |
&aliasStatus); |
| 452 |
CharString unitSubType; |
| 453 |
if (!U_FAILURE(aliasStatus)) { |
| 454 |
// This means the subType is an alias. Then, replace unitSubType with the replacement. |
| 455 |
auto replacement = ures_getUnicodeString(aliasFillIn.getAlias(), &status); |
| 456 |
unitSubType.appendInvariantChars(replacement, status); |
| 457 |
} else { |
| 458 |
unitSubType.append(unit.getSubtype(), status); |
| 459 |
} |
| 460 |
|
| 461 |
// Map duration-year-person, duration-week-person, etc. to duration-year, duration-week, ... |
| 462 |
// TODO(ICU-20400): Get duration-*-person data properly with aliases. |
| 463 |
int32_t subtypeLen = static_cast<int32_t>(uprv_strlen(unitSubType.data())); |
| 464 |
if (subtypeLen > 7 && uprv_strcmp(unitSubType.data() + subtypeLen - 7, "-person") == 0) { |
| 465 |
subKey.append({unitSubType.data(), subtypeLen - 7}, status); |
| 466 |
} else { |
| 467 |
subKey.append({unitSubType.data(), subtypeLen}, status); |
| 468 |
} |
| 469 |
|
| 470 |
if (width != UNUM_UNIT_WIDTH_FULL_NAME) { |
| 471 |
UErrorCode localStatus = status; |
| 472 |
CharString genderKey; |
| 473 |
genderKey.append("units", localStatus); |
| 474 |
genderKey.append(subKey, localStatus); |
| 475 |
genderKey.append("/gender", localStatus); |
| 476 |
StackUResourceBundle fillIn; |
| 477 |
ures_getByKeyWithFallback(unitsBundle.getAlias(), genderKey.data(), fillIn.getAlias(), |
| 478 |
&localStatus); |
| 479 |
outArray[GENDER_INDEX] = ures_getUnicodeString(fillIn.getAlias(), &localStatus); |
| 480 |
} |
| 481 |
|
| 482 |
CharString key; |
| 483 |
key.append("units", status); |
| 484 |
if (width == UNUM_UNIT_WIDTH_NARROW) { |
| 485 |
key.append("Narrow", status); |
| 486 |
} else if (width == UNUM_UNIT_WIDTH_SHORT) { |
| 487 |
key.append("Short", status); |
| 488 |
} |
| 489 |
key.append(subKey, status); |
| 490 |
|
| 491 |
// Grab desired case first, if available. Then grab no-case data to fill in |
| 492 |
// the gaps. |
| 493 |
if (width == UNUM_UNIT_WIDTH_FULL_NAME && unitDisplayCase[0] != 0) { |
| 494 |
CharString caseKey; |
| 495 |
caseKey.append(key, status); |
| 496 |
caseKey.append("/case/", status); |
| 497 |
caseKey.append(unitDisplayCase, status); |
| 498 |
|
| 499 |
UErrorCode localStatus = U_ZERO_ERROR; |
| 500 |
// TODO(icu-units#138): our fallback logic is not spec-compliant: |
| 501 |
// lateral fallback should happen before locale fallback. Switch to |
| 502 |
// getInflectedMeasureData after homogenizing data format? Find a unit |
| 503 |
// test case that demonstrates the incorrect fallback logic (via |
| 504 |
// regional variant of an inflected language?) |
| 505 |
ures_getAllChildrenWithFallback(unitsBundle.getAlias(), caseKey.data(), sink, localStatus); |
| 506 |
} |
| 507 |
|
| 508 |
// TODO(icu-units#138): our fallback logic is not spec-compliant: we |
| 509 |
// check the given case, then go straight to the no-case data. The spec |
| 510 |
// states we should first look for case="nominative". As part of #138, |
| 511 |
// either get the spec changed, or add unit tests that warn us if |
| 512 |
// case="nominative" data differs from no-case data? |
| 513 |
UErrorCode localStatus = U_ZERO_ERROR; |
| 514 |
ures_getAllChildrenWithFallback(unitsBundle.getAlias(), key.data(), sink, localStatus); |
| 515 |
if (width == UNUM_UNIT_WIDTH_SHORT) { |
| 516 |
if (U_FAILURE(localStatus)) { |
| 517 |
status = localStatus; |
| 518 |
} |
| 519 |
return; |
| 520 |
} |
| 521 |
} |
| 522 |
|
| 523 |
// NOTE: outArray MUST have a length of at least ARRAY_LENGTH. |
| 524 |
void getCurrencyLongNameData(const Locale &locale, const CurrencyUnit ¤cy, UnicodeString *outArray, |
| 525 |
UErrorCode &status) { |
| 526 |
// In ICU4J, this method gets a CurrencyData from CurrencyData.provider. |
| 527 |
// TODO(ICU4J): Implement this without going through CurrencyData, like in ICU4C? |
| 528 |
PluralTableSink sink(outArray); |
| 529 |
// Here all outArray entries are bogus. |
| 530 |
LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_CURR, locale.getName(), &status)); |
| 531 |
if (U_FAILURE(status)) { return; } |
| 532 |
ures_getAllChildrenWithFallback(unitsBundle.getAlias(), "CurrencyUnitPatterns", sink, status); |
| 533 |
if (U_FAILURE(status)) { return; } |
| 534 |
// Here the outArray[] entries are filled in with any CurrencyUnitPatterns data for locale, |
| 535 |
// or if there is no CurrencyUnitPatterns data for locale since the patterns all inherited |
| 536 |
// from the "other" pattern in root (which is true for many locales in CLDR 46), then only |
| 537 |
// the "other" entry has a currency pattern. So now what we do is: For all valid plural keywords |
| 538 |
// for the locale, if the corresponding outArray[] entry is bogus, fill it in from the "other" |
| 539 |
// entry. In the longer run, clients of this should instead consider using CurrencyPluralInfo |
| 540 |
// (see i18n/unicode/currpinf.h). |
| 541 |
UErrorCode localStatus = U_ZERO_ERROR; |
| 542 |
const SharedPluralRules *pr = PluralRules::createSharedInstance( |
| 543 |
locale, UPLURAL_TYPE_CARDINAL, localStatus); |
| 544 |
if (U_SUCCESS(localStatus)) { |
| 545 |
LocalPointer<StringEnumeration> keywords((*pr)->getKeywords(localStatus), localStatus); |
| 546 |
if (U_SUCCESS(localStatus)) { |
| 547 |
const char* keyword; |
| 548 |
while (((keyword = keywords->next(nullptr, localStatus)) != nullptr) && U_SUCCESS(localStatus)) { |
| 549 |
int32_t index = StandardPlural::indexOrOtherIndexFromString(keyword); |
| 550 |
if (index != StandardPlural::Form::OTHER && outArray[index].isBogus()) { |
| 551 |
outArray[index].setTo(outArray[StandardPlural::Form::OTHER]); |
| 552 |
} |
| 553 |
} |
| 554 |
} |
| 555 |
pr->removeRef(); |
| 556 |
} |
| 557 |
|
| 558 |
for (int32_t i = 0; i < StandardPlural::Form::COUNT; i++) { |
| 559 |
UnicodeString &pattern = outArray[i]; |
| 560 |
if (pattern.isBogus()) { |
| 561 |
continue; |
| 562 |
} |
| 563 |
int32_t longNameLen = 0; |
| 564 |
const char16_t *longName = ucurr_getPluralName( |
| 565 |
currency.getISOCurrency(), |
| 566 |
locale.getName(), |
| 567 |
nullptr /* isChoiceFormat */, |
| 568 |
StandardPlural::getKeyword(static_cast<StandardPlural::Form>(i)), |
| 569 |
&longNameLen, |
| 570 |
&status); |
| 571 |
// Example pattern from data: "{0} {1}" |
| 572 |
// Example output after find-and-replace: "{0} US dollars" |
| 573 |
pattern.findAndReplace(UnicodeString(u"{1}"), UnicodeString(longName, longNameLen)); |
| 574 |
} |
| 575 |
} |
| 576 |
|
| 577 |
UnicodeString getCompoundValue(StringPiece compoundKey, |
| 578 |
const Locale &locale, |
| 579 |
const UNumberUnitWidth &width, |
| 580 |
UErrorCode &status) { |
| 581 |
LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_UNIT, locale.getName(), &status)); |
| 582 |
if (U_FAILURE(status)) { return {}; } |
| 583 |
CharString key; |
| 584 |
key.append("units", status); |
| 585 |
if (width == UNUM_UNIT_WIDTH_NARROW) { |
| 586 |
key.append("Narrow", status); |
| 587 |
} else if (width == UNUM_UNIT_WIDTH_SHORT) { |
| 588 |
key.append("Short", status); |
| 589 |
} |
| 590 |
key.append("/compound/", status); |
| 591 |
key.append(compoundKey, status); |
| 592 |
|
| 593 |
UErrorCode localStatus = status; |
| 594 |
int32_t len = 0; |
| 595 |
const char16_t *ptr = |
| 596 |
ures_getStringByKeyWithFallback(unitsBundle.getAlias(), key.data(), &len, &localStatus); |
| 597 |
if (U_FAILURE(localStatus) && width != UNUM_UNIT_WIDTH_SHORT) { |
| 598 |
// Fall back to short, which contains more compound data |
| 599 |
key.clear(); |
| 600 |
key.append("unitsShort/compound/", status); |
| 601 |
key.append(compoundKey, status); |
| 602 |
ptr = ures_getStringByKeyWithFallback(unitsBundle.getAlias(), key.data(), &len, &status); |
| 603 |
} else { |
| 604 |
status = localStatus; |
| 605 |
} |
| 606 |
if (U_FAILURE(status)) { |
| 607 |
return {}; |
| 608 |
} |
| 609 |
return UnicodeString(ptr, len); |
| 610 |
} |
| 611 |
|
| 612 |
/** |
| 613 |
* Loads and applies deriveComponent rules from CLDR's grammaticalFeatures.xml. |
| 614 |
* |
| 615 |
* Consider a deriveComponent rule that looks like this: |
| 616 |
* |
| 617 |
* <deriveComponent feature="case" structure="per" value0="compound" value1="nominative"/> |
| 618 |
* |
| 619 |
* Instantiating an instance as follows: |
| 620 |
* |
| 621 |
* DerivedComponents d(loc, "case", "per"); |
| 622 |
* |
| 623 |
* Applying the rule in the XML element above, `d.value0("foo")` will be "foo", |
| 624 |
* and `d.value1("foo")` will be "nominative". |
| 625 |
* |
| 626 |
* The values returned by value0(...) and value1(...) are valid only while the |
| 627 |
* instance exists. In case of any kind of failure, value0(...) and value1(...) |
| 628 |
* will return "". |
| 629 |
*/ |
| 630 |
class DerivedComponents { |
| 631 |
public: |
| 632 |
/** |
| 633 |
* Constructor. |
| 634 |
* |
| 635 |
* The feature and structure parameters must be null-terminated. The string |
| 636 |
* referenced by compoundValue must exist for longer than the |
| 637 |
* DerivedComponents instance. |
| 638 |
*/ |
| 639 |
DerivedComponents(const Locale &locale, const char *feature, const char *structure) { |
| 640 |
StackUResourceBundle derivationsBundle, stackBundle; |
| 641 |
ures_openDirectFillIn(derivationsBundle.getAlias(), nullptr, "grammaticalFeatures", &status); |
| 642 |
ures_getByKey(derivationsBundle.getAlias(), "grammaticalData", derivationsBundle.getAlias(), |
| 643 |
&status); |
| 644 |
ures_getByKey(derivationsBundle.getAlias(), "derivations", derivationsBundle.getAlias(), |
| 645 |
&status); |
| 646 |
if (U_FAILURE(status)) { |
| 647 |
return; |
| 648 |
} |
| 649 |
UErrorCode localStatus = U_ZERO_ERROR; |
| 650 |
// TODO(icu-units#28): use standard normal locale resolution algorithms |
| 651 |
// rather than just grabbing language: |
| 652 |
ures_getByKey(derivationsBundle.getAlias(), locale.getLanguage(), stackBundle.getAlias(), |
| 653 |
&localStatus); |
| 654 |
// TODO(icu-units#28): |
| 655 |
// - code currently assumes if the locale exists, the rules are there - |
| 656 |
// instead of falling back to root when the requested rule is missing. |
| 657 |
// - investigate ures.h functions, see if one that uses res_findResource() |
| 658 |
// might be better (or use res_findResource directly), or maybe help |
| 659 |
// improve ures documentation to guide function selection? |
| 660 |
if (localStatus == U_MISSING_RESOURCE_ERROR) { |
| 661 |
ures_getByKey(derivationsBundle.getAlias(), "root", stackBundle.getAlias(), &status); |
| 662 |
} else { |
| 663 |
status = localStatus; |
| 664 |
} |
| 665 |
ures_getByKey(stackBundle.getAlias(), "component", stackBundle.getAlias(), &status); |
| 666 |
ures_getByKey(stackBundle.getAlias(), feature, stackBundle.getAlias(), &status); |
| 667 |
ures_getByKey(stackBundle.getAlias(), structure, stackBundle.getAlias(), &status); |
| 668 |
UnicodeString val0 = ures_getUnicodeStringByIndex(stackBundle.getAlias(), 0, &status); |
| 669 |
UnicodeString val1 = ures_getUnicodeStringByIndex(stackBundle.getAlias(), 1, &status); |
| 670 |
if (U_SUCCESS(status)) { |
| 671 |
if (val0.compare(UnicodeString(u"compound")) == 0) { |
| 672 |
compound0_ = true; |
| 673 |
} else { |
| 674 |
compound0_ = false; |
| 675 |
value0_.appendInvariantChars(val0, status); |
| 676 |
} |
| 677 |
if (val1.compare(UnicodeString(u"compound")) == 0) { |
| 678 |
compound1_ = true; |
| 679 |
} else { |
| 680 |
compound1_ = false; |
| 681 |
value1_.appendInvariantChars(val1, status); |
| 682 |
} |
| 683 |
} |
| 684 |
} |
| 685 |
|
| 686 |
// Returns a StringPiece that is only valid as long as the instance exists. |
| 687 |
StringPiece value0(const StringPiece compoundValue) const { |
| 688 |
return compound0_ ? compoundValue : value0_.toStringPiece(); |
| 689 |
} |
| 690 |
|
| 691 |
// Returns a StringPiece that is only valid as long as the instance exists. |
| 692 |
StringPiece value1(const StringPiece compoundValue) const { |
| 693 |
return compound1_ ? compoundValue : value1_.toStringPiece(); |
| 694 |
} |
| 695 |
|
| 696 |
// Returns a char* that is only valid as long as the instance exists. |
| 697 |
const char *value0(const char *compoundValue) const { |
| 698 |
return compound0_ ? compoundValue : value0_.data(); |
| 699 |
} |
| 700 |
|
| 701 |
// Returns a char* that is only valid as long as the instance exists. |
| 702 |
const char *value1(const char *compoundValue) const { |
| 703 |
return compound1_ ? compoundValue : value1_.data(); |
| 704 |
} |
| 705 |
|
| 706 |
private: |
| 707 |
UErrorCode status = U_ZERO_ERROR; |
| 708 |
|
| 709 |
// Holds strings referred to by value0 and value1; |
| 710 |
bool compound0_ = false, compound1_ = false; |
| 711 |
CharString value0_, value1_; |
| 712 |
}; |
| 713 |
|
| 714 |
// TODO(icu-units#28): test somehow? Associate with an ICU ticket for adding |
| 715 |
// testsuite support for testing with synthetic data? |
| 716 |
/** |
| 717 |
* Loads and returns the value in rules that look like these: |
| 718 |
* |
| 719 |
* <deriveCompound feature="gender" structure="per" value="0"/> |
| 720 |
* <deriveCompound feature="gender" structure="times" value="1"/> |
| 721 |
* |
| 722 |
* Currently a fake example, but spec compliant: |
| 723 |
* <deriveCompound feature="gender" structure="power" value="feminine"/> |
| 724 |
* |
| 725 |
* NOTE: If U_FAILURE(status), returns an empty string. |
| 726 |
*/ |
| 727 |
UnicodeString |
| 728 |
getDeriveCompoundRule(Locale locale, const char *feature, const char *structure, UErrorCode &status) { |
| 729 |
StackUResourceBundle derivationsBundle, stackBundle; |
| 730 |
ures_openDirectFillIn(derivationsBundle.getAlias(), nullptr, "grammaticalFeatures", &status); |
| 731 |
ures_getByKey(derivationsBundle.getAlias(), "grammaticalData", derivationsBundle.getAlias(), |
| 732 |
&status); |
| 733 |
ures_getByKey(derivationsBundle.getAlias(), "derivations", derivationsBundle.getAlias(), &status); |
| 734 |
// TODO: use standard normal locale resolution algorithms rather than just grabbing language: |
| 735 |
ures_getByKey(derivationsBundle.getAlias(), locale.getLanguage(), stackBundle.getAlias(), &status); |
| 736 |
// TODO: |
| 737 |
// - code currently assumes if the locale exists, the rules are there - |
| 738 |
// instead of falling back to root when the requested rule is missing. |
| 739 |
// - investigate ures.h functions, see if one that uses res_findResource() |
| 740 |
// might be better (or use res_findResource directly), or maybe help |
| 741 |
// improve ures documentation to guide function selection? |
| 742 |
if (status == U_MISSING_RESOURCE_ERROR) { |
| 743 |
status = U_ZERO_ERROR; |
| 744 |
ures_getByKey(derivationsBundle.getAlias(), "root", stackBundle.getAlias(), &status); |
| 745 |
} |
| 746 |
ures_getByKey(stackBundle.getAlias(), "compound", stackBundle.getAlias(), &status); |
| 747 |
ures_getByKey(stackBundle.getAlias(), feature, stackBundle.getAlias(), &status); |
| 748 |
UnicodeString uVal = ures_getUnicodeStringByKey(stackBundle.getAlias(), structure, &status); |
| 749 |
if (U_FAILURE(status)) { |
| 750 |
return {}; |
| 751 |
} |
| 752 |
U_ASSERT(!uVal.isBogus()); |
| 753 |
return uVal; |
| 754 |
} |
| 755 |
|
| 756 |
// Returns the gender string for structures following these rules: |
| 757 |
// |
| 758 |
// <deriveCompound feature="gender" structure="per" value="0"/> |
| 759 |
// <deriveCompound feature="gender" structure="times" value="1"/> |
| 760 |
// |
| 761 |
// Fake example: |
| 762 |
// <deriveCompound feature="gender" structure="power" value="feminine"/> |
| 763 |
// |
| 764 |
// data0 and data1 should be pattern arrays (UnicodeString[ARRAY_SIZE]) that |
| 765 |
// correspond to value="0" and value="1". |
| 766 |
// |
| 767 |
// Pass a nullptr to data1 if the structure has no concept of value="1" (e.g. |
| 768 |
// "prefix" doesn't). |
| 769 |
UnicodeString getDerivedGender(Locale locale, |
| 770 |
const char *structure, |
| 771 |
UnicodeString *data0, |
| 772 |
UnicodeString *data1, |
| 773 |
UErrorCode &status) { |
| 774 |
UnicodeString val = getDeriveCompoundRule(locale, "gender", structure, status); |
| 775 |
if (val.length() == 1) { |
| 776 |
switch (val[0]) { |
| 777 |
case u'0': |
| 778 |
return data0[GENDER_INDEX]; |
| 779 |
case u'1': |
| 780 |
if (data1 == nullptr) { |
| 781 |
return {}; |
| 782 |
} |
| 783 |
return data1[GENDER_INDEX]; |
| 784 |
} |
| 785 |
} |
| 786 |
return val; |
| 787 |
} |
| 788 |
|
| 789 |
//////////////////////// |
| 790 |
/// END DATA LOADING /// |
| 791 |
//////////////////////// |
| 792 |
|
| 793 |
// TODO: promote this somewhere? It's based on patternprops.cpp' trimWhitespace |
| 794 |
const char16_t *trimSpaceChars(const char16_t *s, int32_t &length) { |
| 795 |
if (length <= 0 || (!u_isJavaSpaceChar(s[0]) && !u_isJavaSpaceChar(s[length - 1]))) { |
| 796 |
return s; |
| 797 |
} |
| 798 |
int32_t start = 0; |
| 799 |
int32_t limit = length; |
| 800 |
while (start < limit && u_isJavaSpaceChar(s[start])) { |
| 801 |
++start; |
| 802 |
} |
| 803 |
if (start < limit) { |
| 804 |
// There is non-white space at start; we will not move limit below that, |
| 805 |
// so we need not test start<limit in the loop. |
| 806 |
while (u_isJavaSpaceChar(s[limit - 1])) { |
| 807 |
--limit; |
| 808 |
} |
| 809 |
} |
| 810 |
length = limit - start; |
| 811 |
return s + start; |
| 812 |
} |
| 813 |
|
| 814 |
/** |
| 815 |
* Calculates the gender of an arbitrary unit: this is the *second* |
| 816 |
* implementation of an algorithm to do this: |
| 817 |
* |
| 818 |
* Gender is also calculated in "processPatternTimes": that code path is "bottom |
| 819 |
* up", loading the gender for every component of a compound unit (at the same |
| 820 |
* time as loading the Long Names formatting patterns), even if the gender is |
| 821 |
* unneeded, then combining the single units' genders into the compound unit's |
| 822 |
* gender, according to the rules. This algorithm does a lazier "top-down" |
| 823 |
* evaluation, starting with the compound unit, calculating which single unit's |
| 824 |
* gender is needed by breaking it down according to the rules, and then loading |
| 825 |
* only the gender of the one single unit who's gender is needed. |
| 826 |
* |
| 827 |
* For future refactorings: |
| 828 |
* 1. we could drop processPatternTimes' gender calculation and just call this |
| 829 |
* function: for UNUM_UNIT_WIDTH_FULL_NAME, the unit gender is in the very |
| 830 |
* same table as the formatting patterns, so loading it then may be |
| 831 |
* efficient. For other unit widths however, it needs to be explicitly looked |
| 832 |
* up anyway. |
| 833 |
* 2. alternatively, if CLDR is providing all the genders we need such that we |
| 834 |
* don't need to calculate them in ICU anymore, we could drop this function |
| 835 |
* and keep only processPatternTimes' calculation. (And optimise it a bit?) |
| 836 |
* |
| 837 |
* @param locale The desired locale. |
| 838 |
* @param unit The measure unit to calculate the gender for. |
| 839 |
* @return The gender string for the unit, or an empty string if unknown or |
| 840 |
* ungendered. |
| 841 |
*/ |
| 842 |
UnicodeString calculateGenderForUnit(const Locale &locale, const MeasureUnit &unit, UErrorCode &status) { |
| 843 |
MeasureUnitImpl impl; |
| 844 |
const MeasureUnitImpl& mui = MeasureUnitImpl::forMeasureUnit(unit, impl, status); |
| 845 |
int32_t singleUnitIndex = 0; |
| 846 |
if (mui.complexity == UMEASURE_UNIT_COMPOUND) { |
| 847 |
int32_t startSlice = 0; |
| 848 |
// inclusive |
| 849 |
int32_t endSlice = mui.singleUnits.length()-1; |
| 850 |
U_ASSERT(endSlice > 0); // Else it would not be COMPOUND |
| 851 |
if (mui.singleUnits[endSlice]->dimensionality < 0) { |
| 852 |
// We have a -per- construct |
| 853 |
UnicodeString perRule = getDeriveCompoundRule(locale, "gender", "per", status); |
| 854 |
if (perRule.length() != 1) { |
| 855 |
// Fixed gender for -per- units |
| 856 |
return perRule; |
| 857 |
} |
| 858 |
if (perRule[0] == u'1') { |
| 859 |
// Find the start of the denominator. We already know there is one. |
| 860 |
while (mui.singleUnits[startSlice]->dimensionality >= 0) { |
| 861 |
startSlice++; |
| 862 |
} |
| 863 |
} else { |
| 864 |
// Find the end of the numerator |
| 865 |
while (endSlice >= 0 && mui.singleUnits[endSlice]->dimensionality < 0) { |
| 866 |
endSlice--; |
| 867 |
} |
| 868 |
if (endSlice < 0) { |
| 869 |
// We have only a denominator, e.g. "per-second". |
| 870 |
// TODO(icu-units#28): find out what gender to use in the |
| 871 |
// absence of a first value - mentioned in CLDR-14253. |
| 872 |
return {}; |
| 873 |
} |
| 874 |
} |
| 875 |
} |
| 876 |
if (endSlice > startSlice) { |
| 877 |
// We have a -times- construct |
| 878 |
UnicodeString timesRule = getDeriveCompoundRule(locale, "gender", "times", status); |
| 879 |
if (timesRule.length() != 1) { |
| 880 |
// Fixed gender for -times- units |
| 881 |
return timesRule; |
| 882 |
} |
| 883 |
if (timesRule[0] == u'0') { |
| 884 |
endSlice = startSlice; |
| 885 |
} else { |
| 886 |
// We assume timesRule[0] == u'1' |
| 887 |
startSlice = endSlice; |
| 888 |
} |
| 889 |
} |
| 890 |
U_ASSERT(startSlice == endSlice); |
| 891 |
singleUnitIndex = startSlice; |
| 892 |
} else if (mui.complexity == UMEASURE_UNIT_MIXED) { |
| 893 |
status = U_INTERNAL_PROGRAM_ERROR; |
| 894 |
return {}; |
| 895 |
} else { |
| 896 |
U_ASSERT(mui.complexity == UMEASURE_UNIT_SINGLE); |
| 897 |
U_ASSERT(mui.singleUnits.length() == 1); |
| 898 |
} |
| 899 |
|
| 900 |
// Now we know which singleUnit's gender we want |
| 901 |
const SingleUnitImpl *singleUnit = mui.singleUnits[singleUnitIndex]; |
| 902 |
// Check for any power-prefix gender override: |
| 903 |
if (std::abs(singleUnit->dimensionality) != 1) { |
| 904 |
UnicodeString powerRule = getDeriveCompoundRule(locale, "gender", "power", status); |
| 905 |
if (powerRule.length() != 1) { |
| 906 |
// Fixed gender for -powN- units |
| 907 |
return powerRule; |
| 908 |
} |
| 909 |
// powerRule[0] == u'0'; u'1' not currently in spec. |
| 910 |
} |
| 911 |
// Check for any SI and binary prefix gender override: |
| 912 |
if (std::abs(singleUnit->dimensionality) != 1) { |
| 913 |
UnicodeString prefixRule = getDeriveCompoundRule(locale, "gender", "prefix", status); |
| 914 |
if (prefixRule.length() != 1) { |
| 915 |
// Fixed gender for -powN- units |
| 916 |
return prefixRule; |
| 917 |
} |
| 918 |
// prefixRule[0] == u'0'; u'1' not currently in spec. |
| 919 |
} |
| 920 |
// Now we've boiled it down to the gender of one simple unit identifier: |
| 921 |
return getGenderForBuiltin(locale, MeasureUnit::forIdentifier(singleUnit->getSimpleUnitID(), status), |
| 922 |
status); |
| 923 |
} |
| 924 |
|
| 925 |
void maybeCalculateGender(const Locale &locale, |
| 926 |
const MeasureUnit &unitRef, |
| 927 |
UnicodeString *outArray, |
| 928 |
UErrorCode &status) { |
| 929 |
if (outArray[GENDER_INDEX].isBogus()) { |
| 930 |
UnicodeString meterGender = getGenderForBuiltin(locale, MeasureUnit::getMeter(), status); |
| 931 |
if (meterGender.isEmpty()) { |
| 932 |
// No gender for meter: assume ungendered language |
| 933 |
return; |
| 934 |
} |
| 935 |
// We have a gendered language, but are lacking gender for unitRef. |
| 936 |
outArray[GENDER_INDEX] = calculateGenderForUnit(locale, unitRef, status); |
| 937 |
} |
| 938 |
} |
| 939 |
|
| 940 |
} // namespace |
| 941 |
|
| 942 |
void LongNameHandler::forMeasureUnit(const Locale &loc, |
| 943 |
const MeasureUnit &unitRef, |
| 944 |
const UNumberUnitWidth &width, |
| 945 |
const char *unitDisplayCase, |
| 946 |
const PluralRules *rules, |
| 947 |
const MicroPropsGenerator *parent, |
| 948 |
LongNameHandler *fillIn, |
| 949 |
UErrorCode &status) { |
| 950 |
// From https://unicode.org/reports/tr35/tr35-general.html#compound-units - |
| 951 |
// Points 1 and 2 are mostly handled by MeasureUnit: |
| 952 |
// |
| 953 |
// 1. If the unitId is empty or invalid, fail |
| 954 |
// 2. Put the unitId into normalized order |
| 955 |
U_ASSERT(fillIn != nullptr); |
| 956 |
|
| 957 |
if (uprv_strcmp(unitRef.getType(), "") != 0) { |
| 958 |
// Handling built-in units: |
| 959 |
// |
| 960 |
// 3. Set result to be getValue(unitId with length, pluralCategory, caseVariant) |
| 961 |
// - If result is not empty, return it |
| 962 |
UnicodeString simpleFormats[ARRAY_LENGTH]; |
| 963 |
getMeasureData(loc, unitRef, width, unitDisplayCase, simpleFormats, status); |
| 964 |
maybeCalculateGender(loc, unitRef, simpleFormats, status); |
| 965 |
if (U_FAILURE(status)) { |
| 966 |
return; |
| 967 |
} |
| 968 |
fillIn->rules = rules; |
| 969 |
fillIn->parent = parent; |
| 970 |
fillIn->simpleFormatsToModifiers(simpleFormats, |
| 971 |
{UFIELD_CATEGORY_NUMBER, UNUM_MEASURE_UNIT_FIELD}, status); |
| 972 |
if (!simpleFormats[GENDER_INDEX].isBogus()) { |
| 973 |
fillIn->gender = getGenderString(simpleFormats[GENDER_INDEX], status); |
| 974 |
} |
| 975 |
return; |
| 976 |
|
| 977 |
// TODO(icu-units#145): figure out why this causes a failure in |
| 978 |
// format/MeasureFormatTest/TestIndividualPluralFallback and other |
| 979 |
// tests, when it should have been an alternative for the lines above: |
| 980 |
|
| 981 |
// forArbitraryUnit(loc, unitRef, width, unitDisplayCase, fillIn, status); |
| 982 |
// fillIn->rules = rules; |
| 983 |
// fillIn->parent = parent; |
| 984 |
// return; |
| 985 |
} else { |
| 986 |
// Check if it is a MeasureUnit this constructor handles: this |
| 987 |
// constructor does not handle mixed units |
| 988 |
U_ASSERT(unitRef.getComplexity(status) != UMEASURE_UNIT_MIXED); |
| 989 |
forArbitraryUnit(loc, unitRef, width, unitDisplayCase, fillIn, status); |
| 990 |
fillIn->rules = rules; |
| 991 |
fillIn->parent = parent; |
| 992 |
return; |
| 993 |
} |
| 994 |
} |
| 995 |
|
| 996 |
void LongNameHandler::forArbitraryUnit(const Locale &loc, |
| 997 |
const MeasureUnit &unitRef, |
| 998 |
const UNumberUnitWidth &width, |
| 999 |
const char *unitDisplayCase, |
| 1000 |
LongNameHandler *fillIn, |
| 1001 |
UErrorCode &status) { |
| 1002 |
if (U_FAILURE(status)) { |
| 1003 |
return; |
| 1004 |
} |
| 1005 |
if (fillIn == nullptr) { |
| 1006 |
status = U_INTERNAL_PROGRAM_ERROR; |
| 1007 |
return; |
| 1008 |
} |
| 1009 |
|
| 1010 |
// Numbered list items are from the algorithms at |
| 1011 |
// https://unicode.org/reports/tr35/tr35-general.html#compound-units: |
| 1012 |
// |
| 1013 |
// 4. Divide the unitId into numerator (the part before the "-per-") and |
| 1014 |
// denominator (the part after the "-per-). If both are empty, fail |
| 1015 |
MeasureUnitImpl unit; |
| 1016 |
MeasureUnitImpl perUnit; |
| 1017 |
|
| 1018 |
if (unitRef.getConstantDenominator(status) != 0) { |
| 1019 |
perUnit.constantDenominator = unitRef.getConstantDenominator(status); |
| 1020 |
} |
| 1021 |
|
| 1022 |
{ |
| 1023 |
MeasureUnitImpl fullUnit = MeasureUnitImpl::forMeasureUnitMaybeCopy(unitRef, status); |
| 1024 |
if (U_FAILURE(status)) { |
| 1025 |
return; |
| 1026 |
} |
| 1027 |
for (int32_t i = 0; i < fullUnit.singleUnits.length(); i++) { |
| 1028 |
SingleUnitImpl *subUnit = fullUnit.singleUnits[i]; |
| 1029 |
if (subUnit->dimensionality > 0) { |
| 1030 |
unit.appendSingleUnit(*subUnit, status); |
| 1031 |
} else { |
| 1032 |
subUnit->dimensionality *= -1; |
| 1033 |
perUnit.appendSingleUnit(*subUnit, status); |
| 1034 |
} |
| 1035 |
} |
| 1036 |
} |
| 1037 |
|
| 1038 |
// TODO(icu-units#28): check placeholder logic, see if it needs to be |
| 1039 |
// present here instead of only in processPatternTimes: |
| 1040 |
// |
| 1041 |
// 5. Set both globalPlaceholder and globalPlaceholderPosition to be empty |
| 1042 |
|
| 1043 |
DerivedComponents derivedPerCases(loc, "case", "per"); |
| 1044 |
|
| 1045 |
// 6. numeratorUnitString |
| 1046 |
UnicodeString numeratorUnitData[ARRAY_LENGTH]; |
| 1047 |
processPatternTimes(std::move(unit), loc, width, derivedPerCases.value0(unitDisplayCase), |
| 1048 |
numeratorUnitData, status); |
| 1049 |
|
| 1050 |
// 7. denominatorUnitString |
| 1051 |
UnicodeString denominatorUnitData[ARRAY_LENGTH]; |
| 1052 |
processPatternTimes(std::move(perUnit), loc, width, derivedPerCases.value1(unitDisplayCase), |
| 1053 |
denominatorUnitData, status); |
| 1054 |
|
| 1055 |
// TODO(icu-units#139): |
| 1056 |
// - implement DerivedComponents for "plural/times" and "plural/power": |
| 1057 |
// French has different rules, we'll be producing the wrong results |
| 1058 |
// currently. (Prove via tests!) |
| 1059 |
// - implement DerivedComponents for "plural/per", "plural/prefix", |
| 1060 |
// "case/times", "case/power", and "case/prefix" - although they're |
| 1061 |
// currently hardcoded. Languages with different rules are surely on the |
| 1062 |
// way. |
| 1063 |
// |
| 1064 |
// Currently we only use "case/per", "plural/times", "case/times", and |
| 1065 |
// "case/power". |
| 1066 |
// |
| 1067 |
// This may have impact on multiSimpleFormatsToModifiers(...) below too? |
| 1068 |
// These rules are currently (ICU 69) all the same and hard-coded below. |
| 1069 |
UnicodeString perUnitPattern; |
| 1070 |
if (!denominatorUnitData[PER_INDEX].isBogus()) { |
| 1071 |
// If we have no denominator, we obtain the empty string: |
| 1072 |
perUnitPattern = denominatorUnitData[PER_INDEX]; |
| 1073 |
} else { |
| 1074 |
// 8. Set perPattern to be getValue([per], locale, length) |
| 1075 |
UnicodeString rawPerUnitFormat = getCompoundValue("per", loc, width, status); |
| 1076 |
// rawPerUnitFormat is something like "{0} per {1}"; we need to substitute in the secondary unit. |
| 1077 |
SimpleFormatter perPatternFormatter(rawPerUnitFormat, 2, 2, status); |
| 1078 |
if (U_FAILURE(status)) { |
| 1079 |
return; |
| 1080 |
} |
| 1081 |
// Plural and placeholder handling for 7. denominatorUnitString: |
| 1082 |
// TODO(icu-units#139): hardcoded: |
| 1083 |
// <deriveComponent feature="plural" structure="per" value0="compound" value1="one"/> |
| 1084 |
UnicodeString denominatorFormat = |
| 1085 |
getWithPlural(denominatorUnitData, StandardPlural::Form::ONE, status); |
| 1086 |
// Some "one" pattern may not contain "{0}". For example in "ar" or "ne" locale. |
| 1087 |
SimpleFormatter denominatorFormatter(denominatorFormat, 0, 1, status); |
| 1088 |
if (U_FAILURE(status)) { |
| 1089 |
return; |
| 1090 |
} |
| 1091 |
UnicodeString denominatorPattern = denominatorFormatter.getTextWithNoArguments(); |
| 1092 |
int32_t trimmedLen = denominatorPattern.length(); |
| 1093 |
const char16_t *trimmed = trimSpaceChars(denominatorPattern.getBuffer(), trimmedLen); |
| 1094 |
UnicodeString denominatorString(false, trimmed, trimmedLen); |
| 1095 |
// 9. If the denominatorString is empty, set result to |
| 1096 |
// [numeratorString], otherwise set result to format(perPattern, |
| 1097 |
// numeratorString, denominatorString) |
| 1098 |
// |
| 1099 |
// TODO(icu-units#28): Why does UnicodeString need to be explicit in the |
| 1100 |
// following line? |
| 1101 |
perPatternFormatter.format(UnicodeString(u"{0}"), denominatorString, perUnitPattern, status); |
| 1102 |
if (U_FAILURE(status)) { |
| 1103 |
return; |
| 1104 |
} |
| 1105 |
} |
| 1106 |
if (perUnitPattern.length() == 0) { |
| 1107 |
fillIn->simpleFormatsToModifiers(numeratorUnitData, |
| 1108 |
{UFIELD_CATEGORY_NUMBER, UNUM_MEASURE_UNIT_FIELD}, status); |
| 1109 |
} else { |
| 1110 |
fillIn->multiSimpleFormatsToModifiers(numeratorUnitData, perUnitPattern, |
| 1111 |
{UFIELD_CATEGORY_NUMBER, UNUM_MEASURE_UNIT_FIELD}, status); |
| 1112 |
} |
| 1113 |
|
| 1114 |
// Gender |
| 1115 |
// |
| 1116 |
// TODO(icu-units#28): find out what gender to use in the absence of a first |
| 1117 |
// value - e.g. what's the gender of "per-second"? Mentioned in CLDR-14253. |
| 1118 |
// |
| 1119 |
// gender/per deriveCompound rules don't say: |
| 1120 |
// <deriveCompound feature="gender" structure="per" value="0"/> <!-- gender(gram-per-meter) ← gender(gram) --> |
| 1121 |
fillIn->gender = getGenderString( |
| 1122 |
getDerivedGender(loc, "per", numeratorUnitData, denominatorUnitData, status), status); |
| 1123 |
} |
| 1124 |
|
| 1125 |
void LongNameHandler::processPatternTimes(MeasureUnitImpl &&productUnit, |
| 1126 |
Locale loc, |
| 1127 |
const UNumberUnitWidth &width, |
| 1128 |
const char *caseVariant, |
| 1129 |
UnicodeString *outArray, |
| 1130 |
UErrorCode &status) { |
| 1131 |
if (U_FAILURE(status)) { |
| 1132 |
return; |
| 1133 |
} |
| 1134 |
if (productUnit.complexity == UMEASURE_UNIT_MIXED) { |
| 1135 |
// These are handled by MixedUnitLongNameHandler |
| 1136 |
status = U_UNSUPPORTED_ERROR; |
| 1137 |
return; |
| 1138 |
} |
| 1139 |
|
| 1140 |
#if U_DEBUG |
| 1141 |
for (int32_t pluralIndex = 0; pluralIndex < ARRAY_LENGTH; pluralIndex++) { |
| 1142 |
U_ASSERT(outArray[pluralIndex].length() == 0); |
| 1143 |
U_ASSERT(!outArray[pluralIndex].isBogus()); |
| 1144 |
} |
| 1145 |
#endif |
| 1146 |
|
| 1147 |
if (productUnit.identifier.isEmpty()) { |
| 1148 |
// TODO(icu-units#28): consider when serialize should be called. |
| 1149 |
// identifier might also be empty for MeasureUnit(). |
| 1150 |
productUnit.serialize(status); |
| 1151 |
} |
| 1152 |
if (U_FAILURE(status)) { |
| 1153 |
return; |
| 1154 |
} |
| 1155 |
if (productUnit.identifier.length() == 0) { |
| 1156 |
// MeasureUnit(): no units: return empty strings. |
| 1157 |
return; |
| 1158 |
} |
| 1159 |
|
| 1160 |
MeasureUnit builtinUnit; |
| 1161 |
if (MeasureUnit::findBySubType(productUnit.identifier.toStringPiece(), &builtinUnit)) { |
| 1162 |
// TODO(icu-units#145): spec doesn't cover builtin-per-builtin, it |
| 1163 |
// breaks them all down. Do we want to drop this? |
| 1164 |
// - findBySubType isn't super efficient, if we skip it and go to basic |
| 1165 |
// singles, we don't have to construct MeasureUnit's anymore. |
| 1166 |
// - Check all the existing unit tests that fail without this: is it due |
| 1167 |
// to incorrect fallback via getMeasureData? |
| 1168 |
// - Do those unit tests cover this code path representatively? |
| 1169 |
if (builtinUnit != MeasureUnit()) { |
| 1170 |
getMeasureData(loc, builtinUnit, width, caseVariant, outArray, status); |
| 1171 |
maybeCalculateGender(loc, builtinUnit, outArray, status); |
| 1172 |
} |
| 1173 |
return; |
| 1174 |
} |
| 1175 |
|
| 1176 |
// 2. Set timesPattern to be getValue(times, locale, length) |
| 1177 |
UnicodeString timesPattern = getCompoundValue("times", loc, width, status); |
| 1178 |
SimpleFormatter timesPatternFormatter(timesPattern, 2, 2, status); |
| 1179 |
if (U_FAILURE(status)) { |
| 1180 |
return; |
| 1181 |
} |
| 1182 |
|
| 1183 |
PlaceholderPosition globalPlaceholder[ARRAY_LENGTH]; |
| 1184 |
char16_t globalJoinerChar = 0; |
| 1185 |
// Numbered list items are from the algorithms at |
| 1186 |
// https://unicode.org/reports/tr35/tr35-general.html#compound-units: |
| 1187 |
// |
| 1188 |
// pattern(...) point 5: |
| 1189 |
// - Set both globalPlaceholder and globalPlaceholderPosition to be empty |
| 1190 |
// |
| 1191 |
// 3. Set result to be empty |
| 1192 |
for (int32_t pluralIndex = 0; pluralIndex < ARRAY_LENGTH; pluralIndex++) { |
| 1193 |
// Initial state: empty string pattern, via all falling back to OTHER: |
| 1194 |
if (pluralIndex == StandardPlural::Form::OTHER) { |
| 1195 |
outArray[pluralIndex].remove(); |
| 1196 |
} else { |
| 1197 |
outArray[pluralIndex].setToBogus(); |
| 1198 |
} |
| 1199 |
globalPlaceholder[pluralIndex] = PH_EMPTY; |
| 1200 |
} |
| 1201 |
|
| 1202 |
// Empty string represents "compound" (propagate the plural form). |
| 1203 |
const char *pluralCategory = ""; |
| 1204 |
DerivedComponents derivedTimesPlurals(loc, "plural", "times"); |
| 1205 |
DerivedComponents derivedTimesCases(loc, "case", "times"); |
| 1206 |
DerivedComponents derivedPowerCases(loc, "case", "power"); |
| 1207 |
|
| 1208 |
if (productUnit.constantDenominator != 0) { |
| 1209 |
CharString constantString; |
| 1210 |
constantString.appendNumber(productUnit.constantDenominator, status); |
| 1211 |
outArray[CONSTANT_DENOMINATOR_INDEX] = UnicodeString::fromUTF8(constantString.toStringPiece()); |
| 1212 |
} |
| 1213 |
|
| 1214 |
// 4. For each single_unit in product_unit |
| 1215 |
for (int32_t singleUnitIndex = 0; singleUnitIndex < productUnit.singleUnits.length(); |
| 1216 |
singleUnitIndex++) { |
| 1217 |
SingleUnitImpl *singleUnit = productUnit.singleUnits[singleUnitIndex]; |
| 1218 |
const char *singlePluralCategory; |
| 1219 |
const char *singleCaseVariant; |
| 1220 |
// TODO(icu-units#28): ensure we have unit tests that change/fail if we |
| 1221 |
// assign incorrect case variants here: |
| 1222 |
if (singleUnitIndex < productUnit.singleUnits.length() - 1) { |
| 1223 |
// 4.1. If hasMultiple |
| 1224 |
singlePluralCategory = derivedTimesPlurals.value0(pluralCategory); |
| 1225 |
singleCaseVariant = derivedTimesCases.value0(caseVariant); |
| 1226 |
pluralCategory = derivedTimesPlurals.value1(pluralCategory); |
| 1227 |
caseVariant = derivedTimesCases.value1(caseVariant); |
| 1228 |
} else { |
| 1229 |
singlePluralCategory = derivedTimesPlurals.value1(pluralCategory); |
| 1230 |
singleCaseVariant = derivedTimesCases.value1(caseVariant); |
| 1231 |
} |
| 1232 |
|
| 1233 |
// 4.2. Get the gender of that single_unit |
| 1234 |
MeasureUnit simpleUnit; |
| 1235 |
if (!MeasureUnit::findBySubType(singleUnit->getSimpleUnitID(), &simpleUnit)) { |
| 1236 |
// Ideally all simple units should be known, but they're not: |
| 1237 |
// 100-kilometer is internally treated as a simple unit, but it is |
| 1238 |
// not a built-in unit and does not have formatting data in CLDR 39. |
| 1239 |
// |
| 1240 |
// TODO(icu-units#28): test (desirable) invariants in unit tests. |
| 1241 |
status = U_UNSUPPORTED_ERROR; |
| 1242 |
return; |
| 1243 |
} |
| 1244 |
const char *gender = getGenderString(getGenderForBuiltin(loc, simpleUnit, status), status); |
| 1245 |
|
| 1246 |
// 4.3. If singleUnit starts with a dimensionality_prefix, such as 'square-' |
| 1247 |
U_ASSERT(singleUnit->dimensionality > 0); |
| 1248 |
int32_t dimensionality = singleUnit->dimensionality; |
| 1249 |
UnicodeString dimensionalityPrefixPatterns[ARRAY_LENGTH]; |
| 1250 |
if (dimensionality != 1) { |
| 1251 |
// 4.3.1. set dimensionalityPrefixPattern to be |
| 1252 |
// getValue(that dimensionality_prefix, locale, length, singlePluralCategory, singleCaseVariant, gender), |
| 1253 |
// such as "{0} kwadratowym" |
| 1254 |
CharString dimensionalityKey("compound/power", status); |
| 1255 |
dimensionalityKey.appendNumber(dimensionality, status); |
| 1256 |
getInflectedMeasureData(dimensionalityKey.toStringPiece(), loc, width, gender, |
| 1257 |
singleCaseVariant, dimensionalityPrefixPatterns, status); |
| 1258 |
if (U_FAILURE(status)) { |
| 1259 |
// At the time of writing, only pow2 and pow3 are supported. |
| 1260 |
// Attempting to format other powers results in a |
| 1261 |
// U_RESOURCE_TYPE_MISMATCH. We convert the error if we |
| 1262 |
// understand it: |
| 1263 |
if (status == U_RESOURCE_TYPE_MISMATCH && dimensionality > 3) { |
| 1264 |
status = U_UNSUPPORTED_ERROR; |
| 1265 |
} |
| 1266 |
return; |
| 1267 |
} |
| 1268 |
|
| 1269 |
// TODO(icu-units#139): |
| 1270 |
// 4.3.2. set singlePluralCategory to be power0(singlePluralCategory) |
| 1271 |
|
| 1272 |
// 4.3.3. set singleCaseVariant to be power0(singleCaseVariant) |
| 1273 |
singleCaseVariant = derivedPowerCases.value0(singleCaseVariant); |
| 1274 |
// 4.3.4. remove the dimensionality_prefix from singleUnit |
| 1275 |
singleUnit->dimensionality = 1; |
| 1276 |
} |
| 1277 |
|
| 1278 |
// 4.4. if singleUnit starts with an si_prefix, such as 'centi' |
| 1279 |
UMeasurePrefix prefix = singleUnit->unitPrefix; |
| 1280 |
UnicodeString prefixPattern; |
| 1281 |
if (prefix != UMEASURE_PREFIX_ONE) { |
| 1282 |
// 4.4.1. set siPrefixPattern to be getValue(that si_prefix, locale, |
| 1283 |
// length), such as "centy{0}" |
| 1284 |
CharString prefixKey; |
| 1285 |
// prefixKey looks like "1024p3" or "10p-2": |
| 1286 |
prefixKey.appendNumber(umeas_getPrefixBase(prefix), status); |
| 1287 |
prefixKey.append('p', status); |
| 1288 |
prefixKey.appendNumber(umeas_getPrefixPower(prefix), status); |
| 1289 |
// Contains a pattern like "centy{0}". |
| 1290 |
prefixPattern = getCompoundValue(prefixKey.toStringPiece(), loc, width, status); |
| 1291 |
|
| 1292 |
// 4.4.2. set singlePluralCategory to be prefix0(singlePluralCategory) |
| 1293 |
// |
| 1294 |
// TODO(icu-units#139): that refers to these rules: |
| 1295 |
// <deriveComponent feature="plural" structure="prefix" value0="one" value1="compound"/> |
| 1296 |
// though I'm not sure what other value they might end up having. |
| 1297 |
// |
| 1298 |
// 4.4.3. set singleCaseVariant to be prefix0(singleCaseVariant) |
| 1299 |
// |
| 1300 |
// TODO(icu-units#139): that refers to: |
| 1301 |
// <deriveComponent feature="case" structure="prefix" value0="nominative" |
| 1302 |
// value1="compound"/> but the prefix (value0) doesn't have case, the rest simply |
| 1303 |
// propagates. |
| 1304 |
|
| 1305 |
// 4.4.4. remove the si_prefix from singleUnit |
| 1306 |
singleUnit->unitPrefix = UMEASURE_PREFIX_ONE; |
| 1307 |
} |
| 1308 |
|
| 1309 |
// 4.5. Set corePattern to be the getValue(singleUnit, locale, length, |
| 1310 |
// singlePluralCategory, singleCaseVariant), such as "{0} metrem" |
| 1311 |
UnicodeString singleUnitArray[ARRAY_LENGTH]; |
| 1312 |
// At this point we are left with a Simple Unit: |
| 1313 |
U_ASSERT(uprv_strcmp(singleUnit->build(status).getIdentifier(), singleUnit->getSimpleUnitID()) == |
| 1314 |
0); |
| 1315 |
getMeasureData(loc, singleUnit->build(status), width, singleCaseVariant, singleUnitArray, |
| 1316 |
status); |
| 1317 |
if (U_FAILURE(status)) { |
| 1318 |
// Shouldn't happen if we have data for all single units |
| 1319 |
return; |
| 1320 |
} |
| 1321 |
|
| 1322 |
// Calculate output gender |
| 1323 |
if (!singleUnitArray[GENDER_INDEX].isBogus()) { |
| 1324 |
U_ASSERT(!singleUnitArray[GENDER_INDEX].isEmpty()); |
| 1325 |
UnicodeString uVal; |
| 1326 |
|
| 1327 |
if (prefix != UMEASURE_PREFIX_ONE) { |
| 1328 |
singleUnitArray[GENDER_INDEX] = |
| 1329 |
getDerivedGender(loc, "prefix", singleUnitArray, nullptr, status); |
| 1330 |
} |
| 1331 |
|
| 1332 |
if (dimensionality != 1) { |
| 1333 |
singleUnitArray[GENDER_INDEX] = |
| 1334 |
getDerivedGender(loc, "power", singleUnitArray, nullptr, status); |
| 1335 |
} |
| 1336 |
|
| 1337 |
UnicodeString timesGenderRule = getDeriveCompoundRule(loc, "gender", "times", status); |
| 1338 |
if (timesGenderRule.length() == 1) { |
| 1339 |
switch (timesGenderRule[0]) { |
| 1340 |
case u'0': |
| 1341 |
if (singleUnitIndex == 0) { |
| 1342 |
U_ASSERT(outArray[GENDER_INDEX].isBogus()); |
| 1343 |
outArray[GENDER_INDEX] = singleUnitArray[GENDER_INDEX]; |
| 1344 |
} |
| 1345 |
break; |
| 1346 |
case u'1': |
| 1347 |
if (singleUnitIndex == productUnit.singleUnits.length() - 1) { |
| 1348 |
U_ASSERT(outArray[GENDER_INDEX].isBogus()); |
| 1349 |
outArray[GENDER_INDEX] = singleUnitArray[GENDER_INDEX]; |
| 1350 |
} |
| 1351 |
} |
| 1352 |
} else { |
| 1353 |
if (outArray[GENDER_INDEX].isBogus()) { |
| 1354 |
outArray[GENDER_INDEX] = timesGenderRule; |
| 1355 |
} |
| 1356 |
} |
| 1357 |
} |
| 1358 |
|
| 1359 |
// Calculate resulting patterns for each plural form |
| 1360 |
for (int32_t pluralIndex = 0; pluralIndex < StandardPlural::Form::COUNT; pluralIndex++) { |
| 1361 |
StandardPlural::Form plural = static_cast<StandardPlural::Form>(pluralIndex); |
| 1362 |
|
| 1363 |
// singleUnitArray[pluralIndex] looks something like "{0} Meter" |
| 1364 |
if (outArray[pluralIndex].isBogus()) { |
| 1365 |
if (singleUnitArray[pluralIndex].isBogus()) { |
| 1366 |
// Let the usual plural fallback mechanism take care of this |
| 1367 |
// plural form |
| 1368 |
continue; |
| 1369 |
} else { |
| 1370 |
// Since our singleUnit can have a plural form that outArray |
| 1371 |
// doesn't yet have (relying on fallback to OTHER), we start |
| 1372 |
// by grabbing it with the normal plural fallback mechanism |
| 1373 |
outArray[pluralIndex] = getWithPlural(outArray, plural, status); |
| 1374 |
if (U_FAILURE(status)) { |
| 1375 |
return; |
| 1376 |
} |
| 1377 |
} |
| 1378 |
} |
| 1379 |
|
| 1380 |
if (uprv_strcmp(singlePluralCategory, "") != 0) { |
| 1381 |
plural = static_cast<StandardPlural::Form>(getIndex(singlePluralCategory, status)); |
| 1382 |
} |
| 1383 |
|
| 1384 |
// 4.6. Extract(corePattern, coreUnit, placeholder, placeholderPosition) from that pattern. |
| 1385 |
UnicodeString coreUnit; |
| 1386 |
PlaceholderPosition placeholderPosition; |
| 1387 |
char16_t joinerChar; |
| 1388 |
extractCorePattern(getWithPlural(singleUnitArray, plural, status), coreUnit, |
| 1389 |
placeholderPosition, joinerChar); |
| 1390 |
|
| 1391 |
// 4.7 If the position is middle, then fail |
| 1392 |
if (placeholderPosition == PH_MIDDLE) { |
| 1393 |
status = U_UNSUPPORTED_ERROR; |
| 1394 |
return; |
| 1395 |
} |
| 1396 |
|
| 1397 |
// 4.8. If globalPlaceholder is empty |
| 1398 |
if (globalPlaceholder[pluralIndex] == PH_EMPTY) { |
| 1399 |
globalPlaceholder[pluralIndex] = placeholderPosition; |
| 1400 |
globalJoinerChar = joinerChar; |
| 1401 |
} else { |
| 1402 |
// Expect all units involved to have the same placeholder position |
| 1403 |
U_ASSERT(globalPlaceholder[pluralIndex] == placeholderPosition); |
| 1404 |
// TODO(icu-units#28): Do we want to add a unit test that checks |
| 1405 |
// for consistent joiner chars? Probably not, given how |
| 1406 |
// inconsistent they are. File a CLDR ticket with examples? |
| 1407 |
} |
| 1408 |
// Now coreUnit would be just "Meter" |
| 1409 |
|
| 1410 |
// 4.9. If siPrefixPattern is not empty |
| 1411 |
if (prefix != UMEASURE_PREFIX_ONE) { |
| 1412 |
SimpleFormatter prefixCompiled(prefixPattern, 1, 1, status); |
| 1413 |
if (U_FAILURE(status)) { |
| 1414 |
return; |
| 1415 |
} |
| 1416 |
|
| 1417 |
// 4.9.1. Set coreUnit to be the combineLowercasing(locale, length, siPrefixPattern, |
| 1418 |
// coreUnit) |
| 1419 |
UnicodeString tmp; |
| 1420 |
// combineLowercasing(locale, length, prefixPattern, coreUnit) |
| 1421 |
// |
| 1422 |
// TODO(icu-units#28): run this only if prefixPattern does not |
| 1423 |
// contain space characters - do languages "as", "bn", "hi", |
| 1424 |
// "kk", etc have concepts of upper and lower case?: |
| 1425 |
if (width == UNUM_UNIT_WIDTH_FULL_NAME) { |
| 1426 |
coreUnit.toLower(loc); |
| 1427 |
} |
| 1428 |
prefixCompiled.format(coreUnit, tmp, status); |
| 1429 |
if (U_FAILURE(status)) { |
| 1430 |
return; |
| 1431 |
} |
| 1432 |
coreUnit = tmp; |
| 1433 |
} |
| 1434 |
|
| 1435 |
// 4.10. If dimensionalityPrefixPattern is not empty |
| 1436 |
if (dimensionality != 1) { |
| 1437 |
SimpleFormatter dimensionalityCompiled( |
| 1438 |
getWithPlural(dimensionalityPrefixPatterns, plural, status), 1, 1, status); |
| 1439 |
if (U_FAILURE(status)) { |
| 1440 |
return; |
| 1441 |
} |
| 1442 |
|
| 1443 |
// 4.10.1. Set coreUnit to be the combineLowercasing(locale, length, |
| 1444 |
// dimensionalityPrefixPattern, coreUnit) |
| 1445 |
UnicodeString tmp; |
| 1446 |
// combineLowercasing(locale, length, prefixPattern, coreUnit) |
| 1447 |
// |
| 1448 |
// TODO(icu-units#28): run this only if prefixPattern does not |
| 1449 |
// contain space characters - do languages "as", "bn", "hi", |
| 1450 |
// "kk", etc have concepts of upper and lower case?: |
| 1451 |
if (width == UNUM_UNIT_WIDTH_FULL_NAME) { |
| 1452 |
coreUnit.toLower(loc); |
| 1453 |
} |
| 1454 |
dimensionalityCompiled.format(coreUnit, tmp, status); |
| 1455 |
if (U_FAILURE(status)) { |
| 1456 |
return; |
| 1457 |
} |
| 1458 |
coreUnit = tmp; |
| 1459 |
} |
| 1460 |
|
| 1461 |
if (outArray[pluralIndex].length() == 0) { |
| 1462 |
// 4.11. If the result is empty, set result to be coreUnit |
| 1463 |
outArray[pluralIndex] = coreUnit; |
| 1464 |
} else { |
| 1465 |
// 4.12. Otherwise set result to be format(timesPattern, result, coreUnit) |
| 1466 |
UnicodeString tmp; |
| 1467 |
timesPatternFormatter.format(outArray[pluralIndex], coreUnit, tmp, status); |
| 1468 |
outArray[pluralIndex] = tmp; |
| 1469 |
} |
| 1470 |
} |
| 1471 |
} |
| 1472 |
|
| 1473 |
// 5. Handling constant denominator if it exists. |
| 1474 |
if (productUnit.constantDenominator != 0) { |
| 1475 |
int32_t pluralIndex = -1; |
| 1476 |
for (int32_t index = 0; index < StandardPlural::Form::COUNT; index++) { |
| 1477 |
if (!outArray[index].isBogus()) { |
| 1478 |
pluralIndex = index; |
| 1479 |
break; |
| 1480 |
} |
| 1481 |
} |
| 1482 |
|
| 1483 |
U_ASSERT(pluralIndex >= 0); // "No plural form found for constant denominator" |
| 1484 |
|
| 1485 |
// TODO(ICU-23039): |
| 1486 |
// Improve the handling of constant_denominator representation. |
| 1487 |
// For instance, a constant_denominator of 1000000 should be adaptable to |
| 1488 |
// formats like |
| 1489 |
// 1,000,000, 1e6, or 1 million. |
| 1490 |
// Furthermore, ensure consistent pluralization rules for units. For example, |
| 1491 |
// "meter per 100 seconds" should be evaluated for correct singular/plural |
| 1492 |
// usage: "second" or "seconds"? |
| 1493 |
// Similarly, "kilogram per 1000 meters" should be checked for "meter" or |
| 1494 |
// "meters"? |
| 1495 |
if (outArray[pluralIndex].length() == 0) { |
| 1496 |
outArray[pluralIndex] = outArray[CONSTANT_DENOMINATOR_INDEX]; |
| 1497 |
} else { |
| 1498 |
UnicodeString tmp; |
| 1499 |
timesPatternFormatter.format(outArray[CONSTANT_DENOMINATOR_INDEX], outArray[pluralIndex], |
| 1500 |
tmp, status); |
| 1501 |
outArray[pluralIndex] = tmp; |
| 1502 |
} |
| 1503 |
} |
| 1504 |
|
| 1505 |
for (int32_t pluralIndex = 0; pluralIndex < StandardPlural::Form::COUNT; pluralIndex++) { |
| 1506 |
if (globalPlaceholder[pluralIndex] == PH_BEGINNING) { |
| 1507 |
UnicodeString tmp; |
| 1508 |
tmp.append(u"{0}", 3); |
| 1509 |
if (globalJoinerChar != 0) { |
| 1510 |
tmp.append(globalJoinerChar); |
| 1511 |
} |
| 1512 |
tmp.append(outArray[pluralIndex]); |
| 1513 |
outArray[pluralIndex] = tmp; |
| 1514 |
} else if (globalPlaceholder[pluralIndex] == PH_END) { |
| 1515 |
if (globalJoinerChar != 0) { |
| 1516 |
outArray[pluralIndex].append(globalJoinerChar); |
| 1517 |
} |
| 1518 |
outArray[pluralIndex].append(u"{0}", 3); |
| 1519 |
} |
| 1520 |
} |
| 1521 |
} |
| 1522 |
|
| 1523 |
UnicodeString LongNameHandler::getUnitDisplayName( |
| 1524 |
const Locale& loc, |
| 1525 |
const MeasureUnit& unit, |
| 1526 |
UNumberUnitWidth width, |
| 1527 |
UErrorCode& status) { |
| 1528 |
if (U_FAILURE(status)) { |
| 1529 |
return ICU_Utility::makeBogusString(); |
| 1530 |
} |
| 1531 |
UnicodeString simpleFormats[ARRAY_LENGTH]; |
| 1532 |
getMeasureData(loc, unit, width, "", simpleFormats, status); |
| 1533 |
return simpleFormats[DNAM_INDEX]; |
| 1534 |
} |
| 1535 |
|
| 1536 |
UnicodeString LongNameHandler::getUnitPattern( |
| 1537 |
const Locale& loc, |
| 1538 |
const MeasureUnit& unit, |
| 1539 |
UNumberUnitWidth width, |
| 1540 |
StandardPlural::Form pluralForm, |
| 1541 |
UErrorCode& status) { |
| 1542 |
if (U_FAILURE(status)) { |
| 1543 |
return ICU_Utility::makeBogusString(); |
| 1544 |
} |
| 1545 |
UnicodeString simpleFormats[ARRAY_LENGTH]; |
| 1546 |
getMeasureData(loc, unit, width, "", simpleFormats, status); |
| 1547 |
// The above already handles fallback from other widths to short |
| 1548 |
if (U_FAILURE(status)) { |
| 1549 |
return ICU_Utility::makeBogusString(); |
| 1550 |
} |
| 1551 |
// Now handle fallback from other plural forms to OTHER |
| 1552 |
return (!(simpleFormats[pluralForm]).isBogus())? simpleFormats[pluralForm]: |
| 1553 |
simpleFormats[StandardPlural::Form::OTHER]; |
| 1554 |
} |
| 1555 |
|
| 1556 |
LongNameHandler* LongNameHandler::forCurrencyLongNames(const Locale &loc, const CurrencyUnit ¤cy, |
| 1557 |
const PluralRules *rules, |
| 1558 |
const MicroPropsGenerator *parent, |
| 1559 |
UErrorCode &status) { |
| 1560 |
LocalPointer<LongNameHandler> result(new LongNameHandler(rules, parent), status); |
| 1561 |
if (U_FAILURE(status)) { |
| 1562 |
return nullptr; |
| 1563 |
} |
| 1564 |
UnicodeString simpleFormats[ARRAY_LENGTH]; |
| 1565 |
getCurrencyLongNameData(loc, currency, simpleFormats, status); |
| 1566 |
if (U_FAILURE(status)) { return nullptr; } |
| 1567 |
result->simpleFormatsToModifiers(simpleFormats, {UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD}, status); |
| 1568 |
// TODO(icu-units#28): currency gender? |
| 1569 |
return result.orphan(); |
| 1570 |
} |
| 1571 |
|
| 1572 |
void LongNameHandler::simpleFormatsToModifiers(const UnicodeString *simpleFormats, Field field, |
| 1573 |
UErrorCode &status) { |
| 1574 |
for (int32_t i = 0; i < StandardPlural::Form::COUNT; i++) { |
| 1575 |
StandardPlural::Form plural = static_cast<StandardPlural::Form>(i); |
| 1576 |
UnicodeString simpleFormat = getWithPlural(simpleFormats, plural, status); |
| 1577 |
if (U_FAILURE(status)) { return; } |
| 1578 |
SimpleFormatter compiledFormatter(simpleFormat, 0, 1, status); |
| 1579 |
if (U_FAILURE(status)) { return; } |
| 1580 |
fModifiers[i] = SimpleModifier(compiledFormatter, field, false, {this, SIGNUM_POS_ZERO, plural}); |
| 1581 |
} |
| 1582 |
} |
| 1583 |
|
| 1584 |
void LongNameHandler::multiSimpleFormatsToModifiers(const UnicodeString *leadFormats, UnicodeString trailFormat, |
| 1585 |
Field field, UErrorCode &status) { |
| 1586 |
SimpleFormatter trailCompiled(trailFormat, 1, 1, status); |
| 1587 |
if (U_FAILURE(status)) { return; } |
| 1588 |
for (int32_t i = 0; i < StandardPlural::Form::COUNT; i++) { |
| 1589 |
StandardPlural::Form plural = static_cast<StandardPlural::Form>(i); |
| 1590 |
UnicodeString leadFormat = getWithPlural(leadFormats, plural, status); |
| 1591 |
if (U_FAILURE(status)) { return; } |
| 1592 |
UnicodeString compoundFormat; |
| 1593 |
if (leadFormat.length() == 0) { |
| 1594 |
compoundFormat = trailFormat; |
| 1595 |
} else { |
| 1596 |
trailCompiled.format(leadFormat, compoundFormat, status); |
| 1597 |
if (U_FAILURE(status)) { return; } |
| 1598 |
} |
| 1599 |
SimpleFormatter compoundCompiled(compoundFormat, 0, 1, status); |
| 1600 |
if (U_FAILURE(status)) { return; } |
| 1601 |
fModifiers[i] = SimpleModifier(compoundCompiled, field, false, {this, SIGNUM_POS_ZERO, plural}); |
| 1602 |
} |
| 1603 |
} |
| 1604 |
|
| 1605 |
void LongNameHandler::processQuantity(DecimalQuantity &quantity, MicroProps µs, |
| 1606 |
UErrorCode &status) const { |
| 1607 |
if (parent != nullptr) { |
| 1608 |
parent->processQuantity(quantity, micros, status); |
| 1609 |
} |
| 1610 |
StandardPlural::Form pluralForm = utils::getPluralSafe(micros.rounder, rules, quantity, status); |
| 1611 |
micros.modOuter = &fModifiers[pluralForm]; |
| 1612 |
micros.gender = gender; |
| 1613 |
} |
| 1614 |
|
| 1615 |
const Modifier* LongNameHandler::getModifier(Signum /*signum*/, StandardPlural::Form plural) const { |
| 1616 |
return &fModifiers[plural]; |
| 1617 |
} |
| 1618 |
|
| 1619 |
void MixedUnitLongNameHandler::forMeasureUnit(const Locale &loc, |
| 1620 |
const MeasureUnit &mixedUnit, |
| 1621 |
const UNumberUnitWidth &width, |
| 1622 |
const char *unitDisplayCase, |
| 1623 |
const PluralRules *rules, |
| 1624 |
const MicroPropsGenerator *parent, |
| 1625 |
MixedUnitLongNameHandler *fillIn, |
| 1626 |
UErrorCode &status) { |
| 1627 |
U_ASSERT(mixedUnit.getComplexity(status) == UMEASURE_UNIT_MIXED); |
| 1628 |
U_ASSERT(fillIn != nullptr); |
| 1629 |
if (U_FAILURE(status)) { |
| 1630 |
return; |
| 1631 |
} |
| 1632 |
|
| 1633 |
MeasureUnitImpl temp; |
| 1634 |
const MeasureUnitImpl &impl = MeasureUnitImpl::forMeasureUnit(mixedUnit, temp, status); |
| 1635 |
// Defensive, for production code: |
| 1636 |
if (impl.complexity != UMEASURE_UNIT_MIXED) { |
| 1637 |
// Should be using the normal LongNameHandler |
| 1638 |
status = U_UNSUPPORTED_ERROR; |
| 1639 |
return; |
| 1640 |
} |
| 1641 |
|
| 1642 |
fillIn->fMixedUnitCount = impl.singleUnits.length(); |
| 1643 |
fillIn->fMixedUnitData.adoptInstead(new UnicodeString[fillIn->fMixedUnitCount * ARRAY_LENGTH]); |
| 1644 |
for (int32_t i = 0; i < fillIn->fMixedUnitCount; i++) { |
| 1645 |
// Grab data for each of the components. |
| 1646 |
UnicodeString *unitData = &fillIn->fMixedUnitData[i * ARRAY_LENGTH]; |
| 1647 |
// TODO(CLDR-14582): check from the CLDR-14582 ticket whether this |
| 1648 |
// propagation of unitDisplayCase is correct: |
| 1649 |
getMeasureData(loc, impl.singleUnits[i]->build(status), width, unitDisplayCase, unitData, |
| 1650 |
status); |
| 1651 |
// TODO(ICU-21494): if we add support for gender for mixed units, we may |
| 1652 |
// need maybeCalculateGender() here. |
| 1653 |
} |
| 1654 |
|
| 1655 |
// TODO(icu-units#120): Make sure ICU doesn't output zero-valued |
| 1656 |
// high-magnitude fields |
| 1657 |
// * for mixed units count N, produce N listFormatters, one for each subset |
| 1658 |
// that might be formatted. |
| 1659 |
UListFormatterWidth listWidth = ULISTFMT_WIDTH_SHORT; |
| 1660 |
if (width == UNUM_UNIT_WIDTH_NARROW) { |
| 1661 |
listWidth = ULISTFMT_WIDTH_NARROW; |
| 1662 |
} else if (width == UNUM_UNIT_WIDTH_FULL_NAME) { |
| 1663 |
// This might be the same as SHORT in most languages: |
| 1664 |
listWidth = ULISTFMT_WIDTH_WIDE; |
| 1665 |
} |
| 1666 |
fillIn->fListFormatter.adoptInsteadAndCheckErrorCode( |
| 1667 |
ListFormatter::createInstance(loc, ULISTFMT_TYPE_UNITS, listWidth, status), status); |
| 1668 |
// TODO(ICU-21494): grab gender of each unit, calculate the gender |
| 1669 |
// associated with this list formatter, save it for later. |
| 1670 |
fillIn->rules = rules; |
| 1671 |
fillIn->parent = parent; |
| 1672 |
|
| 1673 |
// We need a localised NumberFormatter for the numbers of the bigger units |
| 1674 |
// (providing Arabic numerals, for example). |
| 1675 |
fillIn->fNumberFormatter = NumberFormatter::withLocale(loc); |
| 1676 |
} |
| 1677 |
|
| 1678 |
void MixedUnitLongNameHandler::processQuantity(DecimalQuantity &quantity, MicroProps µs, |
| 1679 |
UErrorCode &status) const { |
| 1680 |
U_ASSERT(fMixedUnitCount > 1); |
| 1681 |
if (parent != nullptr) { |
| 1682 |
parent->processQuantity(quantity, micros, status); |
| 1683 |
} |
| 1684 |
micros.modOuter = getMixedUnitModifier(quantity, micros, status); |
| 1685 |
} |
| 1686 |
|
| 1687 |
const Modifier *MixedUnitLongNameHandler::getMixedUnitModifier(DecimalQuantity &quantity, |
| 1688 |
MicroProps µs, |
| 1689 |
UErrorCode &status) const { |
| 1690 |
if (micros.mixedMeasuresCount == 0) { |
| 1691 |
U_ASSERT(micros.mixedMeasuresCount > 0); // Mixed unit: we must have more than one unit value |
| 1692 |
status = U_UNSUPPORTED_ERROR; |
| 1693 |
return µs.helpers.emptyWeakModifier; |
| 1694 |
} |
| 1695 |
|
| 1696 |
// Algorithm: |
| 1697 |
// |
| 1698 |
// For the mixed-units measurement of: "3 yard, 1 foot, 2.6 inch", we should |
| 1699 |
// find "3 yard" and "1 foot" in micros.mixedMeasures. |
| 1700 |
// |
| 1701 |
// Obtain long-names with plural forms corresponding to measure values: |
| 1702 |
// * {0} yards, {0} foot, {0} inches |
| 1703 |
// |
| 1704 |
// Format the integer values appropriately and modify with the format |
| 1705 |
// strings: |
| 1706 |
// - 3 yards, 1 foot |
| 1707 |
// |
| 1708 |
// Use ListFormatter to combine, with one placeholder: |
| 1709 |
// - 3 yards, 1 foot and {0} inches |
| 1710 |
// |
| 1711 |
// Return a SimpleModifier for this pattern, letting the rest of the |
| 1712 |
// pipeline take care of the remaining inches. |
| 1713 |
|
| 1714 |
LocalArray<UnicodeString> outputMeasuresList(new UnicodeString[fMixedUnitCount], status); |
| 1715 |
if (U_FAILURE(status)) { |
| 1716 |
return µs.helpers.emptyWeakModifier; |
| 1717 |
} |
| 1718 |
|
| 1719 |
StandardPlural::Form quantityPlural = StandardPlural::Form::OTHER; |
| 1720 |
for (int32_t i = 0; i < micros.mixedMeasuresCount; i++) { |
| 1721 |
DecimalQuantity fdec; |
| 1722 |
|
| 1723 |
// If numbers are negative, only the first number needs to have its |
| 1724 |
// negative sign formatted. |
| 1725 |
int64_t number = i > 0 ? std::abs(micros.mixedMeasures[i]) : micros.mixedMeasures[i]; |
| 1726 |
|
| 1727 |
if (micros.indexOfQuantity == i) { // Insert placeholder for `quantity` |
| 1728 |
// If quantity is not the first value and quantity is negative |
| 1729 |
if (micros.indexOfQuantity > 0 && quantity.isNegative()) { |
| 1730 |
quantity.negate(); |
| 1731 |
} |
| 1732 |
|
| 1733 |
StandardPlural::Form quantityPlural = |
| 1734 |
utils::getPluralSafe(micros.rounder, rules, quantity, status); |
| 1735 |
UnicodeString quantityFormatWithPlural = |
| 1736 |
getWithPlural(&fMixedUnitData[i * ARRAY_LENGTH], quantityPlural, status); |
| 1737 |
SimpleFormatter quantityFormatter(quantityFormatWithPlural, 0, 1, status); |
| 1738 |
quantityFormatter.format(UnicodeString(u"{0}"), outputMeasuresList[i], status); |
| 1739 |
} else { |
| 1740 |
fdec.setToLong(number); |
| 1741 |
StandardPlural::Form pluralForm = utils::getStandardPlural(rules, fdec); |
| 1742 |
UnicodeString simpleFormat = |
| 1743 |
getWithPlural(&fMixedUnitData[i * ARRAY_LENGTH], pluralForm, status); |
| 1744 |
SimpleFormatter compiledFormatter(simpleFormat, 0, 1, status); |
| 1745 |
UnicodeString num; |
| 1746 |
auto appendable = UnicodeStringAppendable(num); |
| 1747 |
|
| 1748 |
fNumberFormatter.formatDecimalQuantity(fdec, status).appendTo(appendable, status); |
| 1749 |
compiledFormatter.format(num, outputMeasuresList[i], status); |
| 1750 |
} |
| 1751 |
} |
| 1752 |
|
| 1753 |
// TODO(ICU-21494): implement gender for lists of mixed units. Presumably we |
| 1754 |
// can set micros.gender to the gender associated with the list formatter in |
| 1755 |
// use below (once we have correct support for that). And then document this |
| 1756 |
// appropriately? "getMixedUnitModifier" doesn't sound like it would do |
| 1757 |
// something like this. |
| 1758 |
|
| 1759 |
// Combine list into a "premixed" pattern |
| 1760 |
UnicodeString premixedFormatPattern; |
| 1761 |
fListFormatter->format(outputMeasuresList.getAlias(), fMixedUnitCount, premixedFormatPattern, |
| 1762 |
status); |
| 1763 |
SimpleFormatter premixedCompiled(premixedFormatPattern, 0, 1, status); |
| 1764 |
if (U_FAILURE(status)) { |
| 1765 |
return µs.helpers.emptyWeakModifier; |
| 1766 |
} |
| 1767 |
|
| 1768 |
micros.helpers.mixedUnitModifier = |
| 1769 |
SimpleModifier(premixedCompiled, kUndefinedField, false, {this, SIGNUM_POS_ZERO, quantityPlural}); |
| 1770 |
return µs.helpers.mixedUnitModifier; |
| 1771 |
} |
| 1772 |
|
| 1773 |
const Modifier *MixedUnitLongNameHandler::getModifier(Signum /*signum*/, |
| 1774 |
StandardPlural::Form /*plural*/) const { |
| 1775 |
// TODO(icu-units#28): investigate this method when investigating where |
| 1776 |
// ModifierStore::getModifier() gets used. To be sure it remains |
| 1777 |
// unreachable: |
| 1778 |
UPRV_UNREACHABLE_EXIT; |
| 1779 |
return nullptr; |
| 1780 |
} |
| 1781 |
|
| 1782 |
LongNameMultiplexer *LongNameMultiplexer::forMeasureUnits(const Locale &loc, |
| 1783 |
const MaybeStackVector<MeasureUnit> &units, |
| 1784 |
const UNumberUnitWidth &width, |
| 1785 |
const char *unitDisplayCase, |
| 1786 |
const PluralRules *rules, |
| 1787 |
const MicroPropsGenerator *parent, |
| 1788 |
UErrorCode &status) { |
| 1789 |
LocalPointer<LongNameMultiplexer> result(new LongNameMultiplexer(parent), status); |
| 1790 |
if (U_FAILURE(status)) { |
| 1791 |
return nullptr; |
| 1792 |
} |
| 1793 |
U_ASSERT(units.length() > 0); |
| 1794 |
if (result->fHandlers.resize(units.length()) == nullptr) { |
| 1795 |
status = U_MEMORY_ALLOCATION_ERROR; |
| 1796 |
return nullptr; |
| 1797 |
} |
| 1798 |
result->fMeasureUnits.adoptInstead(new MeasureUnit[units.length()]); |
| 1799 |
for (int32_t i = 0, length = units.length(); i < length; i++) { |
| 1800 |
const MeasureUnit &unit = *units[i]; |
| 1801 |
result->fMeasureUnits[i] = unit; |
| 1802 |
if (unit.getComplexity(status) == UMEASURE_UNIT_MIXED) { |
| 1803 |
MixedUnitLongNameHandler *mlnh = result->fMixedUnitHandlers.createAndCheckErrorCode(status); |
| 1804 |
MixedUnitLongNameHandler::forMeasureUnit(loc, unit, width, unitDisplayCase, rules, nullptr, |
| 1805 |
mlnh, status); |
| 1806 |
result->fHandlers[i] = mlnh; |
| 1807 |
} else { |
| 1808 |
LongNameHandler *lnh = result->fLongNameHandlers.createAndCheckErrorCode(status); |
| 1809 |
LongNameHandler::forMeasureUnit(loc, unit, width, unitDisplayCase, rules, nullptr, lnh, status); |
| 1810 |
result->fHandlers[i] = lnh; |
| 1811 |
} |
| 1812 |
if (U_FAILURE(status)) { |
| 1813 |
return nullptr; |
| 1814 |
} |
| 1815 |
} |
| 1816 |
return result.orphan(); |
| 1817 |
} |
| 1818 |
|
| 1819 |
void LongNameMultiplexer::processQuantity(DecimalQuantity &quantity, MicroProps µs, |
| 1820 |
UErrorCode &status) const { |
| 1821 |
// We call parent->processQuantity() from the Multiplexer, instead of |
| 1822 |
// letting LongNameHandler handle it: we don't know which LongNameHandler to |
| 1823 |
// call until we've called the parent! |
| 1824 |
fParent->processQuantity(quantity, micros, status); |
| 1825 |
|
| 1826 |
// Call the correct LongNameHandler based on outputUnit |
| 1827 |
for (int i = 0; i < fHandlers.getCapacity(); i++) { |
| 1828 |
if (fMeasureUnits[i] == micros.outputUnit) { |
| 1829 |
fHandlers[i]->processQuantity(quantity, micros, status); |
| 1830 |
return; |
| 1831 |
} |
| 1832 |
} |
| 1833 |
if (U_FAILURE(status)) { |
| 1834 |
return; |
| 1835 |
} |
| 1836 |
// We shouldn't receive any outputUnit for which we haven't already got a |
| 1837 |
// LongNameHandler: |
| 1838 |
status = U_INTERNAL_PROGRAM_ERROR; |
| 1839 |
} |
| 1840 |
|
| 1841 |
#endif /* #if !UCONFIG_NO_FORMATTING */ |