Debian Codegraph @

extra/icu/icu-release-77-1/source/i18n/measunit_extra.cpp

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