1 // Copyright (C) 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 **********************************************************************
5 * Copyright (c) 2004-2016, International Business Machines
6 * Corporation and others. All Rights Reserved.
7 **********************************************************************
9 * Created: April 20, 2004
11 **********************************************************************
13 #include "utypeinfo.h" // for 'typeid' to work
14 #include "unicode/utypes.h"
16 #if !UCONFIG_NO_FORMATTING
18 #include "unicode/measfmt.h"
19 #include "unicode/numfmt.h"
21 #include "unicode/localpointer.h"
23 #include "unicode/simpleformatter.h"
24 #include "quantityformatter.h"
25 #include "unicode/plurrule.h"
26 #include "unicode/decimfmt.h"
28 #include "unicode/ures.h"
33 #include "unicode/listformatter.h"
35 #include "unicode/putil.h"
36 #include "unicode/smpdtfmt.h"
39 #include "sharednumberformat.h"
40 #include "sharedpluralrules.h"
41 #include "standardplural.h"
42 #include "unifiedcache.h"
44 #define MEAS_UNIT_COUNT 138
45 #define WIDTH_INDEX_COUNT (UMEASFMT_WIDTH_NARROW + 1)
49 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(MeasureFormat)
51 // Used to format durations like 5:47 or 21:35:42.
52 class NumericDateFormatters : public UMemory {
55 SimpleDateFormat hourMinute;
58 SimpleDateFormat minuteSecond;
60 // formats like H:mm:ss
61 SimpleDateFormat hourMinuteSecond;
63 // Constructor that takes the actual patterns for hour-minute,
64 // minute-second, and hour-minute-second respectively.
65 NumericDateFormatters(
66 const UnicodeString &hm,
67 const UnicodeString &ms,
68 const UnicodeString &hms,
70 hourMinute(hm, status),
71 minuteSecond(ms, status),
72 hourMinuteSecond(hms, status) {
73 const TimeZone *gmt = TimeZone::getGMT();
74 hourMinute.setTimeZone(*gmt);
75 minuteSecond.setTimeZone(*gmt);
76 hourMinuteSecond.setTimeZone(*gmt);
79 NumericDateFormatters(const NumericDateFormatters &other);
80 NumericDateFormatters &operator=(const NumericDateFormatters &other);
83 static UMeasureFormatWidth getRegularWidth(UMeasureFormatWidth width) {
84 if (width >= WIDTH_INDEX_COUNT) {
85 return UMEASFMT_WIDTH_NARROW;
91 * Instances contain all MeasureFormat specific data for a particular locale.
92 * This data is cached. It is never copied, but is shared via shared pointers.
94 * Note: We might change the cache data to have an array[WIDTH_INDEX_COUNT] of
95 * complete sets of unit & per patterns,
96 * to correspond to the resource data and its aliases.
98 * TODO: Maybe store more sparsely in general, with pointers rather than potentially-empty objects.
100 class MeasureFormatCacheData : public SharedObject {
102 static const int32_t PER_UNIT_INDEX = StandardPlural::COUNT;
103 static const int32_t PATTERN_COUNT = PER_UNIT_INDEX + 1;
106 * Redirection data from root-bundle, top-level sideways aliases.
107 * - UMEASFMT_WIDTH_COUNT: initial value, just fall back to root
108 * - UMEASFMT_WIDTH_WIDE/SHORT/NARROW: sideways alias for missing data
110 UMeasureFormatWidth widthFallback[WIDTH_INDEX_COUNT];
111 /** Measure unit -> format width -> array of patterns ("{0} meters") (plurals + PER_UNIT_INDEX) */
112 SimpleFormatter *patterns[MEAS_UNIT_COUNT][WIDTH_INDEX_COUNT][PATTERN_COUNT];
113 const UChar* dnams[MEAS_UNIT_COUNT][WIDTH_INDEX_COUNT];
114 SimpleFormatter perFormatters[WIDTH_INDEX_COUNT];
116 MeasureFormatCacheData();
117 virtual ~MeasureFormatCacheData();
119 UBool hasPerFormatter(int32_t width) const {
120 // TODO: Create a more obvious way to test if the per-formatter has been set?
121 // Use pointers, check for NULL? Or add an isValid() method?
122 return perFormatters[width].getArgumentLimit() == 2;
125 void adoptCurrencyFormat(int32_t widthIndex, NumberFormat *nfToAdopt) {
126 delete currencyFormats[widthIndex];
127 currencyFormats[widthIndex] = nfToAdopt;
129 const NumberFormat *getCurrencyFormat(UMeasureFormatWidth width) const {
130 return currencyFormats[getRegularWidth(width)];
132 void adoptIntegerFormat(NumberFormat *nfToAdopt) {
133 delete integerFormat;
134 integerFormat = nfToAdopt;
136 const NumberFormat *getIntegerFormat() const {
137 return integerFormat;
139 void adoptNumericDateFormatters(NumericDateFormatters *formattersToAdopt) {
140 delete numericDateFormatters;
141 numericDateFormatters = formattersToAdopt;
143 const NumericDateFormatters *getNumericDateFormatters() const {
144 return numericDateFormatters;
148 NumberFormat *currencyFormats[WIDTH_INDEX_COUNT];
149 NumberFormat *integerFormat;
150 NumericDateFormatters *numericDateFormatters;
151 MeasureFormatCacheData(const MeasureFormatCacheData &other);
152 MeasureFormatCacheData &operator=(const MeasureFormatCacheData &other);
155 MeasureFormatCacheData::MeasureFormatCacheData() {
156 for (int32_t i = 0; i < WIDTH_INDEX_COUNT; ++i) {
157 widthFallback[i] = UMEASFMT_WIDTH_COUNT;
159 for (int32_t i = 0; i < UPRV_LENGTHOF(currencyFormats); ++i) {
160 currencyFormats[i] = NULL;
162 uprv_memset(patterns, 0, sizeof(patterns));
163 uprv_memset(dnams, 0, sizeof(dnams));
164 integerFormat = NULL;
165 numericDateFormatters = NULL;
168 MeasureFormatCacheData::~MeasureFormatCacheData() {
169 for (int32_t i = 0; i < UPRV_LENGTHOF(currencyFormats); ++i) {
170 delete currencyFormats[i];
172 for (int32_t i = 0; i < MEAS_UNIT_COUNT; ++i) {
173 for (int32_t j = 0; j < WIDTH_INDEX_COUNT; ++j) {
174 for (int32_t k = 0; k < PATTERN_COUNT; ++k) {
175 delete patterns[i][j][k];
179 // Note: the contents of 'dnams' are pointers into the resource bundle
180 delete integerFormat;
181 delete numericDateFormatters;
184 static UBool isCurrency(const MeasureUnit &unit) {
185 return (uprv_strcmp(unit.getType(), "currency") == 0);
188 static UBool getString(
189 const UResourceBundle *resource,
190 UnicodeString &result,
191 UErrorCode &status) {
193 const UChar *resStr = ures_getString(resource, &len, &status);
194 if (U_FAILURE(status)) {
197 result.setTo(TRUE, resStr, len);
203 static const UChar g_LOCALE_units[] = {
204 0x2F, 0x4C, 0x4F, 0x43, 0x41, 0x4C, 0x45, 0x2F,
205 0x75, 0x6E, 0x69, 0x74, 0x73
207 static const UChar gShort[] = { 0x53, 0x68, 0x6F, 0x72, 0x74 };
208 static const UChar gNarrow[] = { 0x4E, 0x61, 0x72, 0x72, 0x6F, 0x77 };
211 * Sink for enumerating all of the measurement unit display names.
212 * Contains inner sink classes, each one corresponding to a type of resource table.
213 * The outer sink handles the top-level units, unitsNarrow, and unitsShort tables.
215 * More specific bundles (en_GB) are enumerated before their parents (en_001, en, root):
216 * Only store a value if it is still missing, that is, it has not been overridden.
218 * C++: Each inner sink class has a reference to the main outer sink.
219 * Java: Use non-static inner classes instead.
221 struct UnitDataSink : public ResourceSink {
224 MeasureFormatCacheData &cacheData;
226 // Path to current data.
227 UMeasureFormatWidth width;
231 UnitDataSink(MeasureFormatCacheData &outputData)
232 : cacheData(outputData),
233 width(UMEASFMT_WIDTH_COUNT), type(NULL), unitIndex(0) {}
236 void setFormatterIfAbsent(int32_t index, const ResourceValue &value,
237 int32_t minPlaceholders, UErrorCode &errorCode) {
238 SimpleFormatter **patterns = &cacheData.patterns[unitIndex][width][0];
239 if (U_SUCCESS(errorCode) && patterns[index] == NULL) {
240 if (minPlaceholders >= 0) {
241 patterns[index] = new SimpleFormatter(
242 value.getUnicodeString(errorCode), minPlaceholders, 1, errorCode);
244 if (U_SUCCESS(errorCode) && patterns[index] == NULL) {
245 errorCode = U_MEMORY_ALLOCATION_ERROR;
250 void setDnamIfAbsent(const ResourceValue &value, UErrorCode& errorCode) {
251 if (cacheData.dnams[unitIndex][width] == NULL) {
253 cacheData.dnams[unitIndex][width] = value.getString(length, errorCode);
258 * Consume a display pattern. For example,
259 * unitsShort/duration/hour contains other{"{0} hrs"}.
261 void consumePattern(const char *key, const ResourceValue &value, UErrorCode &errorCode) {
262 if (U_FAILURE(errorCode)) { return; }
263 if (uprv_strcmp(key, "dnam") == 0) {
264 // The display name for the unit in the current width.
265 setDnamIfAbsent(value, errorCode);
266 } else if (uprv_strcmp(key, "per") == 0) {
267 // For example, "{0}/h".
268 setFormatterIfAbsent(MeasureFormatCacheData::PER_UNIT_INDEX, value, 1, errorCode);
270 // The key must be one of the plural form strings. For example:
273 setFormatterIfAbsent(StandardPlural::indexFromString(key, errorCode), value, 0,
279 * Consume a table of per-unit tables. For example,
280 * unitsShort/duration contains tables for duration-unit subtypes day & hour.
282 void consumeSubtypeTable(const char *key, ResourceValue &value, UErrorCode &errorCode) {
283 if (U_FAILURE(errorCode)) { return; }
284 unitIndex = MeasureUnit::internalGetIndexForTypeAndSubtype(type, key);
286 // TODO: How to handle unexpected data?
287 // See http://bugs.icu-project.org/trac/ticket/12597
291 if (value.getType() == URES_STRING) {
292 // Units like "coordinate" that don't have plural variants
293 setFormatterIfAbsent(StandardPlural::OTHER, value, 0, errorCode);
294 } else if (value.getType() == URES_TABLE) {
295 // Units that have plural variants
296 ResourceTable patternTableTable = value.getTable(errorCode);
297 if (U_FAILURE(errorCode)) { return; }
298 for (int i = 0; patternTableTable.getKeyAndValue(i, key, value); ++i) {
299 consumePattern(key, value, errorCode);
302 // TODO: How to handle unexpected data?
303 // See http://bugs.icu-project.org/trac/ticket/12597
309 * Consume compound x-per-y display pattern. For example,
310 * unitsShort/compound/per may be "{0}/{1}".
312 void consumeCompoundPattern(const char *key, const ResourceValue &value, UErrorCode &errorCode) {
313 if (U_SUCCESS(errorCode) && uprv_strcmp(key, "per") == 0) {
314 cacheData.perFormatters[width].
315 applyPatternMinMaxArguments(value.getUnicodeString(errorCode), 2, 2, errorCode);
320 * Consume a table of unit type tables. For example,
321 * unitsShort contains tables for area & duration.
322 * It also contains a table for the compound/per pattern.
324 void consumeUnitTypesTable(const char *key, ResourceValue &value, UErrorCode &errorCode) {
325 if (U_FAILURE(errorCode)) { return; }
326 if (uprv_strcmp(key, "currency") == 0) {
328 } else if (uprv_strcmp(key, "compound") == 0) {
329 if (!cacheData.hasPerFormatter(width)) {
330 ResourceTable compoundTable = value.getTable(errorCode);
331 if (U_FAILURE(errorCode)) { return; }
332 for (int i = 0; compoundTable.getKeyAndValue(i, key, value); ++i) {
333 consumeCompoundPattern(key, value, errorCode);
338 ResourceTable subtypeTable = value.getTable(errorCode);
339 if (U_FAILURE(errorCode)) { return; }
340 for (int i = 0; subtypeTable.getKeyAndValue(i, key, value); ++i) {
341 consumeSubtypeTable(key, value, errorCode);
346 void consumeAlias(const char *key, const ResourceValue &value, UErrorCode &errorCode) {
347 // Handle aliases like
348 // units:alias{"/LOCALE/unitsShort"}
349 // which should only occur in the root bundle.
350 UMeasureFormatWidth sourceWidth = widthFromKey(key);
351 if (sourceWidth == UMEASFMT_WIDTH_COUNT) {
352 // Alias from something we don't care about.
355 UMeasureFormatWidth targetWidth = widthFromAlias(value, errorCode);
356 if (targetWidth == UMEASFMT_WIDTH_COUNT) {
357 // We do not recognize what to fall back to.
358 errorCode = U_INVALID_FORMAT_ERROR;
361 // Check that we do not fall back to another fallback.
362 if (cacheData.widthFallback[targetWidth] != UMEASFMT_WIDTH_COUNT) {
363 errorCode = U_INVALID_FORMAT_ERROR;
366 cacheData.widthFallback[sourceWidth] = targetWidth;
369 void consumeTable(const char *key, ResourceValue &value, UErrorCode &errorCode) {
370 if (U_SUCCESS(errorCode) && (width = widthFromKey(key)) != UMEASFMT_WIDTH_COUNT) {
371 ResourceTable unitTypesTable = value.getTable(errorCode);
372 if (U_FAILURE(errorCode)) { return; }
373 for (int i = 0; unitTypesTable.getKeyAndValue(i, key, value); ++i) {
374 consumeUnitTypesTable(key, value, errorCode);
379 static UMeasureFormatWidth widthFromKey(const char *key) {
380 if (uprv_strncmp(key, "units", 5) == 0) {
383 return UMEASFMT_WIDTH_WIDE;
384 } else if (uprv_strcmp(key, "Short") == 0) {
385 return UMEASFMT_WIDTH_SHORT;
386 } else if (uprv_strcmp(key, "Narrow") == 0) {
387 return UMEASFMT_WIDTH_NARROW;
390 return UMEASFMT_WIDTH_COUNT;
393 static UMeasureFormatWidth widthFromAlias(const ResourceValue &value, UErrorCode &errorCode) {
395 const UChar *s = value.getAliasString(length, errorCode);
396 // For example: "/LOCALE/unitsShort"
397 if (U_SUCCESS(errorCode) && length >= 13 && u_memcmp(s, g_LOCALE_units, 13) == 0) {
401 return UMEASFMT_WIDTH_WIDE;
402 } else if (u_strCompare(s, length, gShort, 5, FALSE) == 0) {
403 return UMEASFMT_WIDTH_SHORT;
404 } else if (u_strCompare(s, length, gNarrow, 6, FALSE) == 0) {
405 return UMEASFMT_WIDTH_NARROW;
408 return UMEASFMT_WIDTH_COUNT;
411 virtual void put(const char *key, ResourceValue &value, UBool /*noFallback*/,
412 UErrorCode &errorCode) {
413 // Main entry point to sink
414 ResourceTable widthsTable = value.getTable(errorCode);
415 if (U_FAILURE(errorCode)) { return; }
416 for (int i = 0; widthsTable.getKeyAndValue(i, key, value); ++i) {
417 if (value.getType() == URES_ALIAS) {
418 consumeAlias(key, value, errorCode);
420 consumeTable(key, value, errorCode);
426 // Virtual destructors must be defined out of line.
427 UnitDataSink::~UnitDataSink() {}
431 static UBool loadMeasureUnitData(
432 const UResourceBundle *resource,
433 MeasureFormatCacheData &cacheData,
434 UErrorCode &status) {
435 UnitDataSink sink(cacheData);
436 ures_getAllItemsWithFallback(resource, "", sink, status);
437 return U_SUCCESS(status);
440 static UnicodeString loadNumericDateFormatterPattern(
441 const UResourceBundle *resource,
443 UErrorCode &status) {
444 UnicodeString result;
445 if (U_FAILURE(status)) {
449 chs.append("durationUnits", status)
450 .append("/", status).append(pattern, status);
451 LocalUResourceBundlePointer patternBundle(
452 ures_getByKeyWithFallback(
457 if (U_FAILURE(status)) {
460 getString(patternBundle.getAlias(), result, status);
461 // Replace 'h' with 'H'
462 int32_t len = result.length();
463 UChar *buffer = result.getBuffer(len);
464 for (int32_t i = 0; i < len; ++i) {
465 if (buffer[i] == 0x68) { // 'h'
466 buffer[i] = 0x48; // 'H'
469 result.releaseBuffer(len);
473 static NumericDateFormatters *loadNumericDateFormatters(
474 const UResourceBundle *resource,
475 UErrorCode &status) {
476 if (U_FAILURE(status)) {
479 NumericDateFormatters *result = new NumericDateFormatters(
480 loadNumericDateFormatterPattern(resource, "hm", status),
481 loadNumericDateFormatterPattern(resource, "ms", status),
482 loadNumericDateFormatterPattern(resource, "hms", status),
484 if (U_FAILURE(status)) {
491 template<> U_I18N_API
492 const MeasureFormatCacheData *LocaleCacheKey<MeasureFormatCacheData>::createObject(
493 const void * /*unused*/, UErrorCode &status) const {
494 const char *localeId = fLoc.getName();
495 LocalUResourceBundlePointer unitsBundle(ures_open(U_ICUDATA_UNIT, localeId, &status));
496 static UNumberFormatStyle currencyStyles[] = {
497 UNUM_CURRENCY_PLURAL, UNUM_CURRENCY_ISO, UNUM_CURRENCY};
498 LocalPointer<MeasureFormatCacheData> result(new MeasureFormatCacheData(), status);
499 if (U_FAILURE(status)) {
502 if (!loadMeasureUnitData(
503 unitsBundle.getAlias(),
508 result->adoptNumericDateFormatters(loadNumericDateFormatters(
509 unitsBundle.getAlias(), status));
510 if (U_FAILURE(status)) {
514 for (int32_t i = 0; i < WIDTH_INDEX_COUNT; ++i) {
515 // NumberFormat::createInstance can erase warning codes from status, so pass it
516 // a separate status instance
517 UErrorCode localStatus = U_ZERO_ERROR;
518 result->adoptCurrencyFormat(i, NumberFormat::createInstance(
519 localeId, currencyStyles[i], localStatus));
520 if (localStatus != U_ZERO_ERROR) {
521 status = localStatus;
523 if (U_FAILURE(status)) {
527 NumberFormat *inf = NumberFormat::createInstance(
528 localeId, UNUM_DECIMAL, status);
529 if (U_FAILURE(status)) {
532 inf->setMaximumFractionDigits(0);
533 DecimalFormat *decfmt = dynamic_cast<DecimalFormat *>(inf);
534 if (decfmt != NULL) {
535 decfmt->setRoundingMode(DecimalFormat::kRoundDown);
537 result->adoptIntegerFormat(inf);
539 return result.orphan();
542 static UBool isTimeUnit(const MeasureUnit &mu, const char *tu) {
543 return uprv_strcmp(mu.getType(), "duration") == 0 &&
544 uprv_strcmp(mu.getSubtype(), tu) == 0;
547 // Converts a composite measure into hours-minutes-seconds and stores at hms
548 // array. [0] is hours; [1] is minutes; [2] is seconds. Returns a bit map of
549 // units found: 1=hours, 2=minutes, 4=seconds. For example, if measures
550 // contains hours-minutes, this function would return 3.
552 // If measures cannot be converted into hours, minutes, seconds or if amounts
553 // are negative, or if hours, minutes, seconds are out of order, returns 0.
554 static int32_t toHMS(
555 const Measure *measures,
556 int32_t measureCount,
558 UErrorCode &status) {
559 if (U_FAILURE(status)) {
563 if (U_FAILURE(status)) {
566 // We use copy constructor to ensure that both sides of equality operator
567 // are instances of MeasureUnit base class and not a subclass. Otherwise,
568 // operator== will immediately return false.
569 for (int32_t i = 0; i < measureCount; ++i) {
570 if (isTimeUnit(measures[i].getUnit(), "hour")) {
571 // hour must come first
575 hms[0] = measures[i].getNumber();
576 if (hms[0].getDouble() < 0.0) {
580 } else if (isTimeUnit(measures[i].getUnit(), "minute")) {
581 // minute must come after hour
585 hms[1] = measures[i].getNumber();
586 if (hms[1].getDouble() < 0.0) {
590 } else if (isTimeUnit(measures[i].getUnit(), "second")) {
591 // second must come after hour and minute
595 hms[2] = measures[i].getNumber();
596 if (hms[2].getDouble() < 0.0) {
608 MeasureFormat::MeasureFormat(
609 const Locale &locale, UMeasureFormatWidth w, UErrorCode &status)
614 listFormatter(NULL) {
615 initMeasureFormat(locale, w, NULL, status);
618 MeasureFormat::MeasureFormat(
619 const Locale &locale,
620 UMeasureFormatWidth w,
621 NumberFormat *nfToAdopt,
627 listFormatter(NULL) {
628 initMeasureFormat(locale, w, nfToAdopt, status);
631 MeasureFormat::MeasureFormat(const MeasureFormat &other) :
634 numberFormat(other.numberFormat),
635 pluralRules(other.pluralRules),
637 listFormatter(NULL) {
639 numberFormat->addRef();
640 pluralRules->addRef();
641 if (other.listFormatter != NULL) {
642 listFormatter = new ListFormatter(*other.listFormatter);
646 MeasureFormat &MeasureFormat::operator=(const MeasureFormat &other) {
647 if (this == &other) {
650 Format::operator=(other);
651 SharedObject::copyPtr(other.cache, cache);
652 SharedObject::copyPtr(other.numberFormat, numberFormat);
653 SharedObject::copyPtr(other.pluralRules, pluralRules);
655 delete listFormatter;
656 if (other.listFormatter != NULL) {
657 listFormatter = new ListFormatter(*other.listFormatter);
659 listFormatter = NULL;
664 MeasureFormat::MeasureFormat() :
668 width(UMEASFMT_WIDTH_SHORT),
669 listFormatter(NULL) {
672 MeasureFormat::~MeasureFormat() {
676 if (numberFormat != NULL) {
677 numberFormat->removeRef();
679 if (pluralRules != NULL) {
680 pluralRules->removeRef();
682 delete listFormatter;
685 UBool MeasureFormat::operator==(const Format &other) const {
686 if (this == &other) { // Same object, equal
689 if (!Format::operator==(other)) {
692 const MeasureFormat &rhs = static_cast<const MeasureFormat &>(other);
694 // Note: Since the ListFormatter depends only on Locale and width, we
695 // don't have to check it here.
697 // differing widths aren't equivalent
698 if (width != rhs.width) {
701 // Width the same check locales.
702 // We don't need to check locales if both objects have same cache.
703 if (cache != rhs.cache) {
704 UErrorCode status = U_ZERO_ERROR;
705 const char *localeId = getLocaleID(status);
706 const char *rhsLocaleId = rhs.getLocaleID(status);
707 if (U_FAILURE(status)) {
708 // On failure, assume not equal
711 if (uprv_strcmp(localeId, rhsLocaleId) != 0) {
715 // Locales same, check NumberFormat if shared data differs.
717 numberFormat == rhs.numberFormat ||
718 **numberFormat == **rhs.numberFormat);
721 Format *MeasureFormat::clone() const {
722 return new MeasureFormat(*this);
725 UnicodeString &MeasureFormat::format(
726 const Formattable &obj,
727 UnicodeString &appendTo,
729 UErrorCode &status) const {
730 if (U_FAILURE(status)) return appendTo;
731 if (obj.getType() == Formattable::kObject) {
732 const UObject* formatObj = obj.getObject();
733 const Measure* amount = dynamic_cast<const Measure*>(formatObj);
734 if (amount != NULL) {
735 return formatMeasure(
736 *amount, **numberFormat, appendTo, pos, status);
739 status = U_ILLEGAL_ARGUMENT_ERROR;
743 void MeasureFormat::parseObject(
744 const UnicodeString & /*source*/,
745 Formattable & /*result*/,
746 ParsePosition& /*pos*/) const {
750 UnicodeString &MeasureFormat::formatMeasurePerUnit(
751 const Measure &measure,
752 const MeasureUnit &perUnit,
753 UnicodeString &appendTo,
755 UErrorCode &status) const {
756 if (U_FAILURE(status)) {
759 MeasureUnit *resolvedUnit =
760 MeasureUnit::resolveUnitPerUnit(measure.getUnit(), perUnit);
761 if (resolvedUnit != NULL) {
762 Measure newMeasure(measure.getNumber(), resolvedUnit, status);
763 return formatMeasure(
764 newMeasure, **numberFormat, appendTo, pos, status);
766 FieldPosition fpos(pos.getField());
767 UnicodeString result;
768 int32_t offset = withPerUnitAndAppend(
770 measure, **numberFormat, result, fpos, status),
774 if (U_FAILURE(status)) {
777 if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
778 pos.setBeginIndex(fpos.getBeginIndex() + offset);
779 pos.setEndIndex(fpos.getEndIndex() + offset);
784 UnicodeString &MeasureFormat::formatMeasures(
785 const Measure *measures,
786 int32_t measureCount,
787 UnicodeString &appendTo,
789 UErrorCode &status) const {
790 if (U_FAILURE(status)) {
793 if (measureCount == 0) {
796 if (measureCount == 1) {
797 return formatMeasure(measures[0], **numberFormat, appendTo, pos, status);
799 if (width == UMEASFMT_WIDTH_NUMERIC) {
801 int32_t bitMap = toHMS(measures, measureCount, hms, status);
803 return formatNumeric(hms, bitMap, appendTo, status);
806 if (pos.getField() != FieldPosition::DONT_CARE) {
807 return formatMeasuresSlowTrack(
808 measures, measureCount, appendTo, pos, status);
810 UnicodeString *results = new UnicodeString[measureCount];
811 if (results == NULL) {
812 status = U_MEMORY_ALLOCATION_ERROR;
815 for (int32_t i = 0; i < measureCount; ++i) {
816 const NumberFormat *nf = cache->getIntegerFormat();
817 if (i == measureCount - 1) {
818 nf = numberFormat->get();
827 listFormatter->format(results, measureCount, appendTo, status);
832 UnicodeString MeasureFormat::getUnitDisplayName(const MeasureUnit& unit, UErrorCode& /*status*/) const {
833 UMeasureFormatWidth width = getRegularWidth(this->width);
834 const UChar* const* styleToDnam = cache->dnams[unit.getIndex()];
835 const UChar* dnam = styleToDnam[width];
837 int32_t fallbackWidth = cache->widthFallback[width];
838 dnam = styleToDnam[fallbackWidth];
841 UnicodeString result;
845 result.setTo(dnam, -1);
850 void MeasureFormat::initMeasureFormat(
851 const Locale &locale,
852 UMeasureFormatWidth w,
853 NumberFormat *nfToAdopt,
854 UErrorCode &status) {
855 static const char *listStyles[] = {"unit", "unit-short", "unit-narrow"};
856 LocalPointer<NumberFormat> nf(nfToAdopt);
857 if (U_FAILURE(status)) {
860 const char *name = locale.getName();
861 setLocaleIDs(name, name);
863 UnifiedCache::getByLocale(locale, cache, status);
864 if (U_FAILURE(status)) {
868 const SharedPluralRules *pr = PluralRules::createSharedInstance(
869 locale, UPLURAL_TYPE_CARDINAL, status);
870 if (U_FAILURE(status)) {
873 SharedObject::copyPtr(pr, pluralRules);
876 const SharedNumberFormat *shared = NumberFormat::createSharedInstance(
877 locale, UNUM_DECIMAL, status);
878 if (U_FAILURE(status)) {
881 SharedObject::copyPtr(shared, numberFormat);
884 adoptNumberFormat(nf.orphan(), status);
885 if (U_FAILURE(status)) {
890 delete listFormatter;
891 listFormatter = ListFormatter::createInstance(
893 listStyles[getRegularWidth(width)],
897 void MeasureFormat::adoptNumberFormat(
898 NumberFormat *nfToAdopt, UErrorCode &status) {
899 LocalPointer<NumberFormat> nf(nfToAdopt);
900 if (U_FAILURE(status)) {
903 SharedNumberFormat *shared = new SharedNumberFormat(nf.getAlias());
904 if (shared == NULL) {
905 status = U_MEMORY_ALLOCATION_ERROR;
909 SharedObject::copyPtr(shared, numberFormat);
912 UBool MeasureFormat::setMeasureFormatLocale(const Locale &locale, UErrorCode &status) {
913 if (U_FAILURE(status) || locale == getLocale(status)) {
916 initMeasureFormat(locale, width, NULL, status);
917 return U_SUCCESS(status);
920 const NumberFormat &MeasureFormat::getNumberFormat() const {
921 return **numberFormat;
924 const PluralRules &MeasureFormat::getPluralRules() const {
925 return **pluralRules;
928 Locale MeasureFormat::getLocale(UErrorCode &status) const {
929 return Format::getLocale(ULOC_VALID_LOCALE, status);
932 const char *MeasureFormat::getLocaleID(UErrorCode &status) const {
933 return Format::getLocaleID(ULOC_VALID_LOCALE, status);
936 UnicodeString &MeasureFormat::formatMeasure(
937 const Measure &measure,
938 const NumberFormat &nf,
939 UnicodeString &appendTo,
941 UErrorCode &status) const {
942 if (U_FAILURE(status)) {
945 const Formattable& amtNumber = measure.getNumber();
946 const MeasureUnit& amtUnit = measure.getUnit();
947 if (isCurrency(amtUnit)) {
949 u_charsToUChars(amtUnit.getSubtype(), isoCode, 4);
950 return cache->getCurrencyFormat(width)->format(
951 new CurrencyAmount(amtNumber, isoCode, status),
956 UnicodeString formattedNumber;
957 StandardPlural::Form pluralForm = QuantityFormatter::selectPlural(
958 amtNumber, nf, **pluralRules, formattedNumber, pos, status);
959 const SimpleFormatter *formatter = getPluralFormatter(amtUnit, width, pluralForm, status);
960 return QuantityFormatter::format(*formatter, formattedNumber, appendTo, pos, status);
963 // Formats hours-minutes-seconds as 5:37:23 or similar.
964 UnicodeString &MeasureFormat::formatNumeric(
965 const Formattable *hms, // always length 3
966 int32_t bitMap, // 1=hourset, 2=minuteset, 4=secondset
967 UnicodeString &appendTo,
968 UErrorCode &status) const {
969 if (U_FAILURE(status)) {
973 (UDate) (((uprv_trunc(hms[0].getDouble(status)) * 60.0
974 + uprv_trunc(hms[1].getDouble(status))) * 60.0
975 + uprv_trunc(hms[2].getDouble(status))) * 1000.0);
979 return formatNumeric(
981 cache->getNumericDateFormatters()->hourMinuteSecond,
988 return formatNumeric(
990 cache->getNumericDateFormatters()->minuteSecond,
997 return formatNumeric(
999 cache->getNumericDateFormatters()->hourMinute,
1006 status = U_INTERNAL_PROGRAM_ERROR;
1013 static void appendRange(
1014 const UnicodeString &src,
1017 UnicodeString &dest) {
1018 dest.append(src, start, end - start);
1021 static void appendRange(
1022 const UnicodeString &src,
1024 UnicodeString &dest) {
1025 dest.append(src, end, src.length() - end);
1028 // Formats time like 5:37:23
1029 UnicodeString &MeasureFormat::formatNumeric(
1030 UDate date, // Time since epoch 1:30:00 would be 5400000
1031 const DateFormat &dateFmt, // h:mm, m:ss, or h:mm:ss
1032 UDateFormatField smallestField, // seconds in 5:37:23.5
1033 const Formattable &smallestAmount, // 23.5 for 5:37:23.5
1034 UnicodeString &appendTo,
1035 UErrorCode &status) const {
1036 if (U_FAILURE(status)) {
1039 // Format the smallest amount with this object's NumberFormat
1040 UnicodeString smallestAmountFormatted;
1042 // We keep track of the integer part of smallest amount so that
1043 // we can replace it later so that we get '0:00:09.3' instead of
1045 FieldPosition intFieldPosition(UNUM_INTEGER_FIELD);
1046 (*numberFormat)->format(
1047 smallestAmount, smallestAmountFormatted, intFieldPosition, status);
1049 intFieldPosition.getBeginIndex() == 0 &&
1050 intFieldPosition.getEndIndex() == 0) {
1051 status = U_INTERNAL_PROGRAM_ERROR;
1055 // Format time. draft becomes something like '5:30:45'
1056 FieldPosition smallestFieldPosition(smallestField);
1057 UnicodeString draft;
1058 dateFmt.format(date, draft, smallestFieldPosition, status);
1060 // If we find field for smallest amount replace it with the formatted
1061 // smallest amount from above taking care to replace the integer part
1062 // with what is in original time. For example, If smallest amount
1063 // is 9.35s and the formatted time is 0:00:09 then 9.35 becomes 09.35
1064 // and replacing yields 0:00:09.35
1065 if (smallestFieldPosition.getBeginIndex() != 0 ||
1066 smallestFieldPosition.getEndIndex() != 0) {
1067 appendRange(draft, 0, smallestFieldPosition.getBeginIndex(), appendTo);
1069 smallestAmountFormatted,
1071 intFieldPosition.getBeginIndex(),
1075 smallestFieldPosition.getBeginIndex(),
1076 smallestFieldPosition.getEndIndex(),
1079 smallestAmountFormatted,
1080 intFieldPosition.getEndIndex(),
1084 smallestFieldPosition.getEndIndex(),
1087 appendTo.append(draft);
1092 const SimpleFormatter *MeasureFormat::getFormatterOrNull(
1093 const MeasureUnit &unit, UMeasureFormatWidth width, int32_t index) const {
1094 width = getRegularWidth(width);
1095 SimpleFormatter *const (*unitPatterns)[MeasureFormatCacheData::PATTERN_COUNT] =
1096 &cache->patterns[unit.getIndex()][0];
1097 if (unitPatterns[width][index] != NULL) {
1098 return unitPatterns[width][index];
1100 int32_t fallbackWidth = cache->widthFallback[width];
1101 if (fallbackWidth != UMEASFMT_WIDTH_COUNT && unitPatterns[fallbackWidth][index] != NULL) {
1102 return unitPatterns[fallbackWidth][index];
1107 const SimpleFormatter *MeasureFormat::getFormatter(
1108 const MeasureUnit &unit, UMeasureFormatWidth width, int32_t index,
1109 UErrorCode &errorCode) const {
1110 if (U_FAILURE(errorCode)) {
1113 const SimpleFormatter *pattern = getFormatterOrNull(unit, width, index);
1114 if (pattern == NULL) {
1115 errorCode = U_MISSING_RESOURCE_ERROR;
1120 const SimpleFormatter *MeasureFormat::getPluralFormatter(
1121 const MeasureUnit &unit, UMeasureFormatWidth width, int32_t index,
1122 UErrorCode &errorCode) const {
1123 if (U_FAILURE(errorCode)) {
1126 if (index != StandardPlural::OTHER) {
1127 const SimpleFormatter *pattern = getFormatterOrNull(unit, width, index);
1128 if (pattern != NULL) {
1132 return getFormatter(unit, width, StandardPlural::OTHER, errorCode);
1135 const SimpleFormatter *MeasureFormat::getPerFormatter(
1136 UMeasureFormatWidth width,
1137 UErrorCode &status) const {
1138 if (U_FAILURE(status)) {
1141 width = getRegularWidth(width);
1142 const SimpleFormatter * perFormatters = cache->perFormatters;
1143 if (perFormatters[width].getArgumentLimit() == 2) {
1144 return &perFormatters[width];
1146 int32_t fallbackWidth = cache->widthFallback[width];
1147 if (fallbackWidth != UMEASFMT_WIDTH_COUNT &&
1148 perFormatters[fallbackWidth].getArgumentLimit() == 2) {
1149 return &perFormatters[fallbackWidth];
1151 status = U_MISSING_RESOURCE_ERROR;
1155 int32_t MeasureFormat::withPerUnitAndAppend(
1156 const UnicodeString &formatted,
1157 const MeasureUnit &perUnit,
1158 UnicodeString &appendTo,
1159 UErrorCode &status) const {
1160 int32_t offset = -1;
1161 if (U_FAILURE(status)) {
1164 const SimpleFormatter *perUnitFormatter =
1165 getFormatterOrNull(perUnit, width, MeasureFormatCacheData::PER_UNIT_INDEX);
1166 if (perUnitFormatter != NULL) {
1167 const UnicodeString *params[] = {&formatted};
1168 perUnitFormatter->formatAndAppend(
1170 UPRV_LENGTHOF(params),
1177 const SimpleFormatter *perFormatter = getPerFormatter(width, status);
1178 const SimpleFormatter *pattern =
1179 getPluralFormatter(perUnit, width, StandardPlural::ONE, status);
1180 if (U_FAILURE(status)) {
1183 UnicodeString perUnitString = pattern->getTextWithNoArguments();
1184 perUnitString.trim();
1185 const UnicodeString *params[] = {&formatted, &perUnitString};
1186 perFormatter->formatAndAppend(
1188 UPRV_LENGTHOF(params),
1196 UnicodeString &MeasureFormat::formatMeasuresSlowTrack(
1197 const Measure *measures,
1198 int32_t measureCount,
1199 UnicodeString& appendTo,
1201 UErrorCode& status) const {
1202 if (U_FAILURE(status)) {
1205 FieldPosition dontCare(FieldPosition::DONT_CARE);
1206 FieldPosition fpos(pos.getField());
1207 UnicodeString *results = new UnicodeString[measureCount];
1208 int32_t fieldPositionFoundIndex = -1;
1209 for (int32_t i = 0; i < measureCount; ++i) {
1210 const NumberFormat *nf = cache->getIntegerFormat();
1211 if (i == measureCount - 1) {
1212 nf = numberFormat->get();
1214 if (fieldPositionFoundIndex == -1) {
1215 formatMeasure(measures[i], *nf, results[i], fpos, status);
1216 if (U_FAILURE(status)) {
1220 if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
1221 fieldPositionFoundIndex = i;
1224 formatMeasure(measures[i], *nf, results[i], dontCare, status);
1228 listFormatter->format(
1232 fieldPositionFoundIndex,
1235 if (U_FAILURE(status)) {
1240 pos.setBeginIndex(fpos.getBeginIndex() + offset);
1241 pos.setEndIndex(fpos.getEndIndex() + offset);
1247 MeasureFormat* U_EXPORT2 MeasureFormat::createCurrencyFormat(const Locale& locale,
1249 CurrencyFormat* fmt = NULL;
1250 if (U_SUCCESS(ec)) {
1251 fmt = new CurrencyFormat(locale, ec);
1252 if (U_FAILURE(ec)) {
1260 MeasureFormat* U_EXPORT2 MeasureFormat::createCurrencyFormat(UErrorCode& ec) {
1261 if (U_FAILURE(ec)) {
1264 return MeasureFormat::createCurrencyFormat(Locale::getDefault(), ec);
1269 #endif /* #if !UCONFIG_NO_FORMATTING */