Imported Upstream version 58.1
[platform/upstream/icu.git] / source / i18n / measfmt.cpp
1 // Copyright (C) 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 "ureslocs.h"
30 #include "cstring.h"
31 #include "mutex.h"
32 #include "ucln_in.h"
33 #include "unicode/listformatter.h"
34 #include "charstr.h"
35 #include "unicode/putil.h"
36 #include "unicode/smpdtfmt.h"
37 #include "uassert.h"
38
39 #include "sharednumberformat.h"
40 #include "sharedpluralrules.h"
41 #include "standardplural.h"
42 #include "unifiedcache.h"
43
44 #define MEAS_UNIT_COUNT 138
45 #define WIDTH_INDEX_COUNT (UMEASFMT_WIDTH_NARROW + 1)
46
47 U_NAMESPACE_BEGIN
48
49 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(MeasureFormat)
50
51 // Used to format durations like 5:47 or 21:35:42.
52 class NumericDateFormatters : public UMemory {
53 public:
54     // Formats like H:mm
55     SimpleDateFormat hourMinute;
56
57     // formats like M:ss
58     SimpleDateFormat minuteSecond;
59
60     // formats like H:mm:ss
61     SimpleDateFormat hourMinuteSecond;
62
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,
69             UErrorCode &status) : 
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);
77     }
78 private:
79     NumericDateFormatters(const NumericDateFormatters &other);
80     NumericDateFormatters &operator=(const NumericDateFormatters &other);
81 };
82
83 static UMeasureFormatWidth getRegularWidth(UMeasureFormatWidth width) {
84     if (width >= WIDTH_INDEX_COUNT) {
85         return UMEASFMT_WIDTH_NARROW;
86     }
87     return width;
88 }
89
90 /**
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.
93  *
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.
97  *
98  * TODO: Maybe store more sparsely in general, with pointers rather than potentially-empty objects.
99  */
100 class MeasureFormatCacheData : public SharedObject {
101 public:
102     static const int32_t PER_UNIT_INDEX = StandardPlural::COUNT;
103     static const int32_t PATTERN_COUNT = PER_UNIT_INDEX + 1;
104
105     /**
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
109      */
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];
115
116     MeasureFormatCacheData();
117     virtual ~MeasureFormatCacheData();
118
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;
123     }
124
125     void adoptCurrencyFormat(int32_t widthIndex, NumberFormat *nfToAdopt) {
126         delete currencyFormats[widthIndex];
127         currencyFormats[widthIndex] = nfToAdopt;
128     }
129     const NumberFormat *getCurrencyFormat(UMeasureFormatWidth width) const {
130         return currencyFormats[getRegularWidth(width)];
131     }
132     void adoptIntegerFormat(NumberFormat *nfToAdopt) {
133         delete integerFormat;
134         integerFormat = nfToAdopt;
135     }
136     const NumberFormat *getIntegerFormat() const {
137         return integerFormat;
138     }
139     void adoptNumericDateFormatters(NumericDateFormatters *formattersToAdopt) {
140         delete numericDateFormatters;
141         numericDateFormatters = formattersToAdopt;
142     }
143     const NumericDateFormatters *getNumericDateFormatters() const {
144         return numericDateFormatters;
145     }
146
147 private:
148     NumberFormat *currencyFormats[WIDTH_INDEX_COUNT];
149     NumberFormat *integerFormat;
150     NumericDateFormatters *numericDateFormatters;
151     MeasureFormatCacheData(const MeasureFormatCacheData &other);
152     MeasureFormatCacheData &operator=(const MeasureFormatCacheData &other);
153 };
154
155 MeasureFormatCacheData::MeasureFormatCacheData() {
156     for (int32_t i = 0; i < WIDTH_INDEX_COUNT; ++i) {
157         widthFallback[i] = UMEASFMT_WIDTH_COUNT;
158     }
159     for (int32_t i = 0; i < UPRV_LENGTHOF(currencyFormats); ++i) {
160         currencyFormats[i] = NULL;
161     }
162     uprv_memset(patterns, 0, sizeof(patterns));
163     uprv_memset(dnams, 0, sizeof(dnams));
164     integerFormat = NULL;
165     numericDateFormatters = NULL;
166 }
167
168 MeasureFormatCacheData::~MeasureFormatCacheData() {
169     for (int32_t i = 0; i < UPRV_LENGTHOF(currencyFormats); ++i) {
170         delete currencyFormats[i];
171     }
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];
176             }
177         }
178     }
179     // Note: the contents of 'dnams' are pointers into the resource bundle
180     delete integerFormat;
181     delete numericDateFormatters;
182 }
183
184 static UBool isCurrency(const MeasureUnit &unit) {
185     return (uprv_strcmp(unit.getType(), "currency") == 0);
186 }
187
188 static UBool getString(
189         const UResourceBundle *resource,
190         UnicodeString &result,
191         UErrorCode &status) {
192     int32_t len = 0;
193     const UChar *resStr = ures_getString(resource, &len, &status);
194     if (U_FAILURE(status)) {
195         return FALSE;
196     }
197     result.setTo(TRUE, resStr, len);
198     return TRUE;
199 }
200
201 namespace {
202
203 static const UChar g_LOCALE_units[] = {
204     0x2F, 0x4C, 0x4F, 0x43, 0x41, 0x4C, 0x45, 0x2F,
205     0x75, 0x6E, 0x69, 0x74, 0x73
206 };
207 static const UChar gShort[] = { 0x53, 0x68, 0x6F, 0x72, 0x74 };
208 static const UChar gNarrow[] = { 0x4E, 0x61, 0x72, 0x72, 0x6F, 0x77 };
209
210 /**
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.
214  *
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.
217  *
218  * C++: Each inner sink class has a reference to the main outer sink.
219  * Java: Use non-static inner classes instead.
220  */
221 struct UnitDataSink : public ResourceSink {
222
223     // Output data.
224     MeasureFormatCacheData &cacheData;
225
226     // Path to current data.
227     UMeasureFormatWidth width;
228     const char *type;
229     int32_t unitIndex;
230
231     UnitDataSink(MeasureFormatCacheData &outputData)
232             : cacheData(outputData),
233               width(UMEASFMT_WIDTH_COUNT), type(NULL), unitIndex(0) {}
234     ~UnitDataSink();
235
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);
243             }
244             if (U_SUCCESS(errorCode) && patterns[index] == NULL) {
245                 errorCode = U_MEMORY_ALLOCATION_ERROR;
246             }
247         }
248     }
249
250     void setDnamIfAbsent(const ResourceValue &value, UErrorCode& errorCode) {
251         if (cacheData.dnams[unitIndex][width] == NULL) {
252             int32_t length;
253             cacheData.dnams[unitIndex][width] = value.getString(length, errorCode);
254         }
255     }
256
257     /**
258      * Consume a display pattern. For example,
259      * unitsShort/duration/hour contains other{"{0} hrs"}.
260      */
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);
269         } else {
270             // The key must be one of the plural form strings. For example:
271             // one{"{0} hr"}
272             // other{"{0} hrs"}
273             setFormatterIfAbsent(StandardPlural::indexFromString(key, errorCode), value, 0,
274                                     errorCode);
275         }
276     }
277
278     /**
279      * Consume a table of per-unit tables. For example,
280      * unitsShort/duration contains tables for duration-unit subtypes day & hour.
281      */
282     void consumeSubtypeTable(const char *key, ResourceValue &value, UErrorCode &errorCode) {
283         if (U_FAILURE(errorCode)) { return; }
284         unitIndex = MeasureUnit::internalGetIndexForTypeAndSubtype(type, key);
285         if (unitIndex < 0) {
286             // TODO: How to handle unexpected data?
287             // See http://bugs.icu-project.org/trac/ticket/12597
288             return;
289         }
290
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);
300             }
301         } else {
302             // TODO: How to handle unexpected data?
303             // See http://bugs.icu-project.org/trac/ticket/12597
304             return;
305         }
306     }
307
308     /**
309      * Consume compound x-per-y display pattern. For example,
310      * unitsShort/compound/per may be "{0}/{1}".
311      */
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);
316         }
317     }
318
319     /**
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.
323      */
324     void consumeUnitTypesTable(const char *key, ResourceValue &value, UErrorCode &errorCode) {
325         if (U_FAILURE(errorCode)) { return; }
326         if (uprv_strcmp(key, "currency") == 0) {
327             // Skip.
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);
334                 }
335             }
336         } else {
337             type = key;
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);
342             }
343         }
344     }
345
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.
353             return;
354         }
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;
359             return;
360         }
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;
364             return;
365         }
366         cacheData.widthFallback[sourceWidth] = targetWidth;
367     }
368
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);
375             }
376         }
377     }
378
379     static UMeasureFormatWidth widthFromKey(const char *key) {
380         if (uprv_strncmp(key, "units", 5) == 0) {
381             key += 5;
382             if (*key == 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;
388             }
389         }
390         return UMEASFMT_WIDTH_COUNT;
391     }
392
393     static UMeasureFormatWidth widthFromAlias(const ResourceValue &value, UErrorCode &errorCode) {
394         int32_t length;
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) {
398             s += 13;
399             length -= 13;
400             if (*s == 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;
406             }
407         }
408         return UMEASFMT_WIDTH_COUNT;
409     }
410
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);
419             } else {
420                 consumeTable(key, value, errorCode);
421             }
422         }
423     }
424 };
425
426 // Virtual destructors must be defined out of line.
427 UnitDataSink::~UnitDataSink() {}
428
429 }  // namespace
430
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);
438 }
439
440 static UnicodeString loadNumericDateFormatterPattern(
441         const UResourceBundle *resource,
442         const char *pattern,
443         UErrorCode &status) {
444     UnicodeString result;
445     if (U_FAILURE(status)) {
446         return result;
447     }
448     CharString chs;
449     chs.append("durationUnits", status)
450             .append("/", status).append(pattern, status);
451     LocalUResourceBundlePointer patternBundle(
452             ures_getByKeyWithFallback(
453                 resource,
454                 chs.data(),
455                 NULL,
456                 &status));
457     if (U_FAILURE(status)) {
458         return result;
459     }
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'
467         }
468     }
469     result.releaseBuffer(len);
470     return result;
471 }
472
473 static NumericDateFormatters *loadNumericDateFormatters(
474         const UResourceBundle *resource,
475         UErrorCode &status) {
476     if (U_FAILURE(status)) {
477         return NULL;
478     }
479     NumericDateFormatters *result = new NumericDateFormatters(
480         loadNumericDateFormatterPattern(resource, "hm", status),
481         loadNumericDateFormatterPattern(resource, "ms", status),
482         loadNumericDateFormatterPattern(resource, "hms", status),
483         status);
484     if (U_FAILURE(status)) {
485         delete result;
486         return NULL;
487     }
488     return result;
489 }
490
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)) {
500         return NULL;
501     }
502     if (!loadMeasureUnitData(
503             unitsBundle.getAlias(),
504             *result,
505             status)) {
506         return NULL;
507     }
508     result->adoptNumericDateFormatters(loadNumericDateFormatters(
509             unitsBundle.getAlias(), status));
510     if (U_FAILURE(status)) {
511         return NULL;
512     }
513
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;
522         }
523         if (U_FAILURE(status)) {
524             return NULL;
525         }
526     }
527     NumberFormat *inf = NumberFormat::createInstance(
528             localeId, UNUM_DECIMAL, status);
529     if (U_FAILURE(status)) {
530         return NULL;
531     }
532     inf->setMaximumFractionDigits(0);
533     DecimalFormat *decfmt = dynamic_cast<DecimalFormat *>(inf);
534     if (decfmt != NULL) {
535         decfmt->setRoundingMode(DecimalFormat::kRoundDown);
536     }
537     result->adoptIntegerFormat(inf);
538     result->addRef();
539     return result.orphan();
540 }
541
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;
545 }
546
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.
551 //
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,
557         Formattable *hms,
558         UErrorCode &status) {
559     if (U_FAILURE(status)) {
560         return 0;
561     }
562     int32_t result = 0;
563     if (U_FAILURE(status)) {
564         return 0;
565     }
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
572             if (result >= 1) {
573                 return 0;
574             }
575             hms[0] = measures[i].getNumber();
576             if (hms[0].getDouble() < 0.0) {
577                 return 0;
578             }
579             result |= 1;
580         } else if (isTimeUnit(measures[i].getUnit(), "minute")) {
581             // minute must come after hour
582             if (result >= 2) {
583                 return 0;
584             }
585             hms[1] = measures[i].getNumber();
586             if (hms[1].getDouble() < 0.0) {
587                 return 0;
588             }
589             result |= 2;
590         } else if (isTimeUnit(measures[i].getUnit(), "second")) {
591             // second must come after hour and minute
592             if (result >= 4) {
593                 return 0;
594             }
595             hms[2] = measures[i].getNumber();
596             if (hms[2].getDouble() < 0.0) {
597                 return 0;
598             }
599             result |= 4;
600         } else {
601             return 0;
602         }
603     }
604     return result;
605 }
606
607
608 MeasureFormat::MeasureFormat(
609         const Locale &locale, UMeasureFormatWidth w, UErrorCode &status)
610         : cache(NULL),
611           numberFormat(NULL),
612           pluralRules(NULL),
613           width(w),
614           listFormatter(NULL) {
615     initMeasureFormat(locale, w, NULL, status);
616 }
617
618 MeasureFormat::MeasureFormat(
619         const Locale &locale,
620         UMeasureFormatWidth w,
621         NumberFormat *nfToAdopt,
622         UErrorCode &status) 
623         : cache(NULL),
624           numberFormat(NULL),
625           pluralRules(NULL),
626           width(w),
627           listFormatter(NULL) {
628     initMeasureFormat(locale, w, nfToAdopt, status);
629 }
630
631 MeasureFormat::MeasureFormat(const MeasureFormat &other) :
632         Format(other),
633         cache(other.cache),
634         numberFormat(other.numberFormat),
635         pluralRules(other.pluralRules),
636         width(other.width),
637         listFormatter(NULL) {
638     cache->addRef();
639     numberFormat->addRef();
640     pluralRules->addRef();
641     if (other.listFormatter != NULL) {
642         listFormatter = new ListFormatter(*other.listFormatter);
643     }
644 }
645
646 MeasureFormat &MeasureFormat::operator=(const MeasureFormat &other) {
647     if (this == &other) {
648         return *this;
649     }
650     Format::operator=(other);
651     SharedObject::copyPtr(other.cache, cache);
652     SharedObject::copyPtr(other.numberFormat, numberFormat);
653     SharedObject::copyPtr(other.pluralRules, pluralRules);
654     width = other.width;
655     delete listFormatter;
656     if (other.listFormatter != NULL) {
657         listFormatter = new ListFormatter(*other.listFormatter);
658     } else {
659         listFormatter = NULL;
660     }
661     return *this;
662 }
663
664 MeasureFormat::MeasureFormat() :
665         cache(NULL),
666         numberFormat(NULL),
667         pluralRules(NULL),
668         width(UMEASFMT_WIDTH_SHORT),
669         listFormatter(NULL) {
670 }
671
672 MeasureFormat::~MeasureFormat() {
673     if (cache != NULL) {
674         cache->removeRef();
675     }
676     if (numberFormat != NULL) {
677         numberFormat->removeRef();
678     }
679     if (pluralRules != NULL) {
680         pluralRules->removeRef();
681     }
682     delete listFormatter;
683 }
684
685 UBool MeasureFormat::operator==(const Format &other) const {
686     if (this == &other) { // Same object, equal
687         return TRUE;
688     }
689     if (!Format::operator==(other)) {
690         return FALSE;
691     }
692     const MeasureFormat &rhs = static_cast<const MeasureFormat &>(other);
693
694     // Note: Since the ListFormatter depends only on Locale and width, we
695     // don't have to check it here.
696
697     // differing widths aren't equivalent
698     if (width != rhs.width) {
699         return FALSE;
700     }
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
709             return FALSE;
710         }
711         if (uprv_strcmp(localeId, rhsLocaleId) != 0) {
712             return FALSE;
713         }
714     }
715     // Locales same, check NumberFormat if shared data differs.
716     return (
717             numberFormat == rhs.numberFormat ||
718             **numberFormat == **rhs.numberFormat);
719 }
720
721 Format *MeasureFormat::clone() const {
722     return new MeasureFormat(*this);
723 }
724
725 UnicodeString &MeasureFormat::format(
726         const Formattable &obj,
727         UnicodeString &appendTo,
728         FieldPosition &pos,
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);
737         }
738     }
739     status = U_ILLEGAL_ARGUMENT_ERROR;
740     return appendTo;
741 }
742
743 void MeasureFormat::parseObject(
744         const UnicodeString & /*source*/,
745         Formattable & /*result*/,
746         ParsePosition& /*pos*/) const {
747     return;
748 }
749
750 UnicodeString &MeasureFormat::formatMeasurePerUnit(
751         const Measure &measure,
752         const MeasureUnit &perUnit,
753         UnicodeString &appendTo,
754         FieldPosition &pos,
755         UErrorCode &status) const {
756     if (U_FAILURE(status)) {
757         return appendTo;
758     }
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);
765     }
766     FieldPosition fpos(pos.getField());
767     UnicodeString result;
768     int32_t offset = withPerUnitAndAppend(
769             formatMeasure(
770                     measure, **numberFormat, result, fpos, status),
771             perUnit,
772             appendTo,
773             status);
774     if (U_FAILURE(status)) {
775         return appendTo;
776     }
777     if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
778         pos.setBeginIndex(fpos.getBeginIndex() + offset);
779         pos.setEndIndex(fpos.getEndIndex() + offset);
780     }
781     return appendTo;
782 }
783
784 UnicodeString &MeasureFormat::formatMeasures(
785         const Measure *measures,
786         int32_t measureCount,
787         UnicodeString &appendTo,
788         FieldPosition &pos,
789         UErrorCode &status) const {
790     if (U_FAILURE(status)) {
791         return appendTo;
792     }
793     if (measureCount == 0) {
794         return appendTo;
795     }
796     if (measureCount == 1) {
797         return formatMeasure(measures[0], **numberFormat, appendTo, pos, status);
798     }
799     if (width == UMEASFMT_WIDTH_NUMERIC) {
800         Formattable hms[3];
801         int32_t bitMap = toHMS(measures, measureCount, hms, status);
802         if (bitMap > 0) {
803             return formatNumeric(hms, bitMap, appendTo, status);
804         }
805     }
806     if (pos.getField() != FieldPosition::DONT_CARE) {
807         return formatMeasuresSlowTrack(
808                 measures, measureCount, appendTo, pos, status);
809     }
810     UnicodeString *results = new UnicodeString[measureCount];
811     if (results == NULL) {
812         status = U_MEMORY_ALLOCATION_ERROR;
813         return appendTo;
814     }
815     for (int32_t i = 0; i < measureCount; ++i) {
816         const NumberFormat *nf = cache->getIntegerFormat();
817         if (i == measureCount - 1) {
818             nf = numberFormat->get();
819         }
820         formatMeasure(
821                 measures[i],
822                 *nf,
823                 results[i],
824                 pos,
825                 status);
826     }
827     listFormatter->format(results, measureCount, appendTo, status);
828     delete [] results;
829     return appendTo;
830 }
831
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];
836     if (dnam == NULL) {
837         int32_t fallbackWidth = cache->widthFallback[width];
838         dnam = styleToDnam[fallbackWidth];
839     }
840
841     UnicodeString result;
842     if (dnam == NULL) {
843         result.setToBogus();
844     } else {
845         result.setTo(dnam, -1);
846     }
847     return result;
848 }
849
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)) {
858         return;
859     }
860     const char *name = locale.getName();
861     setLocaleIDs(name, name);
862
863     UnifiedCache::getByLocale(locale, cache, status);
864     if (U_FAILURE(status)) {
865         return;
866     }
867
868     const SharedPluralRules *pr = PluralRules::createSharedInstance(
869             locale, UPLURAL_TYPE_CARDINAL, status);
870     if (U_FAILURE(status)) {
871         return;
872     }
873     SharedObject::copyPtr(pr, pluralRules);
874     pr->removeRef();
875     if (nf.isNull()) {
876         const SharedNumberFormat *shared = NumberFormat::createSharedInstance(
877                 locale, UNUM_DECIMAL, status);
878         if (U_FAILURE(status)) {
879             return;
880         }
881         SharedObject::copyPtr(shared, numberFormat);
882         shared->removeRef();
883     } else {
884         adoptNumberFormat(nf.orphan(), status);
885         if (U_FAILURE(status)) {
886             return;
887         }
888     }
889     width = w;
890     delete listFormatter;
891     listFormatter = ListFormatter::createInstance(
892             locale,
893             listStyles[getRegularWidth(width)],
894             status);
895 }
896
897 void MeasureFormat::adoptNumberFormat(
898         NumberFormat *nfToAdopt, UErrorCode &status) {
899     LocalPointer<NumberFormat> nf(nfToAdopt);
900     if (U_FAILURE(status)) {
901         return;
902     }
903     SharedNumberFormat *shared = new SharedNumberFormat(nf.getAlias());
904     if (shared == NULL) {
905         status = U_MEMORY_ALLOCATION_ERROR;
906         return;
907     }
908     nf.orphan();
909     SharedObject::copyPtr(shared, numberFormat);
910 }
911
912 UBool MeasureFormat::setMeasureFormatLocale(const Locale &locale, UErrorCode &status) {
913     if (U_FAILURE(status) || locale == getLocale(status)) {
914         return FALSE;
915     }
916     initMeasureFormat(locale, width, NULL, status);
917     return U_SUCCESS(status);
918
919
920 const NumberFormat &MeasureFormat::getNumberFormat() const {
921     return **numberFormat;
922 }
923
924 const PluralRules &MeasureFormat::getPluralRules() const {
925     return **pluralRules;
926 }
927
928 Locale MeasureFormat::getLocale(UErrorCode &status) const {
929     return Format::getLocale(ULOC_VALID_LOCALE, status);
930 }
931
932 const char *MeasureFormat::getLocaleID(UErrorCode &status) const {
933     return Format::getLocaleID(ULOC_VALID_LOCALE, status);
934 }
935
936 UnicodeString &MeasureFormat::formatMeasure(
937         const Measure &measure,
938         const NumberFormat &nf,
939         UnicodeString &appendTo,
940         FieldPosition &pos,
941         UErrorCode &status) const {
942     if (U_FAILURE(status)) {
943         return appendTo;
944     }
945     const Formattable& amtNumber = measure.getNumber();
946     const MeasureUnit& amtUnit = measure.getUnit();
947     if (isCurrency(amtUnit)) {
948         UChar isoCode[4];
949         u_charsToUChars(amtUnit.getSubtype(), isoCode, 4);
950         return cache->getCurrencyFormat(width)->format(
951                 new CurrencyAmount(amtNumber, isoCode, status),
952                 appendTo,
953                 pos,
954                 status);
955     }
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);
961 }
962
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)) {
970         return appendTo;
971     }
972     UDate millis = 
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);
976     switch (bitMap) {
977     case 5: // hs
978     case 7: // hms
979         return formatNumeric(
980                 millis,
981                 cache->getNumericDateFormatters()->hourMinuteSecond,
982                 UDAT_SECOND_FIELD,
983                 hms[2],
984                 appendTo,
985                 status);
986         break;
987     case 6: // ms
988         return formatNumeric(
989                 millis,
990                 cache->getNumericDateFormatters()->minuteSecond,
991                 UDAT_SECOND_FIELD,
992                 hms[2],
993                 appendTo,
994                 status);
995         break;
996     case 3: // hm
997         return formatNumeric(
998                 millis,
999                 cache->getNumericDateFormatters()->hourMinute,
1000                 UDAT_MINUTE_FIELD,
1001                 hms[1],
1002                 appendTo,
1003                 status);
1004         break;
1005     default:
1006         status = U_INTERNAL_PROGRAM_ERROR;
1007         return appendTo;
1008         break;
1009     }
1010     return appendTo;
1011 }
1012
1013 static void appendRange(
1014         const UnicodeString &src,
1015         int32_t start,
1016         int32_t end,
1017         UnicodeString &dest) {
1018     dest.append(src, start, end - start);
1019 }
1020
1021 static void appendRange(
1022         const UnicodeString &src,
1023         int32_t end,
1024         UnicodeString &dest) {
1025     dest.append(src, end, src.length() - end);
1026 }
1027
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)) {
1037         return appendTo;
1038     }
1039     // Format the smallest amount with this object's NumberFormat
1040     UnicodeString smallestAmountFormatted;
1041
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
1044     // '0:00:9.3'
1045     FieldPosition intFieldPosition(UNUM_INTEGER_FIELD);
1046     (*numberFormat)->format(
1047             smallestAmount, smallestAmountFormatted, intFieldPosition, status);
1048     if (
1049             intFieldPosition.getBeginIndex() == 0 &&
1050             intFieldPosition.getEndIndex() == 0) {
1051         status = U_INTERNAL_PROGRAM_ERROR;
1052         return appendTo;
1053     }
1054
1055     // Format time. draft becomes something like '5:30:45'
1056     FieldPosition smallestFieldPosition(smallestField);
1057     UnicodeString draft;
1058     dateFmt.format(date, draft, smallestFieldPosition, status);
1059
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);
1068         appendRange(
1069                 smallestAmountFormatted,
1070                 0,
1071                 intFieldPosition.getBeginIndex(),
1072                 appendTo);
1073         appendRange(
1074                 draft,
1075                 smallestFieldPosition.getBeginIndex(),
1076                 smallestFieldPosition.getEndIndex(),
1077                 appendTo);
1078         appendRange(
1079                 smallestAmountFormatted,
1080                 intFieldPosition.getEndIndex(),
1081                 appendTo);
1082         appendRange(
1083                 draft,
1084                 smallestFieldPosition.getEndIndex(),
1085                 appendTo);
1086     } else {
1087         appendTo.append(draft);
1088     }
1089     return appendTo;
1090 }
1091
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];
1099     }
1100     int32_t fallbackWidth = cache->widthFallback[width];
1101     if (fallbackWidth != UMEASFMT_WIDTH_COUNT && unitPatterns[fallbackWidth][index] != NULL) {
1102         return unitPatterns[fallbackWidth][index];
1103     }
1104     return NULL;
1105 }
1106
1107 const SimpleFormatter *MeasureFormat::getFormatter(
1108         const MeasureUnit &unit, UMeasureFormatWidth width, int32_t index,
1109         UErrorCode &errorCode) const {
1110     if (U_FAILURE(errorCode)) {
1111         return NULL;
1112     }
1113     const SimpleFormatter *pattern = getFormatterOrNull(unit, width, index);
1114     if (pattern == NULL) {
1115         errorCode = U_MISSING_RESOURCE_ERROR;
1116     }
1117     return pattern;
1118 }
1119
1120 const SimpleFormatter *MeasureFormat::getPluralFormatter(
1121         const MeasureUnit &unit, UMeasureFormatWidth width, int32_t index,
1122         UErrorCode &errorCode) const {
1123     if (U_FAILURE(errorCode)) {
1124         return NULL;
1125     }
1126     if (index != StandardPlural::OTHER) {
1127         const SimpleFormatter *pattern = getFormatterOrNull(unit, width, index);
1128         if (pattern != NULL) {
1129             return pattern;
1130         }
1131     }
1132     return getFormatter(unit, width, StandardPlural::OTHER, errorCode);
1133 }
1134
1135 const SimpleFormatter *MeasureFormat::getPerFormatter(
1136         UMeasureFormatWidth width,
1137         UErrorCode &status) const {
1138     if (U_FAILURE(status)) {
1139         return NULL;
1140     }
1141     width = getRegularWidth(width);
1142     const SimpleFormatter * perFormatters = cache->perFormatters;
1143     if (perFormatters[width].getArgumentLimit() == 2) {
1144         return &perFormatters[width];
1145     }
1146     int32_t fallbackWidth = cache->widthFallback[width];
1147     if (fallbackWidth != UMEASFMT_WIDTH_COUNT &&
1148             perFormatters[fallbackWidth].getArgumentLimit() == 2) {
1149         return &perFormatters[fallbackWidth];
1150     }
1151     status = U_MISSING_RESOURCE_ERROR;
1152     return NULL;
1153 }
1154
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)) {
1162         return offset;
1163     }
1164     const SimpleFormatter *perUnitFormatter =
1165             getFormatterOrNull(perUnit, width, MeasureFormatCacheData::PER_UNIT_INDEX);
1166     if (perUnitFormatter != NULL) {
1167         const UnicodeString *params[] = {&formatted};
1168         perUnitFormatter->formatAndAppend(
1169                 params,
1170                 UPRV_LENGTHOF(params),
1171                 appendTo,
1172                 &offset,
1173                 1,
1174                 status);
1175         return offset;
1176     }
1177     const SimpleFormatter *perFormatter = getPerFormatter(width, status);
1178     const SimpleFormatter *pattern =
1179             getPluralFormatter(perUnit, width, StandardPlural::ONE, status);
1180     if (U_FAILURE(status)) {
1181         return offset;
1182     }
1183     UnicodeString perUnitString = pattern->getTextWithNoArguments();
1184     perUnitString.trim();
1185     const UnicodeString *params[] = {&formatted, &perUnitString};
1186     perFormatter->formatAndAppend(
1187             params,
1188             UPRV_LENGTHOF(params),
1189             appendTo,
1190             &offset,
1191             1,
1192             status);
1193     return offset;
1194 }
1195
1196 UnicodeString &MeasureFormat::formatMeasuresSlowTrack(
1197         const Measure *measures,
1198         int32_t measureCount,
1199         UnicodeString& appendTo,
1200         FieldPosition& pos,
1201         UErrorCode& status) const {
1202     if (U_FAILURE(status)) {
1203         return appendTo;
1204     }
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();
1213         }
1214         if (fieldPositionFoundIndex == -1) {
1215             formatMeasure(measures[i], *nf, results[i], fpos, status);
1216             if (U_FAILURE(status)) {
1217                 delete [] results;
1218                 return appendTo;
1219             }
1220             if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
1221                 fieldPositionFoundIndex = i;
1222             }
1223         } else {
1224             formatMeasure(measures[i], *nf, results[i], dontCare, status);
1225         }
1226     }
1227     int32_t offset;
1228     listFormatter->format(
1229             results,
1230             measureCount,
1231             appendTo,
1232             fieldPositionFoundIndex,
1233             offset,
1234             status);
1235     if (U_FAILURE(status)) {
1236         delete [] results;
1237         return appendTo;
1238     }
1239     if (offset != -1) {
1240         pos.setBeginIndex(fpos.getBeginIndex() + offset);
1241         pos.setEndIndex(fpos.getEndIndex() + offset);
1242     }
1243     delete [] results;
1244     return appendTo;
1245 }
1246
1247 MeasureFormat* U_EXPORT2 MeasureFormat::createCurrencyFormat(const Locale& locale,
1248                                                    UErrorCode& ec) {
1249     CurrencyFormat* fmt = NULL;
1250     if (U_SUCCESS(ec)) {
1251         fmt = new CurrencyFormat(locale, ec);
1252         if (U_FAILURE(ec)) {
1253             delete fmt;
1254             fmt = NULL;
1255         }
1256     }
1257     return fmt;
1258 }
1259
1260 MeasureFormat* U_EXPORT2 MeasureFormat::createCurrencyFormat(UErrorCode& ec) {
1261     if (U_FAILURE(ec)) {
1262         return NULL;
1263     }
1264     return MeasureFormat::createCurrencyFormat(Locale::getDefault(), ec);
1265 }
1266
1267 U_NAMESPACE_END
1268
1269 #endif /* #if !UCONFIG_NO_FORMATTING */