1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 **********************************************************************
5 * Copyright (c) 2004-2016, International Business Machines
6 * Corporation and others. All Rights Reserved.
7 **********************************************************************
8 * Author: Alan Liu
9 * Created: April 20, 2004
10 * Since: ICU 3.0
11 **********************************************************************
12 */
13 #include "utypeinfo.h" // for 'typeid' to work
14 #include "unicode/utypes.h"
15
16 #if !UCONFIG_NO_FORMATTING
17
18 #include "unicode/measfmt.h"
19 #include "unicode/numfmt.h"
20 #include "currfmt.h"
21 #include "unicode/localpointer.h"
22 #include "resource.h"
23 #include "unicode/simpleformatter.h"
24 #include "quantityformatter.h"
25 #include "unicode/plurrule.h"
26 #include "unicode/decimfmt.h"
27 #include "uresimp.h"
28 #include "unicode/ures.h"
29 #include "unicode/ustring.h"
30 #include "ureslocs.h"
31 #include "cstring.h"
32 #include "mutex.h"
33 #include "ucln_in.h"
34 #include "unicode/listformatter.h"
35 #include "charstr.h"
36 #include "unicode/putil.h"
37 #include "unicode/smpdtfmt.h"
38 #include "uassert.h"
39 #include "unicode/numberformatter.h"
40 #include "number_longnames.h"
41 #include "number_utypes.h"
42
43 #include "sharednumberformat.h"
44 #include "sharedpluralrules.h"
45 #include "standardplural.h"
46 #include "unifiedcache.h"
47
48
49 U_NAMESPACE_BEGIN
50
51 using number::impl::UFormattedNumberData;
52
53 static constexpr int32_t WIDTH_INDEX_COUNT = UMEASFMT_WIDTH_NARROW + 1;
54
55 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(MeasureFormat)
56
57 // Used to format durations like 5:47 or 21:35:42.
58 class NumericDateFormatters : public UMemory {
59 public:
60 // Formats like H:mm
61 UnicodeString hourMinute;
62
63 // formats like M:ss
64 UnicodeString minuteSecond;
65
66 // formats like H:mm:ss
67 UnicodeString hourMinuteSecond;
68
69 // Constructor that takes the actual patterns for hour-minute,
70 // minute-second, and hour-minute-second respectively.
NumericDateFormatters(const UnicodeString & hm,const UnicodeString & ms,const UnicodeString & hms)71 NumericDateFormatters(
72 const UnicodeString &hm,
73 const UnicodeString &ms,
74 const UnicodeString &hms) :
75 hourMinute(hm),
76 minuteSecond(ms),
77 hourMinuteSecond(hms) {
78 }
79 private:
80 NumericDateFormatters(const NumericDateFormatters &other);
81 NumericDateFormatters &operator=(const NumericDateFormatters &other);
82 };
83
getRegularWidth(UMeasureFormatWidth width)84 static UMeasureFormatWidth getRegularWidth(UMeasureFormatWidth width) {
85 if (width >= WIDTH_INDEX_COUNT) {
86 return UMEASFMT_WIDTH_NARROW;
87 }
88 return width;
89 }
90
getUnitWidth(UMeasureFormatWidth width)91 static UNumberUnitWidth getUnitWidth(UMeasureFormatWidth width) {
92 switch (width) {
93 case UMEASFMT_WIDTH_WIDE:
94 return UNUM_UNIT_WIDTH_FULL_NAME;
95 case UMEASFMT_WIDTH_NARROW:
96 case UMEASFMT_WIDTH_NUMERIC:
97 return UNUM_UNIT_WIDTH_NARROW;
98 case UMEASFMT_WIDTH_SHORT:
99 default:
100 return UNUM_UNIT_WIDTH_SHORT;
101 }
102 }
103
104 /**
105 * Instances contain all MeasureFormat specific data for a particular locale.
106 * This data is cached. It is never copied, but is shared via shared pointers.
107 *
108 * Note: We might change the cache data to have an array[WIDTH_INDEX_COUNT] of
109 * complete sets of unit & per patterns,
110 * to correspond to the resource data and its aliases.
111 *
112 * TODO: Maybe store more sparsely in general, with pointers rather than potentially-empty objects.
113 */
114 class MeasureFormatCacheData : public SharedObject {
115 public:
116
117 /**
118 * Redirection data from root-bundle, top-level sideways aliases.
119 * - UMEASFMT_WIDTH_COUNT: initial value, just fall back to root
120 * - UMEASFMT_WIDTH_WIDE/SHORT/NARROW: sideways alias for missing data
121 */
122 UMeasureFormatWidth widthFallback[WIDTH_INDEX_COUNT];
123
124 MeasureFormatCacheData();
125 virtual ~MeasureFormatCacheData();
126
adoptCurrencyFormat(int32_t widthIndex,NumberFormat * nfToAdopt)127 void adoptCurrencyFormat(int32_t widthIndex, NumberFormat *nfToAdopt) {
128 delete currencyFormats[widthIndex];
129 currencyFormats[widthIndex] = nfToAdopt;
130 }
getCurrencyFormat(UMeasureFormatWidth width) const131 const NumberFormat *getCurrencyFormat(UMeasureFormatWidth width) const {
132 return currencyFormats[getRegularWidth(width)];
133 }
adoptIntegerFormat(NumberFormat * nfToAdopt)134 void adoptIntegerFormat(NumberFormat *nfToAdopt) {
135 delete integerFormat;
136 integerFormat = nfToAdopt;
137 }
getIntegerFormat() const138 const NumberFormat *getIntegerFormat() const {
139 return integerFormat;
140 }
adoptNumericDateFormatters(NumericDateFormatters * formattersToAdopt)141 void adoptNumericDateFormatters(NumericDateFormatters *formattersToAdopt) {
142 delete numericDateFormatters;
143 numericDateFormatters = formattersToAdopt;
144 }
getNumericDateFormatters() const145 const NumericDateFormatters *getNumericDateFormatters() const {
146 return numericDateFormatters;
147 }
148
149 private:
150 NumberFormat* currencyFormats[WIDTH_INDEX_COUNT];
151 NumberFormat* integerFormat;
152 NumericDateFormatters* numericDateFormatters;
153
154 MeasureFormatCacheData(const MeasureFormatCacheData &other);
155 MeasureFormatCacheData &operator=(const MeasureFormatCacheData &other);
156 };
157
MeasureFormatCacheData()158 MeasureFormatCacheData::MeasureFormatCacheData()
159 : integerFormat(nullptr), numericDateFormatters(nullptr) {
160 for (int32_t i = 0; i < WIDTH_INDEX_COUNT; ++i) {
161 widthFallback[i] = UMEASFMT_WIDTH_COUNT;
162 }
163 memset(currencyFormats, 0, sizeof(currencyFormats));
164 }
165
~MeasureFormatCacheData()166 MeasureFormatCacheData::~MeasureFormatCacheData() {
167 for (int32_t i = 0; i < UPRV_LENGTHOF(currencyFormats); ++i) {
168 delete currencyFormats[i];
169 }
170 // Note: the contents of 'dnams' are pointers into the resource bundle
171 delete integerFormat;
172 delete numericDateFormatters;
173 }
174
isCurrency(const MeasureUnit & unit)175 static UBool isCurrency(const MeasureUnit &unit) {
176 return (uprv_strcmp(unit.getType(), "currency") == 0);
177 }
178
getString(const UResourceBundle * resource,UnicodeString & result,UErrorCode & status)179 static UBool getString(
180 const UResourceBundle *resource,
181 UnicodeString &result,
182 UErrorCode &status) {
183 int32_t len = 0;
184 const char16_t *resStr = ures_getString(resource, &len, &status);
185 if (U_FAILURE(status)) {
186 return false;
187 }
188 result.setTo(true, resStr, len);
189 return true;
190 }
191
loadNumericDateFormatterPattern(const UResourceBundle * resource,const char * pattern,UErrorCode & status)192 static UnicodeString loadNumericDateFormatterPattern(
193 const UResourceBundle *resource,
194 const char *pattern,
195 UErrorCode &status) {
196 UnicodeString result;
197 if (U_FAILURE(status)) {
198 return result;
199 }
200 CharString chs;
201 chs.append("durationUnits", status)
202 .append("/", status).append(pattern, status);
203 LocalUResourceBundlePointer patternBundle(
204 ures_getByKeyWithFallback(
205 resource,
206 chs.data(),
207 nullptr,
208 &status));
209 if (U_FAILURE(status)) {
210 return result;
211 }
212 getString(patternBundle.getAlias(), result, status);
213 // Replace 'h' with 'H'
214 int32_t len = result.length();
215 char16_t *buffer = result.getBuffer(len);
216 for (int32_t i = 0; i < len; ++i) {
217 if (buffer[i] == 0x68) { // 'h'
218 buffer[i] = 0x48; // 'H'
219 }
220 }
221 result.releaseBuffer(len);
222 return result;
223 }
224
loadNumericDateFormatters(const UResourceBundle * resource,UErrorCode & status)225 static NumericDateFormatters *loadNumericDateFormatters(
226 const UResourceBundle *resource,
227 UErrorCode &status) {
228 if (U_FAILURE(status)) {
229 return nullptr;
230 }
231 NumericDateFormatters *result = new NumericDateFormatters(
232 loadNumericDateFormatterPattern(resource, "hm", status),
233 loadNumericDateFormatterPattern(resource, "ms", status),
234 loadNumericDateFormatterPattern(resource, "hms", status));
235 if (U_FAILURE(status)) {
236 delete result;
237 return nullptr;
238 }
239 return result;
240 }
241
242 template<>
createObject(const void *,UErrorCode & status) const243 const MeasureFormatCacheData *LocaleCacheKey<MeasureFormatCacheData>::createObject(
244 const void * /*unused*/, UErrorCode &status) const {
245 const char *localeId = fLoc.getName();
246 LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_UNIT, localeId, &status));
247 static UNumberFormatStyle currencyStyles[] = {
248 UNUM_CURRENCY_PLURAL, UNUM_CURRENCY_ISO, UNUM_CURRENCY};
249 LocalPointer<MeasureFormatCacheData> result(new MeasureFormatCacheData(), status);
250 if (U_FAILURE(status)) {
251 return nullptr;
252 }
253 result->adoptNumericDateFormatters(loadNumericDateFormatters(
254 unitsBundle.getAlias(), status));
255 if (U_FAILURE(status)) {
256 return nullptr;
257 }
258
259 for (int32_t i = 0; i < WIDTH_INDEX_COUNT; ++i) {
260 // NumberFormat::createInstance can erase warning codes from status, so pass it
261 // a separate status instance
262 UErrorCode localStatus = U_ZERO_ERROR;
263 result->adoptCurrencyFormat(i, NumberFormat::createInstance(
264 localeId, currencyStyles[i], localStatus));
265 if (localStatus != U_ZERO_ERROR) {
266 status = localStatus;
267 }
268 if (U_FAILURE(status)) {
269 return nullptr;
270 }
271 }
272 NumberFormat *inf = NumberFormat::createInstance(
273 localeId, UNUM_DECIMAL, status);
274 if (U_FAILURE(status)) {
275 return nullptr;
276 }
277 inf->setMaximumFractionDigits(0);
278 DecimalFormat *decfmt = dynamic_cast<DecimalFormat *>(inf);
279 if (decfmt != nullptr) {
280 decfmt->setRoundingMode(DecimalFormat::kRoundDown);
281 }
282 result->adoptIntegerFormat(inf);
283 result->addRef();
284 return result.orphan();
285 }
286
isTimeUnit(const MeasureUnit & mu,const char * tu)287 static UBool isTimeUnit(const MeasureUnit &mu, const char *tu) {
288 return uprv_strcmp(mu.getType(), "duration") == 0 &&
289 uprv_strcmp(mu.getSubtype(), tu) == 0;
290 }
291
292 // Converts a composite measure into hours-minutes-seconds and stores at hms
293 // array. [0] is hours; [1] is minutes; [2] is seconds. Returns a bit map of
294 // units found: 1=hours, 2=minutes, 4=seconds. For example, if measures
295 // contains hours-minutes, this function would return 3.
296 //
297 // If measures cannot be converted into hours, minutes, seconds or if amounts
298 // are negative, or if hours, minutes, seconds are out of order, returns 0.
toHMS(const Measure * measures,int32_t measureCount,Formattable * hms,UErrorCode & status)299 static int32_t toHMS(
300 const Measure *measures,
301 int32_t measureCount,
302 Formattable *hms,
303 UErrorCode &status) {
304 if (U_FAILURE(status)) {
305 return 0;
306 }
307 int32_t result = 0;
308 if (U_FAILURE(status)) {
309 return 0;
310 }
311 // We use copy constructor to ensure that both sides of equality operator
312 // are instances of MeasureUnit base class and not a subclass. Otherwise,
313 // operator== will immediately return false.
314 for (int32_t i = 0; i < measureCount; ++i) {
315 if (isTimeUnit(measures[i].getUnit(), "hour")) {
316 // hour must come first
317 if (result >= 1) {
318 return 0;
319 }
320 hms[0] = measures[i].getNumber();
321 if (hms[0].getDouble() < 0.0) {
322 return 0;
323 }
324 result |= 1;
325 } else if (isTimeUnit(measures[i].getUnit(), "minute")) {
326 // minute must come after hour
327 if (result >= 2) {
328 return 0;
329 }
330 hms[1] = measures[i].getNumber();
331 if (hms[1].getDouble() < 0.0) {
332 return 0;
333 }
334 result |= 2;
335 } else if (isTimeUnit(measures[i].getUnit(), "second")) {
336 // second must come after hour and minute
337 if (result >= 4) {
338 return 0;
339 }
340 hms[2] = measures[i].getNumber();
341 if (hms[2].getDouble() < 0.0) {
342 return 0;
343 }
344 result |= 4;
345 } else {
346 return 0;
347 }
348 }
349 return result;
350 }
351
352
MeasureFormat(const Locale & locale,UMeasureFormatWidth w,UErrorCode & status)353 MeasureFormat::MeasureFormat(
354 const Locale &locale, UMeasureFormatWidth w, UErrorCode &status)
355 : cache(nullptr),
356 numberFormat(nullptr),
357 pluralRules(nullptr),
358 fWidth(w),
359 listFormatter(nullptr) {
360 initMeasureFormat(locale, w, nullptr, status);
361 }
362
MeasureFormat(const Locale & locale,UMeasureFormatWidth w,NumberFormat * nfToAdopt,UErrorCode & status)363 MeasureFormat::MeasureFormat(
364 const Locale &locale,
365 UMeasureFormatWidth w,
366 NumberFormat *nfToAdopt,
367 UErrorCode &status)
368 : cache(nullptr),
369 numberFormat(nullptr),
370 pluralRules(nullptr),
371 fWidth(w),
372 listFormatter(nullptr) {
373 initMeasureFormat(locale, w, nfToAdopt, status);
374 }
375
MeasureFormat(const MeasureFormat & other)376 MeasureFormat::MeasureFormat(const MeasureFormat &other) :
377 Format(other),
378 cache(other.cache),
379 numberFormat(other.numberFormat),
380 pluralRules(other.pluralRules),
381 fWidth(other.fWidth),
382 listFormatter(nullptr) {
383 cache->addRef();
384 numberFormat->addRef();
385 pluralRules->addRef();
386 if (other.listFormatter != nullptr) {
387 listFormatter = new ListFormatter(*other.listFormatter);
388 }
389 }
390
operator =(const MeasureFormat & other)391 MeasureFormat &MeasureFormat::operator=(const MeasureFormat &other) {
392 if (this == &other) {
393 return *this;
394 }
395 Format::operator=(other);
396 SharedObject::copyPtr(other.cache, cache);
397 SharedObject::copyPtr(other.numberFormat, numberFormat);
398 SharedObject::copyPtr(other.pluralRules, pluralRules);
399 fWidth = other.fWidth;
400 delete listFormatter;
401 if (other.listFormatter != nullptr) {
402 listFormatter = new ListFormatter(*other.listFormatter);
403 } else {
404 listFormatter = nullptr;
405 }
406 return *this;
407 }
408
MeasureFormat()409 MeasureFormat::MeasureFormat() :
410 cache(nullptr),
411 numberFormat(nullptr),
412 pluralRules(nullptr),
413 fWidth(UMEASFMT_WIDTH_SHORT),
414 listFormatter(nullptr) {
415 }
416
~MeasureFormat()417 MeasureFormat::~MeasureFormat() {
418 if (cache != nullptr) {
419 cache->removeRef();
420 }
421 if (numberFormat != nullptr) {
422 numberFormat->removeRef();
423 }
424 if (pluralRules != nullptr) {
425 pluralRules->removeRef();
426 }
427 delete listFormatter;
428 }
429
operator ==(const Format & other) const430 bool MeasureFormat::operator==(const Format &other) const {
431 if (this == &other) { // Same object, equal
432 return true;
433 }
434 if (!Format::operator==(other)) {
435 return false;
436 }
437 const MeasureFormat &rhs = static_cast<const MeasureFormat &>(other);
438
439 // Note: Since the ListFormatter depends only on Locale and width, we
440 // don't have to check it here.
441
442 // differing widths aren't equivalent
443 if (fWidth != rhs.fWidth) {
444 return false;
445 }
446 // Width the same check locales.
447 // We don't need to check locales if both objects have same cache.
448 if (cache != rhs.cache) {
449 UErrorCode status = U_ZERO_ERROR;
450 const char *localeId = getLocaleID(status);
451 const char *rhsLocaleId = rhs.getLocaleID(status);
452 if (U_FAILURE(status)) {
453 // On failure, assume not equal
454 return false;
455 }
456 if (uprv_strcmp(localeId, rhsLocaleId) != 0) {
457 return false;
458 }
459 }
460 // Locales same, check NumberFormat if shared data differs.
461 return (
462 numberFormat == rhs.numberFormat ||
463 **numberFormat == **rhs.numberFormat);
464 }
465
clone() const466 MeasureFormat *MeasureFormat::clone() const {
467 return new MeasureFormat(*this);
468 }
469
format(const Formattable & obj,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const470 UnicodeString &MeasureFormat::format(
471 const Formattable &obj,
472 UnicodeString &appendTo,
473 FieldPosition &pos,
474 UErrorCode &status) const {
475 if (U_FAILURE(status)) return appendTo;
476 if (obj.getType() == Formattable::kObject) {
477 const UObject* formatObj = obj.getObject();
478 const Measure* amount = dynamic_cast<const Measure*>(formatObj);
479 if (amount != nullptr) {
480 return formatMeasure(
481 *amount, **numberFormat, appendTo, pos, status);
482 }
483 }
484 status = U_ILLEGAL_ARGUMENT_ERROR;
485 return appendTo;
486 }
487
parseObject(const UnicodeString &,Formattable &,ParsePosition &) const488 void MeasureFormat::parseObject(
489 const UnicodeString & /*source*/,
490 Formattable & /*result*/,
491 ParsePosition& /*pos*/) const {
492 return;
493 }
494
formatMeasurePerUnit(const Measure & measure,const MeasureUnit & perUnit,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const495 UnicodeString &MeasureFormat::formatMeasurePerUnit(
496 const Measure &measure,
497 const MeasureUnit &perUnit,
498 UnicodeString &appendTo,
499 FieldPosition &pos,
500 UErrorCode &status) const {
501 if (U_FAILURE(status)) {
502 return appendTo;
503 }
504 auto* df = dynamic_cast<const DecimalFormat*>(&getNumberFormatInternal());
505 if (df == nullptr) {
506 // Don't know how to handle other types of NumberFormat
507 status = U_UNSUPPORTED_ERROR;
508 return appendTo;
509 }
510 UFormattedNumberData result;
511 if (auto* lnf = df->toNumberFormatter(status)) {
512 result.quantity.setToDouble(measure.getNumber().getDouble(status));
513 lnf->unit(measure.getUnit())
514 .perUnit(perUnit)
515 .unitWidth(getUnitWidth(fWidth))
516 .formatImpl(&result, status);
517 }
518 DecimalFormat::fieldPositionHelper(result, pos, appendTo.length(), status);
519 appendTo.append(result.toTempString(status));
520 return appendTo;
521 }
522
formatMeasures(const Measure * measures,int32_t measureCount,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const523 UnicodeString &MeasureFormat::formatMeasures(
524 const Measure *measures,
525 int32_t measureCount,
526 UnicodeString &appendTo,
527 FieldPosition &pos,
528 UErrorCode &status) const {
529 if (U_FAILURE(status)) {
530 return appendTo;
531 }
532 if (measureCount == 0) {
533 return appendTo;
534 }
535 if (measureCount == 1) {
536 return formatMeasure(measures[0], **numberFormat, appendTo, pos, status);
537 }
538 if (fWidth == UMEASFMT_WIDTH_NUMERIC) {
539 Formattable hms[3];
540 int32_t bitMap = toHMS(measures, measureCount, hms, status);
541 if (bitMap > 0) {
542 return formatNumeric(hms, bitMap, appendTo, status);
543 }
544 }
545 if (pos.getField() != FieldPosition::DONT_CARE) {
546 return formatMeasuresSlowTrack(
547 measures, measureCount, appendTo, pos, status);
548 }
549 UnicodeString *results = new UnicodeString[measureCount];
550 if (results == nullptr) {
551 status = U_MEMORY_ALLOCATION_ERROR;
552 return appendTo;
553 }
554 for (int32_t i = 0; i < measureCount; ++i) {
555 const NumberFormat *nf = cache->getIntegerFormat();
556 if (i == measureCount - 1) {
557 nf = numberFormat->get();
558 }
559 formatMeasure(
560 measures[i],
561 *nf,
562 results[i],
563 pos,
564 status);
565 }
566 listFormatter->format(results, measureCount, appendTo, status);
567 delete [] results;
568 return appendTo;
569 }
570
getUnitDisplayName(const MeasureUnit & unit,UErrorCode & status) const571 UnicodeString MeasureFormat::getUnitDisplayName(const MeasureUnit& unit, UErrorCode& status) const {
572 return number::impl::LongNameHandler::getUnitDisplayName(
573 getLocale(status),
574 unit,
575 getUnitWidth(fWidth),
576 status);
577 }
578
initMeasureFormat(const Locale & locale,UMeasureFormatWidth w,NumberFormat * nfToAdopt,UErrorCode & status)579 void MeasureFormat::initMeasureFormat(
580 const Locale &locale,
581 UMeasureFormatWidth w,
582 NumberFormat *nfToAdopt,
583 UErrorCode &status) {
584 static const UListFormatterWidth listWidths[] = {
585 ULISTFMT_WIDTH_WIDE,
586 ULISTFMT_WIDTH_SHORT,
587 ULISTFMT_WIDTH_NARROW};
588 LocalPointer<NumberFormat> nf(nfToAdopt);
589 if (U_FAILURE(status)) {
590 return;
591 }
592 const char *name = locale.getName();
593 setLocaleIDs(name, name);
594
595 UnifiedCache::getByLocale(locale, cache, status);
596 if (U_FAILURE(status)) {
597 return;
598 }
599
600 const SharedPluralRules *pr = PluralRules::createSharedInstance(
601 locale, UPLURAL_TYPE_CARDINAL, status);
602 if (U_FAILURE(status)) {
603 return;
604 }
605 SharedObject::copyPtr(pr, pluralRules);
606 pr->removeRef();
607 if (nf.isNull()) {
608 // TODO: Clean this up
609 const SharedNumberFormat *shared = NumberFormat::createSharedInstance(
610 locale, UNUM_DECIMAL, status);
611 if (U_FAILURE(status)) {
612 return;
613 }
614 SharedObject::copyPtr(shared, numberFormat);
615 shared->removeRef();
616 } else {
617 adoptNumberFormat(nf.orphan(), status);
618 if (U_FAILURE(status)) {
619 return;
620 }
621 }
622 fWidth = w;
623 delete listFormatter;
624 listFormatter = ListFormatter::createInstance(
625 locale,
626 ULISTFMT_TYPE_UNITS,
627 listWidths[getRegularWidth(fWidth)],
628 status);
629 }
630
adoptNumberFormat(NumberFormat * nfToAdopt,UErrorCode & status)631 void MeasureFormat::adoptNumberFormat(
632 NumberFormat *nfToAdopt, UErrorCode &status) {
633 LocalPointer<NumberFormat> nf(nfToAdopt);
634 if (U_FAILURE(status)) {
635 return;
636 }
637 SharedNumberFormat *shared = new SharedNumberFormat(nf.getAlias());
638 if (shared == nullptr) {
639 status = U_MEMORY_ALLOCATION_ERROR;
640 return;
641 }
642 nf.orphan();
643 SharedObject::copyPtr(shared, numberFormat);
644 }
645
setMeasureFormatLocale(const Locale & locale,UErrorCode & status)646 UBool MeasureFormat::setMeasureFormatLocale(const Locale &locale, UErrorCode &status) {
647 if (U_FAILURE(status) || locale == getLocale(status)) {
648 return false;
649 }
650 initMeasureFormat(locale, fWidth, nullptr, status);
651 return U_SUCCESS(status);
652 }
653
getNumberFormatInternal() const654 const NumberFormat &MeasureFormat::getNumberFormatInternal() const {
655 return **numberFormat;
656 }
657
getCurrencyFormatInternal() const658 const NumberFormat &MeasureFormat::getCurrencyFormatInternal() const {
659 return *cache->getCurrencyFormat(UMEASFMT_WIDTH_NARROW);
660 }
661
getPluralRules() const662 const PluralRules &MeasureFormat::getPluralRules() const {
663 return **pluralRules;
664 }
665
getLocale(UErrorCode & status) const666 Locale MeasureFormat::getLocale(UErrorCode &status) const {
667 return Format::getLocale(ULOC_VALID_LOCALE, status);
668 }
669
getLocaleID(UErrorCode & status) const670 const char *MeasureFormat::getLocaleID(UErrorCode &status) const {
671 return Format::getLocaleID(ULOC_VALID_LOCALE, status);
672 }
673
formatMeasure(const Measure & measure,const NumberFormat & nf,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const674 UnicodeString &MeasureFormat::formatMeasure(
675 const Measure &measure,
676 const NumberFormat &nf,
677 UnicodeString &appendTo,
678 FieldPosition &pos,
679 UErrorCode &status) const {
680 if (U_FAILURE(status)) {
681 return appendTo;
682 }
683 const Formattable& amtNumber = measure.getNumber();
684 const MeasureUnit& amtUnit = measure.getUnit();
685 if (isCurrency(amtUnit)) {
686 char16_t isoCode[4];
687 u_charsToUChars(amtUnit.getSubtype(), isoCode, 4);
688 return cache->getCurrencyFormat(fWidth)->format(
689 new CurrencyAmount(amtNumber, isoCode, status),
690 appendTo,
691 pos,
692 status);
693 }
694 auto* df = dynamic_cast<const DecimalFormat*>(&nf);
695 if (df == nullptr) {
696 // Handle other types of NumberFormat using the ICU 63 code, modified to
697 // get the unitPattern from LongNameHandler and handle fallback to OTHER.
698 UnicodeString formattedNumber;
699 StandardPlural::Form pluralForm = QuantityFormatter::selectPlural(
700 amtNumber, nf, **pluralRules, formattedNumber, pos, status);
701 UnicodeString pattern = number::impl::LongNameHandler::getUnitPattern(getLocale(status),
702 amtUnit, getUnitWidth(fWidth), pluralForm, status);
703 // The above handles fallback from other widths to short, and from other plural forms to OTHER
704 if (U_FAILURE(status)) {
705 return appendTo;
706 }
707 SimpleFormatter formatter(pattern, 0, 1, status);
708 return QuantityFormatter::format(formatter, formattedNumber, appendTo, pos, status);
709 }
710 UFormattedNumberData result;
711 if (auto* lnf = df->toNumberFormatter(status)) {
712 result.quantity.setToDouble(amtNumber.getDouble(status));
713 lnf->unit(amtUnit)
714 .unitWidth(getUnitWidth(fWidth))
715 .formatImpl(&result, status);
716 }
717 DecimalFormat::fieldPositionHelper(result, pos, appendTo.length(), status);
718 appendTo.append(result.toTempString(status));
719 return appendTo;
720 }
721
722
723 // Formats numeric time duration as 5:00:47 or 3:54.
formatNumeric(const Formattable * hms,int32_t bitMap,UnicodeString & appendTo,UErrorCode & status) const724 UnicodeString &MeasureFormat::formatNumeric(
725 const Formattable *hms, // always length 3
726 int32_t bitMap, // 1=hour set, 2=minute set, 4=second set
727 UnicodeString &appendTo,
728 UErrorCode &status) const {
729 if (U_FAILURE(status)) {
730 return appendTo;
731 }
732
733 UnicodeString pattern;
734
735 double hours = hms[0].getDouble(status);
736 double minutes = hms[1].getDouble(status);
737 double seconds = hms[2].getDouble(status);
738 if (U_FAILURE(status)) {
739 return appendTo;
740 }
741
742 // All possible combinations: "h", "m", "s", "hm", "hs", "ms", "hms"
743 if (bitMap == 5 || bitMap == 7) { // "hms" & "hs" (we add minutes if "hs")
744 pattern = cache->getNumericDateFormatters()->hourMinuteSecond;
745 hours = uprv_trunc(hours);
746 minutes = uprv_trunc(minutes);
747 } else if (bitMap == 3) { // "hm"
748 pattern = cache->getNumericDateFormatters()->hourMinute;
749 hours = uprv_trunc(hours);
750 } else if (bitMap == 6) { // "ms"
751 pattern = cache->getNumericDateFormatters()->minuteSecond;
752 minutes = uprv_trunc(minutes);
753 } else { // h m s, handled outside formatNumeric. No value is also an error.
754 status = U_INTERNAL_PROGRAM_ERROR;
755 return appendTo;
756 }
757
758 const DecimalFormat *numberFormatter = dynamic_cast<const DecimalFormat*>(numberFormat->get());
759 if (!numberFormatter) {
760 status = U_INTERNAL_PROGRAM_ERROR;
761 return appendTo;
762 }
763 number::LocalizedNumberFormatter numberFormatter2;
764 if (auto* lnf = numberFormatter->toNumberFormatter(status)) {
765 numberFormatter2 = lnf->integerWidth(number::IntegerWidth::zeroFillTo(2));
766 } else {
767 return appendTo;
768 }
769
770 FormattedStringBuilder fsb;
771
772 UBool protect = false;
773 const int32_t patternLength = pattern.length();
774 for (int32_t i = 0; i < patternLength; i++) {
775 char16_t c = pattern[i];
776
777 // Also set the proper field in this switch
778 // We don't use DateFormat.Field because this is not a date / time, is a duration.
779 double value = 0;
780 switch (c) {
781 case u'H': value = hours; break;
782 case u'm': value = minutes; break;
783 case u's': value = seconds; break;
784 }
785
786 // There is not enough info to add Field(s) for the unit because all we have are plain
787 // text patterns. For example in "21:51" there is no text for something like "hour",
788 // while in something like "21h51" there is ("h"). But we can't really tell...
789 switch (c) {
790 case u'H':
791 case u'm':
792 case u's':
793 if (protect) {
794 fsb.appendChar16(c, kUndefinedField, status);
795 } else {
796 UnicodeString tmp;
797 if ((i + 1 < patternLength) && pattern[i + 1] == c) { // doubled
798 tmp = numberFormatter2.formatDouble(value, status).toString(status);
799 i++;
800 } else {
801 numberFormatter->format(value, tmp, status);
802 }
803 // TODO: Use proper Field
804 fsb.append(tmp, kUndefinedField, status);
805 }
806 break;
807 case u'\'':
808 // '' is escaped apostrophe
809 if ((i + 1 < patternLength) && pattern[i + 1] == c) {
810 fsb.appendChar16(c, kUndefinedField, status);
811 i++;
812 } else {
813 protect = !protect;
814 }
815 break;
816 default:
817 fsb.appendChar16(c, kUndefinedField, status);
818 }
819 }
820
821 appendTo.append(fsb.toTempUnicodeString());
822
823 return appendTo;
824 }
825
formatMeasuresSlowTrack(const Measure * measures,int32_t measureCount,UnicodeString & appendTo,FieldPosition & pos,UErrorCode & status) const826 UnicodeString &MeasureFormat::formatMeasuresSlowTrack(
827 const Measure *measures,
828 int32_t measureCount,
829 UnicodeString& appendTo,
830 FieldPosition& pos,
831 UErrorCode& status) const {
832 if (U_FAILURE(status)) {
833 return appendTo;
834 }
835 FieldPosition dontCare(FieldPosition::DONT_CARE);
836 FieldPosition fpos(pos.getField());
837 LocalArray<UnicodeString> results(new UnicodeString[measureCount], status);
838 int32_t fieldPositionFoundIndex = -1;
839 for (int32_t i = 0; i < measureCount; ++i) {
840 const NumberFormat *nf = cache->getIntegerFormat();
841 if (i == measureCount - 1) {
842 nf = numberFormat->get();
843 }
844 if (fieldPositionFoundIndex == -1) {
845 formatMeasure(measures[i], *nf, results[i], fpos, status);
846 if (U_FAILURE(status)) {
847 return appendTo;
848 }
849 if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
850 fieldPositionFoundIndex = i;
851 }
852 } else {
853 formatMeasure(measures[i], *nf, results[i], dontCare, status);
854 }
855 }
856 int32_t offset;
857 listFormatter->format(
858 results.getAlias(),
859 measureCount,
860 appendTo,
861 fieldPositionFoundIndex,
862 offset,
863 status);
864 if (U_FAILURE(status)) {
865 return appendTo;
866 }
867 // Fix up FieldPosition indexes if our field is found.
868 if (fieldPositionFoundIndex != -1 && offset != -1) {
869 pos.setBeginIndex(fpos.getBeginIndex() + offset);
870 pos.setEndIndex(fpos.getEndIndex() + offset);
871 }
872 return appendTo;
873 }
874
createCurrencyFormat(const Locale & locale,UErrorCode & ec)875 MeasureFormat* U_EXPORT2 MeasureFormat::createCurrencyFormat(const Locale& locale,
876 UErrorCode& ec) {
877 if (U_FAILURE(ec)) {
878 return nullptr;
879 }
880 LocalPointer<CurrencyFormat> fmt(new CurrencyFormat(locale, ec), ec);
881 return fmt.orphan();
882 }
883
createCurrencyFormat(UErrorCode & ec)884 MeasureFormat* U_EXPORT2 MeasureFormat::createCurrencyFormat(UErrorCode& ec) {
885 if (U_FAILURE(ec)) {
886 return nullptr;
887 }
888 return MeasureFormat::createCurrencyFormat(Locale::getDefault(), ec);
889 }
890
891 U_NAMESPACE_END
892
893 #endif /* #if !UCONFIG_NO_FORMATTING */
894