Debian Codegraph @

intl/icu/source/i18n/measunit_extra.cpp

raw
1 // © 2020 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3
4 // Extra functions for MeasureUnit not needed for all clients.
5 // Separate .o file so that it can be removed for modularity.
6
7 #include "unicode/utypes.h"
8
9 #if !UCONFIG_NO_FORMATTING
10
11 // Allow implicit conversion from char16_t* to UnicodeString for this file:
12 // Helpful in toString methods and elsewhere.
13 #define UNISTR_FROM_STRING_EXPLICIT
14
15 #include "charstr.h"
16 #include "cmemory.h"
17 #include "cstring.h"
18 #ifdef JS_HAS_INTL_API
19 #include "double-conversion/string-to-double.h"
20 #else
21 #include "double-conversion-string-to-double.h"
22 #endif
23 #include "measunit_impl.h"
24 #include "resource.h"
25 #include "uarrsort.h"
26 #include "uassert.h"
27 #include "ucln_in.h"
28 #include "umutex.h"
29 #include "unicode/bytestrie.h"
30 #include "unicode/bytestriebuilder.h"
31 #include "unicode/localpointer.h"
32 #include "unicode/stringpiece.h"
33 #include "unicode/stringtriebuilder.h"
34 #include "unicode/ures.h"
35 #include "unicode/ustringtrie.h"
36 #include "uresimp.h"
37 #include "util.h"
38 #include <limits.h>
39 #include <cstdlib>
40 U_NAMESPACE_BEGIN
41
42
43 namespace {
44
45 #ifdef JS_HAS_INTL_API
46 using double_conversion::StringToDoubleConverter;
47 #else
48 using icu::double_conversion::StringToDoubleConverter;
49 #endif
50
51 // TODO: Propose a new error code for this?
52 constexpr UErrorCode kUnitIdentifierSyntaxError = U_ILLEGAL_ARGUMENT_ERROR;
53
54 // Trie value offset for SI or binary prefixes. This is big enough to ensure we only
55 // insert positive integers into the trie.
56 constexpr int32_t kPrefixOffset = 64;
57 static_assert(kPrefixOffset + UMEASURE_PREFIX_INTERNAL_MIN_BIN > 0,
58 "kPrefixOffset is too small for minimum UMeasurePrefix value");
59 static_assert(kPrefixOffset + UMEASURE_PREFIX_INTERNAL_MIN_SI > 0,
60 "kPrefixOffset is too small for minimum UMeasurePrefix value");
61
62 // Trie value offset for compound parts, e.g. "-per-", "-", "-and-".
63 constexpr int32_t kCompoundPartOffset = 128;
64 static_assert(kCompoundPartOffset > kPrefixOffset + UMEASURE_PREFIX_INTERNAL_MAX_BIN,
65 "Ambiguous token values: prefix tokens are overlapping with CompoundPart tokens");
66 static_assert(kCompoundPartOffset > kPrefixOffset + UMEASURE_PREFIX_INTERNAL_MAX_SI,
67 "Ambiguous token values: prefix tokens are overlapping with CompoundPart tokens");
68
69 enum CompoundPart {
70 // Represents "-per-"
71 COMPOUND_PART_PER = kCompoundPartOffset,
72 // Represents "-"
73 COMPOUND_PART_TIMES,
74 // Represents "-and-"
75 COMPOUND_PART_AND,
76 };
77
78 // Trie value offset for "per-".
79 constexpr int32_t kInitialCompoundPartOffset = 192;
80
81 enum InitialCompoundPart {
82 // Represents "per-", the only compound part that can appear at the start of
83 // an identifier.
84 INITIAL_COMPOUND_PART_PER = kInitialCompoundPartOffset,
85 };
86
87 // Trie value offset for powers like "square-", "cubic-", "pow2-" etc.
88 constexpr int32_t kPowerPartOffset = 256;
89
90 enum PowerPart {
91 POWER_PART_P2 = kPowerPartOffset + 2,
92 POWER_PART_P3,
93 POWER_PART_P4,
94 POWER_PART_P5,
95 POWER_PART_P6,
96 POWER_PART_P7,
97 POWER_PART_P8,
98 POWER_PART_P9,
99 POWER_PART_P10,
100 POWER_PART_P11,
101 POWER_PART_P12,
102 POWER_PART_P13,
103 POWER_PART_P14,
104 POWER_PART_P15,
105 };
106
107 // Trie value offset for simple units, e.g. "gram", "nautical-mile",
108 // "fluid-ounce-imperial".
109 constexpr int32_t kSimpleUnitOffset = 512;
110
111 const struct UnitPrefixStrings {
112 const char* const string;
113 UMeasurePrefix value;
114 } gUnitPrefixStrings[] = {
115 // SI prefixes
116 { "quetta", UMEASURE_PREFIX_QUETTA },
117 { "ronna", UMEASURE_PREFIX_RONNA },
118 { "yotta", UMEASURE_PREFIX_YOTTA },
119 { "zetta", UMEASURE_PREFIX_ZETTA },
120 { "exa", UMEASURE_PREFIX_EXA },
121 { "peta", UMEASURE_PREFIX_PETA },
122 { "tera", UMEASURE_PREFIX_TERA },
123 { "giga", UMEASURE_PREFIX_GIGA },
124 { "mega", UMEASURE_PREFIX_MEGA },
125 { "kilo", UMEASURE_PREFIX_KILO },
126 { "hecto", UMEASURE_PREFIX_HECTO },
127 { "deka", UMEASURE_PREFIX_DEKA },
128 { "deci", UMEASURE_PREFIX_DECI },
129 { "centi", UMEASURE_PREFIX_CENTI },
130 { "milli", UMEASURE_PREFIX_MILLI },
131 { "micro", UMEASURE_PREFIX_MICRO },
132 { "nano", UMEASURE_PREFIX_NANO },
133 { "pico", UMEASURE_PREFIX_PICO },
134 { "femto", UMEASURE_PREFIX_FEMTO },
135 { "atto", UMEASURE_PREFIX_ATTO },
136 { "zepto", UMEASURE_PREFIX_ZEPTO },
137 { "yocto", UMEASURE_PREFIX_YOCTO },
138 { "ronto", UMEASURE_PREFIX_RONTO },
139 { "quecto", UMEASURE_PREFIX_QUECTO },
140 // Binary prefixes
141 { "yobi", UMEASURE_PREFIX_YOBI },
142 { "zebi", UMEASURE_PREFIX_ZEBI },
143 { "exbi", UMEASURE_PREFIX_EXBI },
144 { "pebi", UMEASURE_PREFIX_PEBI },
145 { "tebi", UMEASURE_PREFIX_TEBI },
146 { "gibi", UMEASURE_PREFIX_GIBI },
147 { "mebi", UMEASURE_PREFIX_MEBI },
148 { "kibi", UMEASURE_PREFIX_KIBI },
149 };
150
151 /**
152 * A ResourceSink that collects simple unit identifiers from the keys of the
153 * convertUnits table into an array, and adds these values to a TrieBuilder,
154 * with associated values being their index into this array plus a specified
155 * offset.
156 *
157 * Example code:
158 *
159 * UErrorCode status = U_ZERO_ERROR;
160 * BytesTrieBuilder b(status);
161 * int32_t ARR_SIZE = 200;
162 * const char *unitIdentifiers[ARR_SIZE];
163 * int32_t *unitCategories[ARR_SIZE];
164 * SimpleUnitIdentifiersSink identifierSink(gSerializedUnitCategoriesTrie, unitIdentifiers,
165 * unitCategories, ARR_SIZE, b, kTrieValueOffset);
166 * LocalUResourceBundlePointer unitsBundle(ures_openDirect(nullptr, "units", &status));
167 * ures_getAllItemsWithFallback(unitsBundle.getAlias(), "convertUnits", identifierSink, status);
168 */
169 class SimpleUnitIdentifiersSink : public icu::ResourceSink {
170 public:
171 /**
172 * Constructor.
173 * @param quantitiesTrieData The data for constructing a quantitiesTrie,
174 * which maps from a simple unit identifier to an index into the
175 * gCategories array.
176 * @param out Array of char* to which pointers to the simple unit
177 * identifiers will be saved. (Does not take ownership.)
178 * @param outCategories Array of int32_t to which category indexes will be
179 * saved: this corresponds to simple unit IDs saved to `out`, mapping
180 * from the ID to the value produced by the quantitiesTrie (which is an
181 * index into the gCategories array).
182 * @param outSize The size of `out` and `outCategories`.
183 * @param trieBuilder The trie builder to which the simple unit identifier
184 * should be added. The trie builder must outlive this resource sink.
185 * @param trieValueOffset This is added to the index of the identifier in
186 * the `out` array, before adding to `trieBuilder` as the value
187 * associated with the identifier.
188 */
189 explicit SimpleUnitIdentifiersSink(StringPiece quantitiesTrieData, const char **out,
190 int32_t *outCategories, int32_t outSize,
191 BytesTrieBuilder &trieBuilder, int32_t trieValueOffset)
192 : outArray(out), outCategories(outCategories), outSize(outSize), trieBuilder(trieBuilder),
193 trieValueOffset(trieValueOffset), quantitiesTrieData(quantitiesTrieData), outIndex(0) {}
194
195 /**
196 * Adds the table keys found in value to the output vector.
197 * @param key The key of the resource passed to `value`: the second
198 * parameter of the ures_getAllItemsWithFallback() call.
199 * @param value Should be a ResourceTable value, if
200 * ures_getAllItemsWithFallback() was called correctly for this sink.
201 * @param noFallback Ignored.
202 * @param status The standard ICU error code output parameter.
203 */
204 void put(const char * /*key*/, ResourceValue &value, UBool /*noFallback*/, UErrorCode &status) override {
205 ResourceTable table = value.getTable(status);
206 if (U_FAILURE(status)) return;
207
208 if (outIndex + table.getSize() > outSize) {
209 status = U_INDEX_OUTOFBOUNDS_ERROR;
210 return;
211 }
212
213 BytesTrie quantitiesTrie(quantitiesTrieData.data());
214
215 // Collect keys from the table resource.
216 const char *simpleUnitID;
217 for (int32_t i = 0; table.getKeyAndValue(i, simpleUnitID, value); ++i) {
218 U_ASSERT(i < table.getSize());
219 U_ASSERT(outIndex < outSize);
220 if (uprv_strcmp(simpleUnitID, "kilogram") == 0) {
221 // For parsing, we use "gram", the prefixless metric mass unit. We
222 // thus ignore the SI Base Unit of Mass: it exists due to being the
223 // mass conversion target unit, but not needed for MeasureUnit
224 // parsing.
225 continue;
226 }
227 outArray[outIndex] = simpleUnitID;
228 trieBuilder.add(simpleUnitID, trieValueOffset + outIndex, status);
229
230 // Find the base target unit for this simple unit
231 ResourceTable table = value.getTable(status);
232 if (U_FAILURE(status)) { return; }
233 if (!table.findValue("target", value)) {
234 status = U_INVALID_FORMAT_ERROR;
235 break;
236 }
237 int32_t len;
238 const char16_t* uTarget = value.getString(len, status);
239 CharString target;
240 target.appendInvariantChars(uTarget, len, status);
241 if (U_FAILURE(status)) { return; }
242 quantitiesTrie.reset();
243 UStringTrieResult result = quantitiesTrie.next(target.data(), target.length());
244 if (!USTRINGTRIE_HAS_VALUE(result)) {
245 status = U_INVALID_FORMAT_ERROR;
246 break;
247 }
248 outCategories[outIndex] = quantitiesTrie.getValue();
249
250 outIndex++;
251 }
252 }
253
254 private:
255 const char **outArray;
256 int32_t *outCategories;
257 int32_t outSize;
258 BytesTrieBuilder &trieBuilder;
259 int32_t trieValueOffset;
260
261 StringPiece quantitiesTrieData;
262
263 int32_t outIndex;
264 };
265
266 /**
267 * A ResourceSink that collects information from `unitQuantities` in the `units`
268 * resource to provide key->value lookups from base unit to category, as well as
269 * preserving ordering information for these categories. See `units.txt`.
270 *
271 * For example: "kilogram" -> "mass", "meter-per-second" -> "speed".
272 *
273 * In C++ unitQuantity values are collected in order into a char16_t* array, while
274 * unitQuantity keys are added added to a TrieBuilder, with associated values
275 * being the index into the aforementioned char16_t* array.
276 */
277 class CategoriesSink : public icu::ResourceSink {
278 public:
279 /**
280 * Constructor.
281 * @param out Array of char16_t* to which unitQuantity values will be saved.
282 * The pointers returned not owned: they point directly at the resource
283 * strings in static memory.
284 * @param outSize The size of the `out` array.
285 * @param trieBuilder The trie builder to which the keys (base units) of
286 * each unitQuantity will be added, each with value being the offset
287 * into `out`.
288 */
289 explicit CategoriesSink(const char16_t **out, int32_t &outSize, BytesTrieBuilder &trieBuilder)
290 : outQuantitiesArray(out), outSize(outSize), trieBuilder(trieBuilder), outIndex(0) {}
291
292 void put(const char * /*key*/, ResourceValue &value, UBool /*noFallback*/, UErrorCode &status) override {
293 ResourceArray array = value.getArray(status);
294 if (U_FAILURE(status)) {
295 return;
296 }
297
298 if (outIndex + array.getSize() > outSize) {
299 status = U_INDEX_OUTOFBOUNDS_ERROR;
300 return;
301 }
302
303 for (int32_t i = 0; array.getValue(i, value); ++i) {
304 U_ASSERT(outIndex < outSize);
305 ResourceTable table = value.getTable(status);
306 if (U_FAILURE(status)) {
307 return;
308 }
309 if (table.getSize() != 1) {
310 status = U_INVALID_FORMAT_ERROR;
311 return;
312 }
313 const char *key;
314 table.getKeyAndValue(0, key, value);
315 int32_t uTmpLen;
316 outQuantitiesArray[outIndex] = value.getString(uTmpLen, status);
317 trieBuilder.add(key, outIndex, status);
318 outIndex++;
319 }
320 }
321
322 private:
323 const char16_t **outQuantitiesArray;
324 int32_t &outSize;
325 BytesTrieBuilder &trieBuilder;
326
327 int32_t outIndex;
328 };
329
330 icu::UInitOnce gUnitExtrasInitOnce {};
331
332 // Array of simple unit IDs.
333 //
334 // The array memory itself is owned by this pointer, but the individual char* in
335 // that array point at static memory. (Note that these char* are also returned
336 // by SingleUnitImpl::getSimpleUnitID().)
337 const char **gSimpleUnits = nullptr;
338
339 // Maps from the value associated with each simple unit ID to an index into the
340 // gCategories array.
341 int32_t *gSimpleUnitCategories = nullptr;
342
343 char *gSerializedUnitExtrasStemTrie = nullptr;
344
345 // Array of char16_t* pointing at the unit categories (aka "quantities", aka
346 // "types"), as found in the `unitQuantities` resource. The array memory itself
347 // is owned by this pointer, but the individual char16_t* in that array point at
348 // static memory.
349 const char16_t **gCategories = nullptr;
350 // Number of items in `gCategories`.
351 int32_t gCategoriesCount = 0;
352 // Serialized BytesTrie for mapping from base units to indices into gCategories.
353 char *gSerializedUnitCategoriesTrie = nullptr;
354
355 UBool U_CALLCONV cleanupUnitExtras() {
356 uprv_free(gSerializedUnitCategoriesTrie);
357 gSerializedUnitCategoriesTrie = nullptr;
358 uprv_free(gCategories);
359 gCategories = nullptr;
360 uprv_free(gSerializedUnitExtrasStemTrie);
361 gSerializedUnitExtrasStemTrie = nullptr;
362 uprv_free(gSimpleUnitCategories);
363 gSimpleUnitCategories = nullptr;
364 uprv_free(gSimpleUnits);
365 gSimpleUnits = nullptr;
366 gUnitExtrasInitOnce.reset();
367 return true;
368 }
369
370 void U_CALLCONV initUnitExtras(UErrorCode& status) {
371 ucln_i18n_registerCleanup(UCLN_I18N_UNIT_EXTRAS, cleanupUnitExtras);
372 LocalUResourceBundlePointer unitsBundle(ures_openDirect(nullptr, "units", &status));
373
374 // Collect unitQuantities information into gSerializedUnitCategoriesTrie and gCategories.
375 const char *CATEGORY_TABLE_NAME = "unitQuantities";
376 LocalUResourceBundlePointer unitQuantities(
377 ures_getByKey(unitsBundle.getAlias(), CATEGORY_TABLE_NAME, nullptr, &status));
378 if (U_FAILURE(status)) { return; }
379 gCategoriesCount = unitQuantities.getAlias()->fSize;
380 size_t quantitiesMallocSize = sizeof(char16_t *) * gCategoriesCount;
381 gCategories = static_cast<const char16_t **>(uprv_malloc(quantitiesMallocSize));
382 if (gCategories == nullptr) {
383 status = U_MEMORY_ALLOCATION_ERROR;
384 return;
385 }
386 uprv_memset(gCategories, 0, quantitiesMallocSize);
387 BytesTrieBuilder quantitiesBuilder(status);
388 CategoriesSink categoriesSink(gCategories, gCategoriesCount, quantitiesBuilder);
389 ures_getAllItemsWithFallback(unitsBundle.getAlias(), CATEGORY_TABLE_NAME, categoriesSink, status);
390 StringPiece resultQuantities = quantitiesBuilder.buildStringPiece(USTRINGTRIE_BUILD_FAST, status);
391 if (U_FAILURE(status)) { return; }
392 // Copy the result into the global constant pointer
393 size_t numBytesQuantities = resultQuantities.length();
394 gSerializedUnitCategoriesTrie = static_cast<char *>(uprv_malloc(numBytesQuantities));
395 if (gSerializedUnitCategoriesTrie == nullptr) {
396 status = U_MEMORY_ALLOCATION_ERROR;
397 return;
398 }
399 uprv_memcpy(gSerializedUnitCategoriesTrie, resultQuantities.data(), numBytesQuantities);
400
401 // Build the BytesTrie that Parser needs for parsing unit identifiers.
402
403 BytesTrieBuilder b(status);
404 if (U_FAILURE(status)) { return; }
405
406 // Add SI and binary prefixes
407 for (const auto& unitPrefixInfo : gUnitPrefixStrings) {
408 b.add(unitPrefixInfo.string, unitPrefixInfo.value + kPrefixOffset, status);
409 }
410 if (U_FAILURE(status)) { return; }
411
412 // Add syntax parts (compound, power prefixes)
413 b.add("-per-", COMPOUND_PART_PER, status);
414 b.add("-", COMPOUND_PART_TIMES, status);
415 b.add("-and-", COMPOUND_PART_AND, status);
416 b.add("per-", INITIAL_COMPOUND_PART_PER, status);
417 b.add("square-", POWER_PART_P2, status);
418 b.add("cubic-", POWER_PART_P3, status);
419 b.add("pow2-", POWER_PART_P2, status);
420 b.add("pow3-", POWER_PART_P3, status);
421 b.add("pow4-", POWER_PART_P4, status);
422 b.add("pow5-", POWER_PART_P5, status);
423 b.add("pow6-", POWER_PART_P6, status);
424 b.add("pow7-", POWER_PART_P7, status);
425 b.add("pow8-", POWER_PART_P8, status);
426 b.add("pow9-", POWER_PART_P9, status);
427 b.add("pow10-", POWER_PART_P10, status);
428 b.add("pow11-", POWER_PART_P11, status);
429 b.add("pow12-", POWER_PART_P12, status);
430 b.add("pow13-", POWER_PART_P13, status);
431 b.add("pow14-", POWER_PART_P14, status);
432 b.add("pow15-", POWER_PART_P15, status);
433 if (U_FAILURE(status)) { return; }
434
435 // Add sanctioned simple units by offset: simple units all have entries in
436 // units/convertUnits resources.
437 LocalUResourceBundlePointer convertUnits(
438 ures_getByKey(unitsBundle.getAlias(), "convertUnits", nullptr, &status));
439 if (U_FAILURE(status)) { return; }
440
441 // Allocate enough space: with identifierSink below skipping kilogram, we're
442 // probably allocating one more than needed.
443 int32_t simpleUnitsCount = convertUnits.getAlias()->fSize;
444 int32_t arrayMallocSize = sizeof(char *) * simpleUnitsCount;
445 gSimpleUnits = static_cast<const char **>(uprv_malloc(arrayMallocSize));
446 if (gSimpleUnits == nullptr) {
447 status = U_MEMORY_ALLOCATION_ERROR;
448 return;
449 }
450 uprv_memset(gSimpleUnits, 0, arrayMallocSize);
451 arrayMallocSize = sizeof(int32_t) * simpleUnitsCount;
452 gSimpleUnitCategories = static_cast<int32_t *>(uprv_malloc(arrayMallocSize));
453 if (gSimpleUnitCategories == nullptr) {
454 status = U_MEMORY_ALLOCATION_ERROR;
455 return;
456 }
457 uprv_memset(gSimpleUnitCategories, 0, arrayMallocSize);
458
459 // Populate gSimpleUnits and build the associated trie.
460 SimpleUnitIdentifiersSink identifierSink(resultQuantities, gSimpleUnits, gSimpleUnitCategories,
461 simpleUnitsCount, b, kSimpleUnitOffset);
462 ures_getAllItemsWithFallback(unitsBundle.getAlias(), "convertUnits", identifierSink, status);
463
464 // Build the CharsTrie
465 // TODO: Use SLOW or FAST here?
466 StringPiece result = b.buildStringPiece(USTRINGTRIE_BUILD_FAST, status);
467 if (U_FAILURE(status)) { return; }
468
469 // Copy the result into the global constant pointer
470 size_t numBytes = result.length();
471 gSerializedUnitExtrasStemTrie = static_cast<char *>(uprv_malloc(numBytes));
472 if (gSerializedUnitExtrasStemTrie == nullptr) {
473 status = U_MEMORY_ALLOCATION_ERROR;
474 return;
475 }
476 uprv_memcpy(gSerializedUnitExtrasStemTrie, result.data(), numBytes);
477 }
478
479 class Token {
480 public:
481 Token(int64_t match) : fMatch(match) {
482 if (fMatch < kCompoundPartOffset) {
483 this->fType = TYPE_PREFIX;
484 } else if (fMatch < kInitialCompoundPartOffset) {
485 this->fType = TYPE_COMPOUND_PART;
486 } else if (fMatch < kPowerPartOffset) {
487 this->fType = TYPE_INITIAL_COMPOUND_PART;
488 } else if (fMatch < kSimpleUnitOffset) {
489 this->fType = TYPE_POWER_PART;
490 } else {
491 this->fType = TYPE_SIMPLE_UNIT;
492 }
493 }
494
495 static Token constantToken(StringPiece str, UErrorCode &status) {
496 Token result;
497 auto value = Token::parseStringToLong(str, status);
498 if (U_FAILURE(status)) {
499 return result;
500 }
501 result.fMatch = value;
502 result.fType = TYPE_CONSTANT_DENOMINATOR;
503 return result;
504 }
505
506 enum Type {
507 TYPE_UNDEFINED,
508 TYPE_PREFIX,
509 // Token type for "-per-", "-", and "-and-".
510 TYPE_COMPOUND_PART,
511 // Token type for "per-".
512 TYPE_INITIAL_COMPOUND_PART,
513 TYPE_POWER_PART,
514 TYPE_SIMPLE_UNIT,
515 TYPE_CONSTANT_DENOMINATOR,
516 };
517
518 // Calling getType() is invalid, resulting in an assertion failure, if Token
519 // value isn't positive.
520 Type getType() const {
521 U_ASSERT(fMatch >= 0);
522 return this->fType;
523 }
524
525 // Retrieve the value of the constant denominator if the token is of type TYPE_CONSTANT_DENOMINATOR.
526 uint64_t getConstantDenominator() const {
527 U_ASSERT(getType() == TYPE_CONSTANT_DENOMINATOR);
528 return static_cast<uint64_t>(fMatch);
529 }
530
531 UMeasurePrefix getUnitPrefix() const {
532 U_ASSERT(getType() == TYPE_PREFIX);
533 return static_cast<UMeasurePrefix>(fMatch - kPrefixOffset);
534 }
535
536 // Valid only for tokens with type TYPE_COMPOUND_PART.
537 int32_t getMatch() const {
538 U_ASSERT(getType() == TYPE_COMPOUND_PART);
539 return fMatch;
540 }
541
542 int32_t getInitialCompoundPart() const {
543 // Even if there is only one InitialCompoundPart value, we have this
544 // function for the simplicity of code consistency.
545 U_ASSERT(getType() == TYPE_INITIAL_COMPOUND_PART);
546 // Defensive: if this assert fails, code using this function also needs
547 // to change.
548 U_ASSERT(fMatch == INITIAL_COMPOUND_PART_PER);
549 return fMatch;
550 }
551
552 int8_t getPower() const {
553 U_ASSERT(getType() == TYPE_POWER_PART);
554 return static_cast<int8_t>(fMatch - kPowerPartOffset);
555 }
556
557 int32_t getSimpleUnitIndex() const {
558 U_ASSERT(getType() == TYPE_SIMPLE_UNIT);
559 return fMatch - kSimpleUnitOffset;
560 }
561
562 // TODO: Consider moving this to a separate utility class.
563 // Utility function to parse a string into an unsigned long value.
564 // The value must be a positive integer within the range [1, INT64_MAX].
565 // The input can be in integer or scientific notation.
566 static uint64_t parseStringToLong(const StringPiece strNum, UErrorCode &status) {
567 // We are processing well-formed input, so we don't need any special options to
568 // StringToDoubleConverter.
569 StringToDoubleConverter converter(0, 0, 0, "", "");
570 int32_t count;
571 double double_result = converter.StringToDouble(strNum.data(), strNum.length(), &count);
572 if (count != strNum.length()) {
573 status = kUnitIdentifierSyntaxError;
574 return 0;
575 }
576
577 if (U_FAILURE(status) || double_result < 1.0 || double_result > static_cast<double>(INT64_MAX)) {
578 status = kUnitIdentifierSyntaxError;
579 return 0;
580 }
581
582 // Check if the value is integer.
583 uint64_t int_result = static_cast<uint64_t>(double_result);
584 const double kTolerance = 1e-9;
585 if (abs(double_result - int_result) > kTolerance) {
586 status = kUnitIdentifierSyntaxError;
587 return 0;
588 }
589
590 return int_result;
591 }
592
593 private:
594 Token() = default;
595 int64_t fMatch;
596 Type fType = TYPE_UNDEFINED;
597 };
598
599 class Parser {
600 public:
601 /**
602 * Factory function for parsing the given identifier.
603 *
604 * @param source The identifier to parse. This function does not make a copy
605 * of source: the underlying string that source points at, must outlive the
606 * parser.
607 * @param status ICU error code.
608 */
609 static Parser from(StringPiece source, UErrorCode& status) {
610 if (U_FAILURE(status)) {
611 return {};
612 }
613 umtx_initOnce(gUnitExtrasInitOnce, &initUnitExtras, status);
614 if (U_FAILURE(status)) {
615 return {};
616 }
617 return {source};
618 }
619
620 /**
621 * A single unit or a constant denominator.
622 */
623 struct SingleUnitOrConstant {
624 enum ValueType {
625 kSingleUnit,
626 kConstantDenominator,
627 };
628
629 ValueType type = kSingleUnit;
630 SingleUnitImpl singleUnit;
631 uint64_t constantDenominator;
632
633 static SingleUnitOrConstant singleUnitValue(SingleUnitImpl singleUnit) {
634 SingleUnitOrConstant result;
635 result.type = kSingleUnit;
636 result.singleUnit = singleUnit;
637 result.constantDenominator = 0;
638 return result;
639 }
640
641 static SingleUnitOrConstant constantDenominatorValue(uint64_t constant) {
642 SingleUnitOrConstant result;
643 result.type = kConstantDenominator;
644 result.singleUnit = {};
645 result.constantDenominator = constant;
646 return result;
647 }
648
649 uint64_t getConstantDenominator() const {
650 U_ASSERT(type == kConstantDenominator);
651 return constantDenominator;
652 }
653
654 SingleUnitImpl getSingleUnit() const {
655 U_ASSERT(type == kSingleUnit);
656 return singleUnit;
657 }
658
659 bool isSingleUnit() const { return type == kSingleUnit; }
660
661 bool isConstantDenominator() const { return type == kConstantDenominator; }
662 };
663
664 MeasureUnitImpl parse(UErrorCode& status) {
665 MeasureUnitImpl result;
666
667 if (U_FAILURE(status)) {
668 return result;
669 }
670 if (fSource.empty()) {
671 // The dimenionless unit: nothing to parse. leave result as is.
672 return result;
673 }
674
675 while (hasNext()) {
676 bool sawAnd = false;
677
678 auto singleUnitOrConstant = nextSingleUnitOrConstant(sawAnd, status);
679 if (U_FAILURE(status)) {
680 return result;
681 }
682
683 if (singleUnitOrConstant.isConstantDenominator()) {
684 result.constantDenominator = singleUnitOrConstant.getConstantDenominator();
685 result.complexity = UMEASURE_UNIT_COMPOUND;
686 continue;
687 }
688
689 U_ASSERT(singleUnitOrConstant.isSingleUnit());
690 bool added = result.appendSingleUnit(singleUnitOrConstant.getSingleUnit(), status);
691 if (U_FAILURE(status)) {
692 return result;
693 }
694
695 if (sawAnd && !added) {
696 // Two similar units are not allowed in a mixed unit.
697 status = kUnitIdentifierSyntaxError;
698 return result;
699 }
700
701 if (result.singleUnits.length() >= 2) {
702 // nextSingleUnit fails appropriately for "per" and "and" in the
703 // same identifier. It doesn't fail for other compound units
704 // (COMPOUND_PART_TIMES). Consequently we take care of that
705 // here.
706 UMeasureUnitComplexity complexity =
707 sawAnd ? UMEASURE_UNIT_MIXED : UMEASURE_UNIT_COMPOUND;
708 if (result.singleUnits.length() == 2) {
709 // After appending two singleUnits, the complexity will be `UMEASURE_UNIT_COMPOUND`
710 U_ASSERT(result.complexity == UMEASURE_UNIT_COMPOUND);
711 result.complexity = complexity;
712 } else if (result.complexity != complexity) {
713 // Can't have mixed compound units
714 status = kUnitIdentifierSyntaxError;
715 return result;
716 }
717 }
718 }
719
720 if (result.singleUnits.length() == 0) {
721 // The identifier was empty or only had a constant denominator.
722 status = kUnitIdentifierSyntaxError;
723 return result; // add it for code consistency.
724 }
725
726 return result;
727 }
728
729 private:
730 // Tracks parser progress: the offset into fSource.
731 int32_t fIndex = 0;
732
733 // Since we're not owning this memory, whatever is passed to the constructor
734 // should live longer than this Parser - and the parser shouldn't return any
735 // references to that string.
736 StringPiece fSource;
737 BytesTrie fTrie;
738
739 // Set to true when we've seen a "-per-" or a "per-", after which all units
740 // are in the denominator. Until we find an "-and-", at which point the
741 // identifier is invalid pending TODO(CLDR-13701).
742 bool fAfterPer = false;
743
744 // Set to true when we've just seen a "per-". This is used to determine if
745 // the next token can be a constant denominator token.
746 bool fJustSawPer = false;
747
748 Parser() : fSource(""), fTrie(u"") {}
749
750 Parser(StringPiece source)
751 : fSource(source), fTrie(gSerializedUnitExtrasStemTrie) {}
752
753 inline bool hasNext() const {
754 return fIndex < fSource.length();
755 }
756
757 // Returns the next Token parsed from fSource, advancing fIndex to the end
758 // of that token in fSource. In case of U_FAILURE(status), the token
759 // returned will cause an abort if getType() is called on it.
760 Token nextToken(UErrorCode& status) {
761 fTrie.reset();
762 int32_t match = -1;
763 // Saves the position in the fSource string for the end of the most
764 // recent matching token.
765 int32_t previ = -1;
766
767 // Saves the position in the fSource string for later use in case of unit constant found.
768 int32_t currentFIndex = fIndex;
769
770 // Find the longest token that matches a value in the trie:
771 while (fIndex < fSource.length()) {
772 auto result = fTrie.next(fSource.data()[fIndex++]);
773 if (result == USTRINGTRIE_NO_MATCH) {
774 break;
775 } else if (result == USTRINGTRIE_NO_VALUE) {
776 continue;
777 }
778 U_ASSERT(USTRINGTRIE_HAS_VALUE(result));
779 match = fTrie.getValue();
780 previ = fIndex;
781 if (result == USTRINGTRIE_FINAL_VALUE) {
782 break;
783 }
784 U_ASSERT(result == USTRINGTRIE_INTERMEDIATE_VALUE);
785 // continue;
786 }
787
788 if (match >= 0) {
789 fIndex = previ;
790 return {match};
791 }
792
793 // If no match was found, we check if the token is a constant denominator.
794 // 1. We find the index of the start of the next token or the end of the string.
795 int32_t endOfConstantIndex = fSource.find("-", currentFIndex);
796 endOfConstantIndex = (endOfConstantIndex == -1) ? fSource.length() : endOfConstantIndex;
797 if (endOfConstantIndex <= currentFIndex) {
798 status = kUnitIdentifierSyntaxError;
799 return {match};
800 }
801
802 // 2. We extract the substring from the start of the constant to the end of the constant.
803 StringPiece constantDenominatorStr =
804 fSource.substr(currentFIndex, endOfConstantIndex - currentFIndex);
805 fIndex = endOfConstantIndex;
806 return Token::constantToken(constantDenominatorStr, status);
807 }
808
809 /**
810 * Returns the next "single unit" via result.
811 *
812 * If a "-per-" was parsed, the result will have appropriate negative
813 * dimensionality.
814 *
815 * Returns an error if we parse both compound units and "-and-", since mixed
816 * compound units are not yet supported - TODO(CLDR-13701).
817 *
818 * @param result Will be overwritten by the result, if status shows success.
819 * @param sawAnd If an "-and-" was parsed prior to finding the "single
820 * unit", sawAnd is set to true. If not, it is left as is.
821 * @param status ICU error code.
822 */
823 SingleUnitOrConstant nextSingleUnitOrConstant(bool &sawAnd, UErrorCode &status) {
824 SingleUnitImpl singleUnitResult;
825 if (U_FAILURE(status)) {
826 return {};
827 }
828
829 // state:
830 // 0 = no tokens seen yet (will accept power, SI or binary prefix, or simple unit)
831 // 1 = power token seen (will not accept another power token)
832 // 2 = SI or binary prefix token seen (will not accept a power, or SI or binary prefix token)
833 int32_t state = 0;
834
835 bool atStart = fIndex == 0;
836 Token token = nextToken(status);
837 if (U_FAILURE(status)) {
838 return {};
839 }
840
841 fJustSawPer = false;
842
843 if (atStart) {
844 // Identifiers optionally start with "per-".
845 if (token.getType() == Token::TYPE_INITIAL_COMPOUND_PART) {
846 U_ASSERT(token.getInitialCompoundPart() == INITIAL_COMPOUND_PART_PER);
847 fAfterPer = true;
848 fJustSawPer = true;
849 singleUnitResult.dimensionality = -1;
850
851 token = nextToken(status);
852 if (U_FAILURE(status)) {
853 return {};
854 }
855 }
856 } else {
857 // All other SingleUnit's are separated from previous SingleUnit's
858 // via a compound part:
859 if (token.getType() != Token::TYPE_COMPOUND_PART) {
860 status = kUnitIdentifierSyntaxError;
861 return {};
862 }
863
864 switch (token.getMatch()) {
865 case COMPOUND_PART_PER:
866 if (sawAnd) {
867 // Mixed compound units not yet supported,
868 // TODO(CLDR-13701).
869 status = kUnitIdentifierSyntaxError;
870 return {};
871 }
872 fAfterPer = true;
873 fJustSawPer = true;
874 singleUnitResult.dimensionality = -1;
875 break;
876
877 case COMPOUND_PART_TIMES:
878 if (fAfterPer) {
879 singleUnitResult.dimensionality = -1;
880 }
881 break;
882
883 case COMPOUND_PART_AND:
884 if (fAfterPer) {
885 // Can't start with "-and-", and mixed compound units
886 // not yet supported, TODO(CLDR-13701).
887 status = kUnitIdentifierSyntaxError;
888 return {};
889 }
890 sawAnd = true;
891 break;
892 }
893
894 token = nextToken(status);
895 if (U_FAILURE(status)) {
896 return {};
897 }
898 }
899
900 if (token.getType() == Token::TYPE_CONSTANT_DENOMINATOR) {
901 if (!fJustSawPer) {
902 status = kUnitIdentifierSyntaxError;
903 return {};
904 }
905
906 return SingleUnitOrConstant::constantDenominatorValue(token.getConstantDenominator());
907 }
908
909 // Read tokens until we have a complete SingleUnit or we reach the end.
910 while (true) {
911 switch (token.getType()) {
912 case Token::TYPE_POWER_PART:
913 if (state > 0) {
914 status = kUnitIdentifierSyntaxError;
915 return {};
916 }
917 singleUnitResult.dimensionality *= token.getPower();
918 state = 1;
919 break;
920
921 case Token::TYPE_PREFIX:
922 if (state > 1) {
923 status = kUnitIdentifierSyntaxError;
924 return {};
925 }
926 singleUnitResult.unitPrefix = token.getUnitPrefix();
927 state = 2;
928 break;
929
930 case Token::TYPE_SIMPLE_UNIT:
931 singleUnitResult.index = token.getSimpleUnitIndex();
932 break;
933
934 default:
935 status = kUnitIdentifierSyntaxError;
936 return {};
937 }
938
939 if (token.getType() == Token::TYPE_SIMPLE_UNIT) {
940 break;
941 }
942
943 if (!hasNext()) {
944 // We ran out of tokens before finding a complete single unit.
945 status = kUnitIdentifierSyntaxError;
946 return {};
947 }
948 token = nextToken(status);
949 if (U_FAILURE(status)) {
950 return {};
951 }
952 }
953
954 return SingleUnitOrConstant::singleUnitValue(singleUnitResult);
955 }
956 };
957
958 // Sorting function wrapping SingleUnitImpl::compareTo for use with uprv_sortArray.
959 int32_t U_CALLCONV
960 compareSingleUnits(const void* /*context*/, const void* left, const void* right) {
961 const auto* realLeft = static_cast<const SingleUnitImpl* const*>(left);
962 const auto* realRight = static_cast<const SingleUnitImpl* const*>(right);
963 return (*realLeft)->compareTo(**realRight);
964 }
965
966 // Returns an index into the gCategories array, for the "unitQuantity" (aka
967 // "type" or "category") associated with the given base unit identifier. Returns
968 // -1 on failure, together with U_UNSUPPORTED_ERROR.
969 int32_t getUnitCategoryIndex(BytesTrie &trie, StringPiece baseUnitIdentifier, UErrorCode &status) {
970 UStringTrieResult result = trie.reset().next(baseUnitIdentifier.data(), baseUnitIdentifier.length());
971 if (!USTRINGTRIE_HAS_VALUE(result)) {
972 status = U_UNSUPPORTED_ERROR;
973 return -1;
974 }
975
976 return trie.getValue();
977 }
978
979 } // namespace
980
981 U_CAPI int32_t U_EXPORT2
982 umeas_getPrefixPower(UMeasurePrefix unitPrefix) {
983 if (unitPrefix >= UMEASURE_PREFIX_INTERNAL_MIN_BIN &&
984 unitPrefix <= UMEASURE_PREFIX_INTERNAL_MAX_BIN) {
985 return unitPrefix - UMEASURE_PREFIX_INTERNAL_ONE_BIN;
986 }
987 U_ASSERT(unitPrefix >= UMEASURE_PREFIX_INTERNAL_MIN_SI &&
988 unitPrefix <= UMEASURE_PREFIX_INTERNAL_MAX_SI);
989 return unitPrefix - UMEASURE_PREFIX_ONE;
990 }
991
992 U_CAPI int32_t U_EXPORT2
993 umeas_getPrefixBase(UMeasurePrefix unitPrefix) {
994 if (unitPrefix >= UMEASURE_PREFIX_INTERNAL_MIN_BIN &&
995 unitPrefix <= UMEASURE_PREFIX_INTERNAL_MAX_BIN) {
996 return 1024;
997 }
998 U_ASSERT(unitPrefix >= UMEASURE_PREFIX_INTERNAL_MIN_SI &&
999 unitPrefix <= UMEASURE_PREFIX_INTERNAL_MAX_SI);
1000 return 10;
1001 }
1002
1003 CharString U_I18N_API getUnitQuantity(const MeasureUnitImpl &baseMeasureUnitImpl, UErrorCode &status) {
1004 CharString result;
1005 MeasureUnitImpl baseUnitImpl = baseMeasureUnitImpl.copy(status);
1006 UErrorCode localStatus = U_ZERO_ERROR;
1007 umtx_initOnce(gUnitExtrasInitOnce, &initUnitExtras, status);
1008 if (U_FAILURE(status)) {
1009 return result;
1010 }
1011 BytesTrie trie(gSerializedUnitCategoriesTrie);
1012
1013 baseUnitImpl.serialize(status);
1014 StringPiece identifier = baseUnitImpl.identifier.data();
1015 int32_t idx = getUnitCategoryIndex(trie, identifier, localStatus);
1016 if (U_FAILURE(status)) {
1017 return result;
1018 }
1019
1020 // In case the base unit identifier did not match any entry.
1021 if (U_FAILURE(localStatus)) {
1022 localStatus = U_ZERO_ERROR;
1023 baseUnitImpl.takeReciprocal(status);
1024 baseUnitImpl.serialize(status);
1025 identifier.set(baseUnitImpl.identifier.data());
1026 idx = getUnitCategoryIndex(trie, identifier, localStatus);
1027
1028 if (U_FAILURE(status)) {
1029 return result;
1030 }
1031 }
1032
1033 // In case the reciprocal of the base unit identifier did not match any entry.
1034 MeasureUnitImpl simplifiedUnit = baseMeasureUnitImpl.copyAndSimplify(status);
1035 if (U_FAILURE(status)) {
1036 return result;
1037 }
1038 if (U_FAILURE(localStatus)) {
1039 localStatus = U_ZERO_ERROR;
1040 simplifiedUnit.serialize(status);
1041 identifier.set(simplifiedUnit.identifier.data());
1042 idx = getUnitCategoryIndex(trie, identifier, localStatus);
1043
1044 if (U_FAILURE(status)) {
1045 return result;
1046 }
1047 }
1048
1049 // In case the simplified base unit identifier did not match any entry.
1050 if (U_FAILURE(localStatus)) {
1051 localStatus = U_ZERO_ERROR;
1052 simplifiedUnit.takeReciprocal(status);
1053 simplifiedUnit.serialize(status);
1054 identifier.set(simplifiedUnit.identifier.data());
1055 idx = getUnitCategoryIndex(trie, identifier, localStatus);
1056
1057 if (U_FAILURE(status)) {
1058 return result;
1059 }
1060 }
1061
1062 // If there is no match at all, throw an exception.
1063 if (U_FAILURE(localStatus)) {
1064 status = U_INVALID_FORMAT_ERROR;
1065 return result;
1066 }
1067
1068 if (idx < 0 || idx >= gCategoriesCount) {
1069 status = U_INVALID_FORMAT_ERROR;
1070 return result;
1071 }
1072
1073 result.appendInvariantChars(gCategories[idx], u_strlen(gCategories[idx]), status);
1074 return result;
1075 }
1076
1077 // In ICU4J, this is MeasureUnit.getSingleUnitImpl().
1078 SingleUnitImpl SingleUnitImpl::forMeasureUnit(const MeasureUnit& measureUnit, UErrorCode& status) {
1079 MeasureUnitImpl temp;
1080 const MeasureUnitImpl& impl = MeasureUnitImpl::forMeasureUnit(measureUnit, temp, status);
1081 if (U_FAILURE(status)) {
1082 return {};
1083 }
1084 if (impl.singleUnits.length() == 0) {
1085 return {};
1086 }
1087 if (impl.singleUnits.length() == 1) {
1088 return *impl.singleUnits[0];
1089 }
1090 status = U_ILLEGAL_ARGUMENT_ERROR;
1091 return {};
1092 }
1093
1094 MeasureUnit SingleUnitImpl::build(UErrorCode& status) const {
1095 MeasureUnitImpl temp;
1096 temp.appendSingleUnit(*this, status);
1097 // TODO(icu-units#28): the MeasureUnitImpl::build() method uses
1098 // findBySubtype, which is relatively slow.
1099 // - At the time of loading the simple unit IDs, we could also save a
1100 // mapping to the builtin MeasureUnit type and subtype they correspond to.
1101 // - This method could then check dimensionality and index, and if both are
1102 // 1, directly return MeasureUnit instances very quickly.
1103 return std::move(temp).build(status);
1104 }
1105
1106 const char *SingleUnitImpl::getSimpleUnitID() const {
1107 return gSimpleUnits[index];
1108 }
1109
1110 void SingleUnitImpl::appendNeutralIdentifier(CharString &result, UErrorCode &status) const UPRV_NO_SANITIZE_UNDEFINED {
1111 int32_t absPower = std::abs(this->dimensionality);
1112
1113 U_ASSERT(absPower > 0); // "this function does not support the dimensionless single units";
1114
1115 if (absPower == 1) {
1116 // no-op
1117 } else if (absPower == 2) {
1118 result.append(StringPiece("square-"), status);
1119 } else if (absPower == 3) {
1120 result.append(StringPiece("cubic-"), status);
1121 } else if (absPower <= 15) {
1122 result.append(StringPiece("pow"), status);
1123 result.appendNumber(absPower, status);
1124 result.append(StringPiece("-"), status);
1125 } else {
1126 status = U_ILLEGAL_ARGUMENT_ERROR; // Unit Identifier Syntax Error
1127 return;
1128 }
1129
1130 if (U_FAILURE(status)) {
1131 return;
1132 }
1133
1134 if (this->unitPrefix != UMEASURE_PREFIX_ONE) {
1135 bool found = false;
1136 for (const auto &unitPrefixInfo : gUnitPrefixStrings) {
1137 // TODO: consider using binary search? If we do this, add a unit
1138 // test to ensure gUnitPrefixStrings is sorted?
1139 if (unitPrefixInfo.value == this->unitPrefix) {
1140 result.append(unitPrefixInfo.string, status);
1141 found = true;
1142 break;
1143 }
1144 }
1145 if (!found) {
1146 status = U_UNSUPPORTED_ERROR;
1147 return;
1148 }
1149 }
1150
1151 result.append(StringPiece(this->getSimpleUnitID()), status);
1152 }
1153
1154 int32_t SingleUnitImpl::getUnitCategoryIndex() const {
1155 return gSimpleUnitCategories[index];
1156 }
1157
1158 MeasureUnitImpl::MeasureUnitImpl(const SingleUnitImpl &singleUnit, UErrorCode &status) {
1159 this->appendSingleUnit(singleUnit, status);
1160 }
1161
1162 MeasureUnitImpl MeasureUnitImpl::forIdentifier(StringPiece identifier, UErrorCode& status) {
1163 return Parser::from(identifier, status).parse(status);
1164 }
1165
1166 const MeasureUnitImpl& MeasureUnitImpl::forMeasureUnit(
1167 const MeasureUnit& measureUnit, MeasureUnitImpl& memory, UErrorCode& status) {
1168 if (measureUnit.fImpl) {
1169 return *measureUnit.fImpl;
1170 } else {
1171 memory = Parser::from(measureUnit.getIdentifier(), status).parse(status);
1172 return memory;
1173 }
1174 }
1175
1176 MeasureUnitImpl MeasureUnitImpl::forMeasureUnitMaybeCopy(
1177 const MeasureUnit& measureUnit, UErrorCode& status) {
1178 if (measureUnit.fImpl) {
1179 return measureUnit.fImpl->copy(status);
1180 } else {
1181 return Parser::from(measureUnit.getIdentifier(), status).parse(status);
1182 }
1183 }
1184
1185 void MeasureUnitImpl::takeReciprocal(UErrorCode& /*status*/) {
1186 identifier.clear();
1187 for (int32_t i = 0; i < singleUnits.length(); i++) {
1188 singleUnits[i]->dimensionality *= -1;
1189 }
1190 }
1191
1192 MeasureUnitImpl MeasureUnitImpl::copyAndSimplify(UErrorCode &status) const {
1193 MeasureUnitImpl result;
1194 for (int32_t i = 0; i < singleUnits.length(); i++) {
1195 const SingleUnitImpl &singleUnit = *this->singleUnits[i];
1196
1197 // The following `for` loop will cause time complexity to be O(n^2).
1198 // However, n is very small (number of units, generally, at maximum equal to 10)
1199 bool unitExist = false;
1200 for (int32_t j = 0; j < result.singleUnits.length(); j++) {
1201 if (uprv_strcmp(result.singleUnits[j]->getSimpleUnitID(), singleUnit.getSimpleUnitID()) ==
1202 0 &&
1203 result.singleUnits[j]->unitPrefix == singleUnit.unitPrefix) {
1204 unitExist = true;
1205 result.singleUnits[j]->dimensionality =
1206 result.singleUnits[j]->dimensionality + singleUnit.dimensionality;
1207 break;
1208 }
1209 }
1210
1211 if (!unitExist) {
1212 result.appendSingleUnit(singleUnit, status);
1213 }
1214 }
1215
1216 return result;
1217 }
1218
1219 bool MeasureUnitImpl::appendSingleUnit(const SingleUnitImpl &singleUnit, UErrorCode &status) {
1220 identifier.clear();
1221
1222 if (singleUnit.isDimensionless()) {
1223 // Do not append dimensionless units.
1224 return false;
1225 }
1226
1227 // Find a similar unit that already exists, to attempt to coalesce
1228 SingleUnitImpl *oldUnit = nullptr;
1229 for (int32_t i = 0; i < this->singleUnits.length(); i++) {
1230 auto *candidate = this->singleUnits[i];
1231 if (candidate->isCompatibleWith(singleUnit)) {
1232 oldUnit = candidate;
1233 }
1234 }
1235
1236 if (oldUnit) {
1237 // Both dimensionalities will be positive, or both will be negative, by
1238 // virtue of isCompatibleWith().
1239 oldUnit->dimensionality += singleUnit.dimensionality;
1240
1241 return false;
1242 }
1243
1244 // Add a copy of singleUnit
1245 // NOTE: MaybeStackVector::emplaceBackAndCheckErrorCode creates new copy of singleUnit.
1246 this->singleUnits.emplaceBackAndCheckErrorCode(status, singleUnit);
1247 if (U_FAILURE(status)) {
1248 return false;
1249 }
1250
1251 // If the MeasureUnitImpl is `UMEASURE_UNIT_SINGLE` and after the appending a unit, the `singleUnits`
1252 // contains more than one. thus means the complexity should be `UMEASURE_UNIT_COMPOUND`
1253 if (this->singleUnits.length() > 1 &&
1254 this->complexity == UMeasureUnitComplexity::UMEASURE_UNIT_SINGLE) {
1255 this->complexity = UMeasureUnitComplexity::UMEASURE_UNIT_COMPOUND;
1256 }
1257
1258 return true;
1259 }
1260
1261 MaybeStackVector<MeasureUnitImplWithIndex>
1262 MeasureUnitImpl::extractIndividualUnitsWithIndices(UErrorCode &status) const {
1263 MaybeStackVector<MeasureUnitImplWithIndex> result;
1264
1265 if (this->complexity != UMeasureUnitComplexity::UMEASURE_UNIT_MIXED) {
1266 result.emplaceBackAndCheckErrorCode(status, 0, *this, status);
1267 return result;
1268 }
1269
1270 for (int32_t i = 0; i < singleUnits.length(); ++i) {
1271 result.emplaceBackAndCheckErrorCode(status, i, *singleUnits[i], status);
1272 if (U_FAILURE(status)) {
1273 return result;
1274 }
1275 }
1276
1277 return result;
1278 }
1279
1280 int32_t countCharacter(const CharString &str, char c) {
1281 int32_t count = 0;
1282 for (int32_t i = 0, n = str.length(); i < n; i++) {
1283 if (str[i] == c) {
1284 count++;
1285 }
1286 }
1287 return count;
1288 }
1289
1290 /**
1291 * Internal function that returns a string of the constants in the correct
1292 * format.
1293 *
1294 * Example:
1295 * 1000 --> "-per-1000"
1296 * 1000000 --> "-per-1e6"
1297 *
1298 * NOTE: this function is only used when the constant denominator is greater
1299 * than 0.
1300 */
1301 CharString getConstantsString(uint64_t constantDenominator, UErrorCode &status) {
1302 U_ASSERT(constantDenominator > 0 && constantDenominator <= LLONG_MAX);
1303
1304 CharString result;
1305 result.appendNumber(constantDenominator, status);
1306 if (U_FAILURE(status)) {
1307 return result;
1308 }
1309
1310 if (constantDenominator <= 1000) {
1311 return result;
1312 }
1313
1314 // Check if the constant is a power of 10.
1315 int32_t zeros = countCharacter(result, '0');
1316 if (zeros == result.length() - 1 && result[0] == '1') {
1317 result.clear();
1318 result.append(StringPiece("1e"), status);
1319 result.appendNumber(zeros, status);
1320 }
1321
1322 return result;
1323 }
1324
1325 /**
1326 * Normalize a MeasureUnitImpl and generate the identifier string in place.
1327 */
1328 void MeasureUnitImpl::serialize(UErrorCode &status) {
1329 if (U_FAILURE(status)) {
1330 return;
1331 }
1332
1333 if (this->singleUnits.length() == 0 && this->constantDenominator == 0) {
1334 // Dimensionless, constructed by the default constructor.
1335 return;
1336 }
1337
1338 if (this->complexity == UMEASURE_UNIT_COMPOUND) {
1339 // Note: don't sort a MIXED unit
1340 uprv_sortArray(this->singleUnits.getAlias(), this->singleUnits.length(),
1341 sizeof(this->singleUnits[0]), compareSingleUnits, nullptr, false, &status);
1342 if (U_FAILURE(status)) {
1343 return;
1344 }
1345 }
1346
1347 CharString result;
1348 bool beforePer = true;
1349 bool firstTimeNegativeDimension = false;
1350 bool constantDenominatorAppended = false;
1351 for (int32_t i = 0; i < this->singleUnits.length(); i++) {
1352 if (beforePer && (*this->singleUnits[i]).dimensionality < 0) {
1353 beforePer = false;
1354 firstTimeNegativeDimension = true;
1355 } else if ((*this->singleUnits[i]).dimensionality < 0) {
1356 firstTimeNegativeDimension = false;
1357 }
1358
1359 if (U_FAILURE(status)) {
1360 return;
1361 }
1362
1363 if (this->complexity == UMeasureUnitComplexity::UMEASURE_UNIT_MIXED) {
1364 if (result.length() != 0) {
1365 result.append(StringPiece("-and-"), status);
1366 }
1367 } else {
1368 if (firstTimeNegativeDimension) {
1369 if (result.length() == 0) {
1370 result.append(StringPiece("per-"), status);
1371 } else {
1372 result.append(StringPiece("-per-"), status);
1373 }
1374
1375 if (this->constantDenominator > 0) {
1376 result.append(getConstantsString(this->constantDenominator, status), status);
1377 result.append(StringPiece("-"), status);
1378 constantDenominatorAppended = true;
1379 }
1380
1381 } else if (result.length() != 0) {
1382 result.append(StringPiece("-"), status);
1383 }
1384 }
1385
1386 this->singleUnits[i]->appendNeutralIdentifier(result, status);
1387 }
1388
1389 if (!constantDenominatorAppended && this->constantDenominator > 0) {
1390 result.append(StringPiece("-per-"), status);
1391 result.append(getConstantsString(this->constantDenominator, status), status);
1392 }
1393
1394 if (U_FAILURE(status)) {
1395 return;
1396 }
1397 this->identifier = CharString(result, status);
1398 }
1399
1400 MeasureUnit MeasureUnitImpl::build(UErrorCode &status) && {
1401 this->serialize(status);
1402 return MeasureUnit(std::move(*this));
1403 }
1404
1405 MeasureUnit MeasureUnit::forIdentifier(StringPiece identifier, UErrorCode &status) {
1406 return Parser::from(identifier, status).parse(status).build(status);
1407 }
1408
1409 UMeasureUnitComplexity MeasureUnit::getComplexity(UErrorCode &status) const {
1410 MeasureUnitImpl temp;
1411 return MeasureUnitImpl::forMeasureUnit(*this, temp, status).complexity;
1412 }
1413
1414 UMeasurePrefix MeasureUnit::getPrefix(UErrorCode &status) const {
1415 return SingleUnitImpl::forMeasureUnit(*this, status).unitPrefix;
1416 }
1417
1418 MeasureUnit MeasureUnit::withPrefix(UMeasurePrefix prefix,
1419 UErrorCode &status) const UPRV_NO_SANITIZE_UNDEFINED {
1420 SingleUnitImpl singleUnit = SingleUnitImpl::forMeasureUnit(*this, status);
1421 singleUnit.unitPrefix = prefix;
1422 return singleUnit.build(status);
1423 }
1424
1425 uint64_t MeasureUnit::getConstantDenominator(UErrorCode &status) const {
1426 auto complexity = this->getComplexity(status);
1427 if (U_FAILURE(status)) {
1428 return 0;
1429 }
1430
1431 if (complexity != UMEASURE_UNIT_SINGLE && complexity != UMEASURE_UNIT_COMPOUND) {
1432 status = U_ILLEGAL_ARGUMENT_ERROR;
1433 return 0;
1434 }
1435
1436 if (this->fImpl == nullptr) {
1437 return 0;
1438 }
1439
1440 return this->fImpl->constantDenominator;
1441 }
1442
1443 MeasureUnit MeasureUnit::withConstantDenominator(uint64_t denominator, UErrorCode &status) const {
1444 // To match the behavior of the Java API, we do not allow a constant denominator
1445 // bigger than LONG_MAX.
1446 if (denominator > LONG_MAX) {
1447 status = U_ILLEGAL_ARGUMENT_ERROR;
1448 return {};
1449 }
1450
1451 auto complexity = this->getComplexity(status);
1452 if (U_FAILURE(status)) {
1453 return {};
1454 }
1455 if (complexity != UMEASURE_UNIT_SINGLE && complexity != UMEASURE_UNIT_COMPOUND) {
1456 status = U_ILLEGAL_ARGUMENT_ERROR;
1457 return {};
1458 }
1459
1460 MeasureUnitImpl impl = MeasureUnitImpl::forMeasureUnitMaybeCopy(*this, status);
1461 if (U_FAILURE(status)) {
1462 return {};
1463 }
1464
1465 impl.constantDenominator = denominator;
1466 impl.complexity = (impl.singleUnits.length() < 2 && denominator == 0) ? UMEASURE_UNIT_SINGLE
1467 : UMEASURE_UNIT_COMPOUND;
1468 return std::move(impl).build(status);
1469 }
1470
1471 int32_t MeasureUnit::getDimensionality(UErrorCode& status) const {
1472 SingleUnitImpl singleUnit = SingleUnitImpl::forMeasureUnit(*this, status);
1473 if (U_FAILURE(status)) { return 0; }
1474 if (singleUnit.isDimensionless()) {
1475 return 0;
1476 }
1477 return singleUnit.dimensionality;
1478 }
1479
1480 MeasureUnit MeasureUnit::withDimensionality(int32_t dimensionality, UErrorCode& status) const {
1481 SingleUnitImpl singleUnit = SingleUnitImpl::forMeasureUnit(*this, status);
1482 singleUnit.dimensionality = dimensionality;
1483 return singleUnit.build(status);
1484 }
1485
1486 MeasureUnit MeasureUnit::reciprocal(UErrorCode& status) const {
1487 MeasureUnitImpl impl = MeasureUnitImpl::forMeasureUnitMaybeCopy(*this, status);
1488 // The reciprocal of a unit that has a constant denominator is not allowed.
1489 if (impl.constantDenominator != 0) {
1490 status = U_ILLEGAL_ARGUMENT_ERROR;
1491 return {};
1492 }
1493 impl.takeReciprocal(status);
1494 return std::move(impl).build(status);
1495 }
1496
1497 MeasureUnit MeasureUnit::product(const MeasureUnit& other, UErrorCode& status) const {
1498 MeasureUnitImpl impl = MeasureUnitImpl::forMeasureUnitMaybeCopy(*this, status);
1499 MeasureUnitImpl temp;
1500 const MeasureUnitImpl& otherImpl = MeasureUnitImpl::forMeasureUnit(other, temp, status);
1501 if (impl.complexity == UMEASURE_UNIT_MIXED || otherImpl.complexity == UMEASURE_UNIT_MIXED) {
1502 status = U_ILLEGAL_ARGUMENT_ERROR;
1503 return {};
1504 }
1505 for (int32_t i = 0; i < otherImpl.singleUnits.length(); i++) {
1506 impl.appendSingleUnit(*otherImpl.singleUnits[i], status);
1507 }
1508
1509 uint64_t currentConstatDenominator = this->getConstantDenominator(status);
1510 uint64_t otherConstantDenominator = other.getConstantDenominator(status);
1511
1512 // TODO: we can also multiply the constant denominators instead of returning an error.
1513 if (currentConstatDenominator != 0 && otherConstantDenominator != 0) {
1514 // There is only `one` constant denominator in a compound unit.
1515 // Therefore, we Cannot multiply units that both of them have a constant denominator
1516 status = U_ILLEGAL_ARGUMENT_ERROR;
1517 return {};
1518 }
1519
1520 // Because either one of the constant denominators is zero, we can use the maximum of them.
1521 impl.constantDenominator = uprv_max(currentConstatDenominator, otherConstantDenominator);
1522
1523 if (impl.singleUnits.length() > 1 || impl.constantDenominator > 0) {
1524 impl.complexity = UMEASURE_UNIT_COMPOUND;
1525 }
1526
1527 return std::move(impl).build(status);
1528 }
1529
1530 LocalArray<MeasureUnit> MeasureUnit::splitToSingleUnitsImpl(int32_t& outCount, UErrorCode& status) const {
1531 MeasureUnitImpl temp;
1532 const MeasureUnitImpl& impl = MeasureUnitImpl::forMeasureUnit(*this, temp, status);
1533 outCount = impl.singleUnits.length();
1534 MeasureUnit* arr = new MeasureUnit[outCount];
1535 if (arr == nullptr) {
1536 status = U_MEMORY_ALLOCATION_ERROR;
1537 return LocalArray<MeasureUnit>();
1538 }
1539 for (int32_t i = 0; i < outCount; i++) {
1540 arr[i] = impl.singleUnits[i]->build(status);
1541 }
1542 return LocalArray<MeasureUnit>(arr, status);
1543 }
1544
1545
1546 U_NAMESPACE_END
1547
1548 #endif /* !UNCONFIG_NO_FORMATTING */