• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 *******************************************************************************
5 * Copyright (C) 2007-2016, International Business Machines Corporation and
6 * others. All Rights Reserved.
7 *******************************************************************************
8 *
9 * File DTPTNGEN.CPP
10 *
11 *******************************************************************************
12 */
13 
14 #include "unicode/utypes.h"
15 #if !UCONFIG_NO_FORMATTING
16 
17 #include "unicode/datefmt.h"
18 #include "unicode/decimfmt.h"
19 #include "unicode/dtfmtsym.h"
20 #include "unicode/dtptngen.h"
21 #include "unicode/localpointer.h"
22 #include "unicode/simpleformatter.h"
23 #include "unicode/smpdtfmt.h"
24 #include "unicode/udat.h"
25 #include "unicode/udatpg.h"
26 #include "unicode/uniset.h"
27 #include "unicode/uloc.h"
28 #include "unicode/ures.h"
29 #include "unicode/ustring.h"
30 #include "unicode/rep.h"
31 #include "unicode/region.h"
32 #include "cpputils.h"
33 #include "mutex.h"
34 #include "umutex.h"
35 #include "cmemory.h"
36 #include "cstring.h"
37 #include "locbased.h"
38 #include "hash.h"
39 #include "uhash.h"
40 #include "uresimp.h"
41 #include "dtptngen_impl.h"
42 #include "ucln_in.h"
43 #include "charstr.h"
44 #include "uassert.h"
45 
46 #if U_CHARSET_FAMILY==U_EBCDIC_FAMILY
47 /**
48  * If we are on EBCDIC, use an iterator which will
49  * traverse the bundles in ASCII order.
50  */
51 #define U_USE_ASCII_BUNDLE_ITERATOR
52 #define U_SORT_ASCII_BUNDLE_ITERATOR
53 #endif
54 
55 #if defined(U_USE_ASCII_BUNDLE_ITERATOR)
56 
57 #include "unicode/ustring.h"
58 #include "uarrsort.h"
59 
60 struct UResAEntry {
61     UChar *key;
62     UResourceBundle *item;
63 };
64 
65 struct UResourceBundleAIterator {
66     UResourceBundle  *bund;
67     UResAEntry *entries;
68     int32_t num;
69     int32_t cursor;
70 };
71 
72 /* Must be C linkage to pass function pointer to the sort function */
73 
74 U_CDECL_BEGIN
75 
76 static int32_t U_CALLCONV
ures_a_codepointSort(const void * context,const void * left,const void * right)77 ures_a_codepointSort(const void *context, const void *left, const void *right) {
78     //CompareContext *cmp=(CompareContext *)context;
79     return u_strcmp(((const UResAEntry *)left)->key,
80                     ((const UResAEntry *)right)->key);
81 }
82 
83 U_CDECL_END
84 
ures_a_open(UResourceBundleAIterator * aiter,UResourceBundle * bund,UErrorCode * status)85 static void ures_a_open(UResourceBundleAIterator *aiter, UResourceBundle *bund, UErrorCode *status) {
86     if(U_FAILURE(*status)) {
87         return;
88     }
89     aiter->bund = bund;
90     aiter->num = ures_getSize(aiter->bund);
91     aiter->cursor = 0;
92 #if !defined(U_SORT_ASCII_BUNDLE_ITERATOR)
93     aiter->entries = nullptr;
94 #else
95     aiter->entries = (UResAEntry*)uprv_malloc(sizeof(UResAEntry)*aiter->num);
96     for(int i=0;i<aiter->num;i++) {
97         aiter->entries[i].item = ures_getByIndex(aiter->bund, i, nullptr, status);
98         const char *akey = ures_getKey(aiter->entries[i].item);
99         int32_t len = uprv_strlen(akey)+1;
100         aiter->entries[i].key = (UChar*)uprv_malloc(len*sizeof(UChar));
101         u_charsToUChars(akey, aiter->entries[i].key, len);
102     }
103     uprv_sortArray(aiter->entries, aiter->num, sizeof(UResAEntry), ures_a_codepointSort, nullptr, TRUE, status);
104 #endif
105 }
106 
ures_a_close(UResourceBundleAIterator * aiter)107 static void ures_a_close(UResourceBundleAIterator *aiter) {
108 #if defined(U_SORT_ASCII_BUNDLE_ITERATOR)
109     for(int i=0;i<aiter->num;i++) {
110         uprv_free(aiter->entries[i].key);
111         ures_close(aiter->entries[i].item);
112     }
113 #endif
114 }
115 
ures_a_getNextString(UResourceBundleAIterator * aiter,int32_t * len,const char ** key,UErrorCode * err)116 static const UChar *ures_a_getNextString(UResourceBundleAIterator *aiter, int32_t *len, const char **key, UErrorCode *err) {
117 #if !defined(U_SORT_ASCII_BUNDLE_ITERATOR)
118     return ures_getNextString(aiter->bund, len, key, err);
119 #else
120     if(U_FAILURE(*err)) return nullptr;
121     UResourceBundle *item = aiter->entries[aiter->cursor].item;
122     const UChar* ret = ures_getString(item, len, err);
123     *key = ures_getKey(item);
124     aiter->cursor++;
125     return ret;
126 #endif
127 }
128 
129 
130 #endif
131 
132 
133 U_NAMESPACE_BEGIN
134 
135 // *****************************************************************************
136 // class DateTimePatternGenerator
137 // *****************************************************************************
138 static const UChar Canonical_Items[] = {
139     // GyQMwWEDFdaHmsSv
140     CAP_G, LOW_Y, CAP_Q, CAP_M, LOW_W, CAP_W, CAP_E,
141     CAP_D, CAP_F, LOW_D, LOW_A, // The UDATPG_x_FIELD constants and these fields have a different order than in ICU4J
142     CAP_H, LOW_M, LOW_S, CAP_S, LOW_V, 0
143 };
144 
145 static const dtTypeElem dtTypes[] = {
146     // patternChar, field, type, minLen, weight
147     {CAP_G, UDATPG_ERA_FIELD, DT_SHORT, 1, 3,},
148     {CAP_G, UDATPG_ERA_FIELD, DT_LONG,  4, 0},
149     {CAP_G, UDATPG_ERA_FIELD, DT_NARROW, 5, 0},
150 
151     {LOW_Y, UDATPG_YEAR_FIELD, DT_NUMERIC, 1, 20},
152     {CAP_Y, UDATPG_YEAR_FIELD, DT_NUMERIC + DT_DELTA, 1, 20},
153     {LOW_U, UDATPG_YEAR_FIELD, DT_NUMERIC + 2*DT_DELTA, 1, 20},
154     {LOW_R, UDATPG_YEAR_FIELD, DT_NUMERIC + 3*DT_DELTA, 1, 20},
155     {CAP_U, UDATPG_YEAR_FIELD, DT_SHORT, 1, 3},
156     {CAP_U, UDATPG_YEAR_FIELD, DT_LONG, 4, 0},
157     {CAP_U, UDATPG_YEAR_FIELD, DT_NARROW, 5, 0},
158 
159     {CAP_Q, UDATPG_QUARTER_FIELD, DT_NUMERIC, 1, 2},
160     {CAP_Q, UDATPG_QUARTER_FIELD, DT_SHORT, 3, 0},
161     {CAP_Q, UDATPG_QUARTER_FIELD, DT_LONG, 4, 0},
162     {CAP_Q, UDATPG_QUARTER_FIELD, DT_NARROW, 5, 0},
163     {LOW_Q, UDATPG_QUARTER_FIELD, DT_NUMERIC + DT_DELTA, 1, 2},
164     {LOW_Q, UDATPG_QUARTER_FIELD, DT_SHORT - DT_DELTA, 3, 0},
165     {LOW_Q, UDATPG_QUARTER_FIELD, DT_LONG - DT_DELTA, 4, 0},
166     {LOW_Q, UDATPG_QUARTER_FIELD, DT_NARROW - DT_DELTA, 5, 0},
167 
168     {CAP_M, UDATPG_MONTH_FIELD, DT_NUMERIC, 1, 2},
169     {CAP_M, UDATPG_MONTH_FIELD, DT_SHORT, 3, 0},
170     {CAP_M, UDATPG_MONTH_FIELD, DT_LONG, 4, 0},
171     {CAP_M, UDATPG_MONTH_FIELD, DT_NARROW, 5, 0},
172     {CAP_L, UDATPG_MONTH_FIELD, DT_NUMERIC + DT_DELTA, 1, 2},
173     {CAP_L, UDATPG_MONTH_FIELD, DT_SHORT - DT_DELTA, 3, 0},
174     {CAP_L, UDATPG_MONTH_FIELD, DT_LONG - DT_DELTA, 4, 0},
175     {CAP_L, UDATPG_MONTH_FIELD, DT_NARROW - DT_DELTA, 5, 0},
176     {LOW_L, UDATPG_MONTH_FIELD, DT_NUMERIC + DT_DELTA, 1, 1},
177 
178     {LOW_W, UDATPG_WEEK_OF_YEAR_FIELD, DT_NUMERIC, 1, 2},
179 
180     {CAP_W, UDATPG_WEEK_OF_MONTH_FIELD, DT_NUMERIC, 1, 0},
181 
182     {CAP_E, UDATPG_WEEKDAY_FIELD, DT_SHORT, 1, 3},
183     {CAP_E, UDATPG_WEEKDAY_FIELD, DT_LONG, 4, 0},
184     {CAP_E, UDATPG_WEEKDAY_FIELD, DT_NARROW, 5, 0},
185     {CAP_E, UDATPG_WEEKDAY_FIELD, DT_SHORTER, 6, 0},
186     {LOW_C, UDATPG_WEEKDAY_FIELD, DT_NUMERIC + 2*DT_DELTA, 1, 2},
187     {LOW_C, UDATPG_WEEKDAY_FIELD, DT_SHORT - 2*DT_DELTA, 3, 0},
188     {LOW_C, UDATPG_WEEKDAY_FIELD, DT_LONG - 2*DT_DELTA, 4, 0},
189     {LOW_C, UDATPG_WEEKDAY_FIELD, DT_NARROW - 2*DT_DELTA, 5, 0},
190     {LOW_C, UDATPG_WEEKDAY_FIELD, DT_SHORTER - 2*DT_DELTA, 6, 0},
191     {LOW_E, UDATPG_WEEKDAY_FIELD, DT_NUMERIC + DT_DELTA, 1, 2}, // LOW_E is currently not used in CLDR data, should not be canonical
192     {LOW_E, UDATPG_WEEKDAY_FIELD, DT_SHORT - DT_DELTA, 3, 0},
193     {LOW_E, UDATPG_WEEKDAY_FIELD, DT_LONG - DT_DELTA, 4, 0},
194     {LOW_E, UDATPG_WEEKDAY_FIELD, DT_NARROW - DT_DELTA, 5, 0},
195     {LOW_E, UDATPG_WEEKDAY_FIELD, DT_SHORTER - DT_DELTA, 6, 0},
196 
197     {LOW_D, UDATPG_DAY_FIELD, DT_NUMERIC, 1, 2},
198     {LOW_G, UDATPG_DAY_FIELD, DT_NUMERIC + DT_DELTA, 1, 20}, // really internal use, so we don't care
199 
200     {CAP_D, UDATPG_DAY_OF_YEAR_FIELD, DT_NUMERIC, 1, 3},
201 
202     {CAP_F, UDATPG_DAY_OF_WEEK_IN_MONTH_FIELD, DT_NUMERIC, 1, 0},
203 
204     {LOW_A, UDATPG_DAYPERIOD_FIELD, DT_SHORT, 1, 3},
205     {LOW_A, UDATPG_DAYPERIOD_FIELD, DT_LONG, 4, 0},
206     {LOW_A, UDATPG_DAYPERIOD_FIELD, DT_NARROW, 5, 0},
207     {LOW_B, UDATPG_DAYPERIOD_FIELD, DT_SHORT - DT_DELTA, 1, 3},
208     {LOW_B, UDATPG_DAYPERIOD_FIELD, DT_LONG - DT_DELTA, 4, 0},
209     {LOW_B, UDATPG_DAYPERIOD_FIELD, DT_NARROW - DT_DELTA, 5, 0},
210     // b needs to be closer to a than to B, so we make this 3*DT_DELTA
211     {CAP_B, UDATPG_DAYPERIOD_FIELD, DT_SHORT - 3*DT_DELTA, 1, 3},
212     {CAP_B, UDATPG_DAYPERIOD_FIELD, DT_LONG - 3*DT_DELTA, 4, 0},
213     {CAP_B, UDATPG_DAYPERIOD_FIELD, DT_NARROW - 3*DT_DELTA, 5, 0},
214 
215     {CAP_H, UDATPG_HOUR_FIELD, DT_NUMERIC + 10*DT_DELTA, 1, 2}, // 24 hour
216     {LOW_K, UDATPG_HOUR_FIELD, DT_NUMERIC + 11*DT_DELTA, 1, 2}, // 24 hour
217     {LOW_H, UDATPG_HOUR_FIELD, DT_NUMERIC, 1, 2}, // 12 hour
218     {CAP_K, UDATPG_HOUR_FIELD, DT_NUMERIC + DT_DELTA, 1, 2}, // 12 hour
219     // The C code has had versions of the following 3, keep & update. Should not need these, but...
220     // Without these, certain tests using e.g. staticGetSkeleton fail because j/J in patterns
221     // get skipped instead of mapped to the right hour chars, for example in
222     //   DateFormatTest::TestPatternFromSkeleton
223     //   IntlTestDateTimePatternGeneratorAPI:: testStaticGetSkeleton
224     //   DateIntervalFormatTest::testTicket11985
225     // Need to investigate better handling of jJC replacement e.g. in staticGetSkeleton.
226     {CAP_J, UDATPG_HOUR_FIELD, DT_NUMERIC + 5*DT_DELTA, 1, 2}, // 12/24 hour no AM/PM
227     {LOW_J, UDATPG_HOUR_FIELD, DT_NUMERIC + 6*DT_DELTA, 1, 6}, // 12/24 hour
228     {CAP_C, UDATPG_HOUR_FIELD, DT_NUMERIC + 7*DT_DELTA, 1, 6}, // 12/24 hour with preferred dayPeriods for 12
229 
230     {LOW_M, UDATPG_MINUTE_FIELD, DT_NUMERIC, 1, 2},
231 
232     {LOW_S, UDATPG_SECOND_FIELD, DT_NUMERIC, 1, 2},
233     {CAP_A, UDATPG_SECOND_FIELD, DT_NUMERIC + DT_DELTA, 1, 1000},
234 
235     {CAP_S, UDATPG_FRACTIONAL_SECOND_FIELD, DT_NUMERIC, 1, 1000},
236 
237     {LOW_V, UDATPG_ZONE_FIELD, DT_SHORT - 2*DT_DELTA, 1, 0},
238     {LOW_V, UDATPG_ZONE_FIELD, DT_LONG - 2*DT_DELTA, 4, 0},
239     {LOW_Z, UDATPG_ZONE_FIELD, DT_SHORT, 1, 3},
240     {LOW_Z, UDATPG_ZONE_FIELD, DT_LONG, 4, 0},
241     {CAP_Z, UDATPG_ZONE_FIELD, DT_NARROW - DT_DELTA, 1, 3},
242     {CAP_Z, UDATPG_ZONE_FIELD, DT_LONG - DT_DELTA, 4, 0},
243     {CAP_Z, UDATPG_ZONE_FIELD, DT_SHORT - DT_DELTA, 5, 0},
244     {CAP_O, UDATPG_ZONE_FIELD, DT_SHORT - DT_DELTA, 1, 0},
245     {CAP_O, UDATPG_ZONE_FIELD, DT_LONG - DT_DELTA, 4, 0},
246     {CAP_V, UDATPG_ZONE_FIELD, DT_SHORT - DT_DELTA, 1, 0},
247     {CAP_V, UDATPG_ZONE_FIELD, DT_LONG - DT_DELTA, 2, 0},
248     {CAP_V, UDATPG_ZONE_FIELD, DT_LONG-1 - DT_DELTA, 3, 0},
249     {CAP_V, UDATPG_ZONE_FIELD, DT_LONG-2 - DT_DELTA, 4, 0},
250     {CAP_X, UDATPG_ZONE_FIELD, DT_NARROW - DT_DELTA, 1, 0},
251     {CAP_X, UDATPG_ZONE_FIELD, DT_SHORT - DT_DELTA, 2, 0},
252     {CAP_X, UDATPG_ZONE_FIELD, DT_LONG - DT_DELTA, 4, 0},
253     {LOW_X, UDATPG_ZONE_FIELD, DT_NARROW - DT_DELTA, 1, 0},
254     {LOW_X, UDATPG_ZONE_FIELD, DT_SHORT - DT_DELTA, 2, 0},
255     {LOW_X, UDATPG_ZONE_FIELD, DT_LONG - DT_DELTA, 4, 0},
256 
257     {0, UDATPG_FIELD_COUNT, 0, 0, 0} , // last row of dtTypes[]
258  };
259 
260 static const char* const CLDR_FIELD_APPEND[] = {
261     "Era", "Year", "Quarter", "Month", "Week", "*", "Day-Of-Week",
262     "*", "*", "Day", "*", // The UDATPG_x_FIELD constants and these fields have a different order than in ICU4J
263     "Hour", "Minute", "Second", "*", "Timezone"
264 };
265 
266 static const char* const CLDR_FIELD_NAME[UDATPG_FIELD_COUNT] = {
267     "era", "year", "quarter", "month", "week", "weekOfMonth", "weekday",
268     "dayOfYear", "weekdayOfMonth", "day", "dayperiod", // The UDATPG_x_FIELD constants and these fields have a different order than in ICU4J
269     "hour", "minute", "second", "*", "zone"
270 };
271 
272 static const char* const CLDR_FIELD_WIDTH[] = { // [UDATPG_WIDTH_COUNT]
273     "", "-short", "-narrow"
274 };
275 
276 // TODO(ticket:13619): remove when definition uncommented in dtptngen.h.
277 static const int32_t UDATPG_WIDTH_COUNT = UDATPG_NARROW + 1;
278 static constexpr UDateTimePGDisplayWidth UDATPG_WIDTH_APPENDITEM = UDATPG_WIDE;
279 static constexpr int32_t UDATPG_FIELD_KEY_MAX = 24; // max length of CLDR field tag (type + width)
280 
281 // For appendItems
282 static const UChar UDATPG_ItemFormat[]= {0x7B, 0x30, 0x7D, 0x20, 0x251C, 0x7B, 0x32, 0x7D, 0x3A,
283     0x20, 0x7B, 0x31, 0x7D, 0x2524, 0};  // {0} \u251C{2}: {1}\u2524
284 
285 //static const UChar repeatedPatterns[6]={CAP_G, CAP_E, LOW_Z, LOW_V, CAP_Q, 0}; // "GEzvQ"
286 
287 static const char DT_DateTimePatternsTag[]="DateTimePatterns";
288 static const char DT_DateTimeCalendarTag[]="calendar";
289 static const char DT_DateTimeGregorianTag[]="gregorian";
290 static const char DT_DateTimeAppendItemsTag[]="appendItems";
291 static const char DT_DateTimeFieldsTag[]="fields";
292 static const char DT_DateTimeAvailableFormatsTag[]="availableFormats";
293 //static const UnicodeString repeatedPattern=UnicodeString(repeatedPatterns);
294 
295 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(DateTimePatternGenerator)
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(DTSkeletonEnumeration)296 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(DTSkeletonEnumeration)
297 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(DTRedundantEnumeration)
298 
299 DateTimePatternGenerator*  U_EXPORT2
300 DateTimePatternGenerator::createInstance(UErrorCode& status) {
301     return createInstance(Locale::getDefault(), status);
302 }
303 
304 DateTimePatternGenerator* U_EXPORT2
createInstance(const Locale & locale,UErrorCode & status)305 DateTimePatternGenerator::createInstance(const Locale& locale, UErrorCode& status) {
306     if (U_FAILURE(status)) {
307         return nullptr;
308     }
309     LocalPointer<DateTimePatternGenerator> result(
310             new DateTimePatternGenerator(locale, status), status);
311     return U_SUCCESS(status) ? result.orphan() : nullptr;
312 }
313 
314 DateTimePatternGenerator*  U_EXPORT2
createEmptyInstance(UErrorCode & status)315 DateTimePatternGenerator::createEmptyInstance(UErrorCode& status) {
316     if (U_FAILURE(status)) {
317         return nullptr;
318     }
319     LocalPointer<DateTimePatternGenerator> result(
320             new DateTimePatternGenerator(status), status);
321     return U_SUCCESS(status) ? result.orphan() : nullptr;
322 }
323 
DateTimePatternGenerator(UErrorCode & status)324 DateTimePatternGenerator::DateTimePatternGenerator(UErrorCode &status) :
325     skipMatcher(nullptr),
326     fAvailableFormatKeyHash(nullptr),
327     fDefaultHourFormatChar(0),
328     internalErrorCode(U_ZERO_ERROR)
329 {
330     fp = new FormatParser();
331     dtMatcher = new DateTimeMatcher();
332     distanceInfo = new DistanceInfo();
333     patternMap = new PatternMap();
334     if (fp == nullptr || dtMatcher == nullptr || distanceInfo == nullptr || patternMap == nullptr) {
335         internalErrorCode = status = U_MEMORY_ALLOCATION_ERROR;
336     }
337 }
338 
DateTimePatternGenerator(const Locale & locale,UErrorCode & status)339 DateTimePatternGenerator::DateTimePatternGenerator(const Locale& locale, UErrorCode &status) :
340     skipMatcher(nullptr),
341     fAvailableFormatKeyHash(nullptr),
342     fDefaultHourFormatChar(0),
343     internalErrorCode(U_ZERO_ERROR)
344 {
345     fp = new FormatParser();
346     dtMatcher = new DateTimeMatcher();
347     distanceInfo = new DistanceInfo();
348     patternMap = new PatternMap();
349     if (fp == nullptr || dtMatcher == nullptr || distanceInfo == nullptr || patternMap == nullptr) {
350         internalErrorCode = status = U_MEMORY_ALLOCATION_ERROR;
351     }
352     else {
353         initData(locale, status);
354     }
355 }
356 
DateTimePatternGenerator(const DateTimePatternGenerator & other)357 DateTimePatternGenerator::DateTimePatternGenerator(const DateTimePatternGenerator& other) :
358     UObject(),
359     skipMatcher(nullptr),
360     fAvailableFormatKeyHash(nullptr),
361     fDefaultHourFormatChar(0),
362     internalErrorCode(U_ZERO_ERROR)
363 {
364     fp = new FormatParser();
365     dtMatcher = new DateTimeMatcher();
366     distanceInfo = new DistanceInfo();
367     patternMap = new PatternMap();
368     if (fp == nullptr || dtMatcher == nullptr || distanceInfo == nullptr || patternMap == nullptr) {
369         internalErrorCode = U_MEMORY_ALLOCATION_ERROR;
370     }
371     *this=other;
372 }
373 
374 DateTimePatternGenerator&
operator =(const DateTimePatternGenerator & other)375 DateTimePatternGenerator::operator=(const DateTimePatternGenerator& other) {
376     // reflexive case
377     if (&other == this) {
378         return *this;
379     }
380     internalErrorCode = other.internalErrorCode;
381     pLocale = other.pLocale;
382     fDefaultHourFormatChar = other.fDefaultHourFormatChar;
383     *fp = *(other.fp);
384     dtMatcher->copyFrom(other.dtMatcher->skeleton);
385     *distanceInfo = *(other.distanceInfo);
386     dateTimeFormat = other.dateTimeFormat;
387     decimal = other.decimal;
388     // NUL-terminate for the C API.
389     dateTimeFormat.getTerminatedBuffer();
390     decimal.getTerminatedBuffer();
391     delete skipMatcher;
392     if ( other.skipMatcher == nullptr ) {
393         skipMatcher = nullptr;
394     }
395     else {
396         skipMatcher = new DateTimeMatcher(*other.skipMatcher);
397         if (skipMatcher == nullptr)
398         {
399             internalErrorCode = U_MEMORY_ALLOCATION_ERROR;
400             return *this;
401         }
402     }
403     for (int32_t i=0; i< UDATPG_FIELD_COUNT; ++i ) {
404         appendItemFormats[i] = other.appendItemFormats[i];
405         appendItemFormats[i].getTerminatedBuffer(); // NUL-terminate for the C API.
406         for (int32_t j=0; j< UDATPG_WIDTH_COUNT; ++j ) {
407             fieldDisplayNames[i][j] = other.fieldDisplayNames[i][j];
408             fieldDisplayNames[i][j].getTerminatedBuffer(); // NUL-terminate for the C API.
409         }
410     }
411     patternMap->copyFrom(*other.patternMap, internalErrorCode);
412     copyHashtable(other.fAvailableFormatKeyHash, internalErrorCode);
413     return *this;
414 }
415 
416 
417 UBool
operator ==(const DateTimePatternGenerator & other) const418 DateTimePatternGenerator::operator==(const DateTimePatternGenerator& other) const {
419     if (this == &other) {
420         return TRUE;
421     }
422     if ((pLocale==other.pLocale) && (patternMap->equals(*other.patternMap)) &&
423         (dateTimeFormat==other.dateTimeFormat) && (decimal==other.decimal)) {
424         for ( int32_t i=0 ; i<UDATPG_FIELD_COUNT; ++i ) {
425             if (appendItemFormats[i] != other.appendItemFormats[i]) {
426                 return FALSE;
427             }
428             for (int32_t j=0; j< UDATPG_WIDTH_COUNT; ++j ) {
429                 if (fieldDisplayNames[i][j] != other.fieldDisplayNames[i][j]) {
430                     return FALSE;
431                 }
432             }
433         }
434         return TRUE;
435     }
436     else {
437         return FALSE;
438     }
439 }
440 
441 UBool
operator !=(const DateTimePatternGenerator & other) const442 DateTimePatternGenerator::operator!=(const DateTimePatternGenerator& other) const {
443     return  !operator==(other);
444 }
445 
~DateTimePatternGenerator()446 DateTimePatternGenerator::~DateTimePatternGenerator() {
447     if (fAvailableFormatKeyHash!=nullptr) {
448         delete fAvailableFormatKeyHash;
449     }
450 
451     if (fp != nullptr) delete fp;
452     if (dtMatcher != nullptr) delete dtMatcher;
453     if (distanceInfo != nullptr) delete distanceInfo;
454     if (patternMap != nullptr) delete patternMap;
455     if (skipMatcher != nullptr) delete skipMatcher;
456 }
457 
458 namespace {
459 
460 UInitOnce initOnce = U_INITONCE_INITIALIZER;
461 UHashtable *localeToAllowedHourFormatsMap = nullptr;
462 
463 // Value deleter for hashmap.
deleteAllowedHourFormats(void * ptr)464 U_CFUNC void U_CALLCONV deleteAllowedHourFormats(void *ptr) {
465     uprv_free(ptr);
466 }
467 
468 // Close hashmap at cleanup.
allowedHourFormatsCleanup()469 U_CFUNC UBool U_CALLCONV allowedHourFormatsCleanup() {
470     uhash_close(localeToAllowedHourFormatsMap);
471     return TRUE;
472 }
473 
474 enum AllowedHourFormat{
475     ALLOWED_HOUR_FORMAT_UNKNOWN = -1,
476     ALLOWED_HOUR_FORMAT_h,
477     ALLOWED_HOUR_FORMAT_H,
478     ALLOWED_HOUR_FORMAT_K,  // Added ICU-20383, used by JP
479     ALLOWED_HOUR_FORMAT_k,  // Added ICU-20383, not currently used
480     ALLOWED_HOUR_FORMAT_hb,
481     ALLOWED_HOUR_FORMAT_hB,
482     ALLOWED_HOUR_FORMAT_Kb, // Added ICU-20383, not currently used
483     ALLOWED_HOUR_FORMAT_KB, // Added ICU-20383, not currently used
484     // ICU-20383 The following are unlikely and not currently used
485     ALLOWED_HOUR_FORMAT_Hb,
486     ALLOWED_HOUR_FORMAT_HB
487 };
488 
489 }  // namespace
490 
491 void
initData(const Locale & locale,UErrorCode & status)492 DateTimePatternGenerator::initData(const Locale& locale, UErrorCode &status) {
493     //const char *baseLangName = locale.getBaseName(); // unused
494 
495     skipMatcher = nullptr;
496     fAvailableFormatKeyHash=nullptr;
497     addCanonicalItems(status);
498     addICUPatterns(locale, status);
499     addCLDRData(locale, status);
500     setDateTimeFromCalendar(locale, status);
501     setDecimalSymbols(locale, status);
502     umtx_initOnce(initOnce, loadAllowedHourFormatsData, status);
503     getAllowedHourFormats(locale, status);
504     // If any of the above methods failed then the object is in an invalid state.
505     internalErrorCode = status;
506 } // DateTimePatternGenerator::initData
507 
508 namespace {
509 
510 struct AllowedHourFormatsSink : public ResourceSink {
511     // Initialize sub-sinks.
AllowedHourFormatsSink__anon30ff15940211::AllowedHourFormatsSink512     AllowedHourFormatsSink() {}
513     virtual ~AllowedHourFormatsSink();
514 
put__anon30ff15940211::AllowedHourFormatsSink515     virtual void put(const char *key, ResourceValue &value, UBool /*noFallback*/,
516                      UErrorCode &errorCode) {
517         ResourceTable timeData = value.getTable(errorCode);
518         if (U_FAILURE(errorCode)) { return; }
519         for (int32_t i = 0; timeData.getKeyAndValue(i, key, value); ++i) {
520             const char *regionOrLocale = key;
521             ResourceTable formatList = value.getTable(errorCode);
522             if (U_FAILURE(errorCode)) { return; }
523             // below we construct a list[] that has an entry for the "preferred" value at [0],
524             // followed by 1 or more entries for the "allowed" values, terminated with an
525             // entry for ALLOWED_HOUR_FORMAT_UNKNOWN (not included in length below)
526             LocalMemory<int32_t> list;
527             int32_t length = 0;
528             int32_t preferredFormat = ALLOWED_HOUR_FORMAT_UNKNOWN;
529             for (int32_t j = 0; formatList.getKeyAndValue(j, key, value); ++j) {
530                 if (uprv_strcmp(key, "allowed") == 0) {
531                     if (value.getType() == URES_STRING) {
532                         length = 2; // 1 preferred to add later, 1 allowed to add now
533                         if (list.allocateInsteadAndReset(length + 1) == nullptr) {
534                             errorCode = U_MEMORY_ALLOCATION_ERROR;
535                             return;
536                         }
537                         list[1] = getHourFormatFromUnicodeString(value.getUnicodeString(errorCode));
538                     }
539                     else {
540                         ResourceArray allowedFormats = value.getArray(errorCode);
541                         length = allowedFormats.getSize() + 1; // 1 preferred, getSize allowed
542                         if (list.allocateInsteadAndReset(length + 1) == nullptr) {
543                             errorCode = U_MEMORY_ALLOCATION_ERROR;
544                             return;
545                         }
546                         for (int32_t k = 1; k < length; ++k) {
547                             allowedFormats.getValue(k-1, value);
548                             list[k] = getHourFormatFromUnicodeString(value.getUnicodeString(errorCode));
549                         }
550                     }
551                 } else if (uprv_strcmp(key, "preferred") == 0) {
552                     preferredFormat = getHourFormatFromUnicodeString(value.getUnicodeString(errorCode));
553                 }
554             }
555             if (length > 1) {
556                 list[0] = (preferredFormat!=ALLOWED_HOUR_FORMAT_UNKNOWN)? preferredFormat: list[1];
557             } else {
558                 // fallback handling for missing data
559                 length = 2; // 1 preferred, 1 allowed
560                 if (list.allocateInsteadAndReset(length + 1) == nullptr) {
561                     errorCode = U_MEMORY_ALLOCATION_ERROR;
562                     return;
563                 }
564                 list[0] = (preferredFormat!=ALLOWED_HOUR_FORMAT_UNKNOWN)? preferredFormat: ALLOWED_HOUR_FORMAT_H;
565                 list[1] = list[0];
566             }
567             list[length] = ALLOWED_HOUR_FORMAT_UNKNOWN;
568             // At this point list[] will have at least two non-ALLOWED_HOUR_FORMAT_UNKNOWN entries,
569             // followed by ALLOWED_HOUR_FORMAT_UNKNOWN.
570             uhash_put(localeToAllowedHourFormatsMap, const_cast<char *>(regionOrLocale), list.orphan(), &errorCode);
571             if (U_FAILURE(errorCode)) { return; }
572         }
573     }
574 
getHourFormatFromUnicodeString__anon30ff15940211::AllowedHourFormatsSink575     AllowedHourFormat getHourFormatFromUnicodeString(const UnicodeString &s) {
576         if (s.length() == 1) {
577             if (s[0] == LOW_H) { return ALLOWED_HOUR_FORMAT_h; }
578             if (s[0] == CAP_H) { return ALLOWED_HOUR_FORMAT_H; }
579             if (s[0] == CAP_K) { return ALLOWED_HOUR_FORMAT_K; }
580             if (s[0] == LOW_K) { return ALLOWED_HOUR_FORMAT_k; }
581         } else if (s.length() == 2) {
582             if (s[0] == LOW_H && s[1] == LOW_B) { return ALLOWED_HOUR_FORMAT_hb; }
583             if (s[0] == LOW_H && s[1] == CAP_B) { return ALLOWED_HOUR_FORMAT_hB; }
584             if (s[0] == CAP_K && s[1] == LOW_B) { return ALLOWED_HOUR_FORMAT_Kb; }
585             if (s[0] == CAP_K && s[1] == CAP_B) { return ALLOWED_HOUR_FORMAT_KB; }
586             if (s[0] == CAP_H && s[1] == LOW_B) { return ALLOWED_HOUR_FORMAT_Hb; }
587             if (s[0] == CAP_H && s[1] == CAP_B) { return ALLOWED_HOUR_FORMAT_HB; }
588         }
589 
590         return ALLOWED_HOUR_FORMAT_UNKNOWN;
591     }
592 };
593 
594 }  // namespace
595 
~AllowedHourFormatsSink()596 AllowedHourFormatsSink::~AllowedHourFormatsSink() {}
597 
loadAllowedHourFormatsData(UErrorCode & status)598 U_CFUNC void U_CALLCONV DateTimePatternGenerator::loadAllowedHourFormatsData(UErrorCode &status) {
599     if (U_FAILURE(status)) { return; }
600     localeToAllowedHourFormatsMap = uhash_open(
601         uhash_hashChars, uhash_compareChars, nullptr, &status);
602     if (U_FAILURE(status)) { return; }
603 
604     uhash_setValueDeleter(localeToAllowedHourFormatsMap, deleteAllowedHourFormats);
605     ucln_i18n_registerCleanup(UCLN_I18N_ALLOWED_HOUR_FORMATS, allowedHourFormatsCleanup);
606 
607     LocalUResourceBundlePointer rb(ures_openDirect(nullptr, "supplementalData", &status));
608     if (U_FAILURE(status)) { return; }
609 
610     AllowedHourFormatsSink sink;
611     // TODO: Currently in the enumeration each table allocates a new array.
612     // Try to reduce the number of memory allocations. Consider storing a
613     // UVector32 with the concatenation of all of the sub-arrays, put the start index
614     // into the hashmap, store 6 single-value sub-arrays right at the beginning of the
615     // vector (at index enum*2) for easy data sharing, copy sub-arrays into runtime
616     // object. Remember to clean up the vector, too.
617     ures_getAllItemsWithFallback(rb.getAlias(), "timeData", sink, status);
618 }
619 
getAllowedHourFormatsLangCountry(const char * language,const char * country,UErrorCode & status)620 static int32_t* getAllowedHourFormatsLangCountry(const char* language, const char* country, UErrorCode& status) {
621     CharString langCountry;
622     langCountry.append(language, status);
623     langCountry.append('_', status);
624     langCountry.append(country, status);
625 
626     int32_t* allowedFormats;
627     allowedFormats = (int32_t *)uhash_get(localeToAllowedHourFormatsMap, langCountry.data());
628     if (allowedFormats == nullptr) {
629         allowedFormats = (int32_t *)uhash_get(localeToAllowedHourFormatsMap, const_cast<char *>(country));
630     }
631 
632     return allowedFormats;
633 }
634 
getAllowedHourFormats(const Locale & locale,UErrorCode & status)635 void DateTimePatternGenerator::getAllowedHourFormats(const Locale &locale, UErrorCode &status) {
636     if (U_FAILURE(status)) { return; }
637 
638     const char *language = locale.getLanguage();
639     const char *country = locale.getCountry();
640     Locale maxLocale;  // must be here for correct lifetime
641     if (*language == '\0' || *country == '\0') {
642         maxLocale = locale;
643         UErrorCode localStatus = U_ZERO_ERROR;
644         maxLocale.addLikelySubtags(localStatus);
645         if (U_SUCCESS(localStatus)) {
646             language = maxLocale.getLanguage();
647             country = maxLocale.getCountry();
648         }
649     }
650     if (*language == '\0') {
651         // Unexpected, but fail gracefully
652         language = "und";
653     }
654     if (*country == '\0') {
655         country = "001";
656     }
657 
658     int32_t* allowedFormats = getAllowedHourFormatsLangCountry(language, country, status);
659 
660     // We need to check if there is an hour cycle on locale
661     char buffer[8];
662     int32_t count = locale.getKeywordValue("hours", buffer, sizeof(buffer), status);
663 
664     fDefaultHourFormatChar = 0;
665     if (U_SUCCESS(status) && count > 0) {
666         if(uprv_strcmp(buffer, "h24") == 0) {
667             fDefaultHourFormatChar = LOW_K;
668         } else if(uprv_strcmp(buffer, "h23") == 0) {
669             fDefaultHourFormatChar = CAP_H;
670         } else if(uprv_strcmp(buffer, "h12") == 0) {
671             fDefaultHourFormatChar = LOW_H;
672         } else if(uprv_strcmp(buffer, "h11") == 0) {
673             fDefaultHourFormatChar = CAP_K;
674         }
675     }
676 
677     // Check if the region has an alias
678     if (allowedFormats == nullptr) {
679         UErrorCode localStatus = U_ZERO_ERROR;
680         const Region* region = Region::getInstance(country, localStatus);
681         if (U_SUCCESS(localStatus)) {
682             country = region->getRegionCode(); // the real region code
683             allowedFormats = getAllowedHourFormatsLangCountry(language, country, status);
684         }
685     }
686 
687     if (allowedFormats != nullptr) {  // Lookup is successful
688         // Here allowedFormats points to a list consisting of key for preferredFormat,
689         // followed by one or more keys for allowedFormats, then followed by ALLOWED_HOUR_FORMAT_UNKNOWN.
690         if (!fDefaultHourFormatChar) {
691             switch (allowedFormats[0]) {
692                 case ALLOWED_HOUR_FORMAT_h: fDefaultHourFormatChar = LOW_H; break;
693                 case ALLOWED_HOUR_FORMAT_H: fDefaultHourFormatChar = CAP_H; break;
694                 case ALLOWED_HOUR_FORMAT_K: fDefaultHourFormatChar = CAP_K; break;
695                 case ALLOWED_HOUR_FORMAT_k: fDefaultHourFormatChar = LOW_K; break;
696                 default: fDefaultHourFormatChar = CAP_H; break;
697             }
698         }
699 
700         for (int32_t i = 0; i < UPRV_LENGTHOF(fAllowedHourFormats); ++i) {
701             fAllowedHourFormats[i] = allowedFormats[i + 1];
702             if (fAllowedHourFormats[i] == ALLOWED_HOUR_FORMAT_UNKNOWN) {
703                 break;
704             }
705         }
706     } else {  // Lookup failed, twice
707         if (!fDefaultHourFormatChar) {
708             fDefaultHourFormatChar = CAP_H;
709         }
710         fAllowedHourFormats[0] = ALLOWED_HOUR_FORMAT_H;
711         fAllowedHourFormats[1] = ALLOWED_HOUR_FORMAT_UNKNOWN;
712     }
713 }
714 
715 UDateFormatHourCycle
getDefaultHourCycle(UErrorCode & status) const716 DateTimePatternGenerator::getDefaultHourCycle(UErrorCode& status) const {
717     if (U_FAILURE(status)) {
718         return UDAT_HOUR_CYCLE_23;
719     }
720     if (fDefaultHourFormatChar == 0) {
721         // We need to return something, but the caller should ignore it
722         // anyways since the returned status is a failure.
723         status = U_UNSUPPORTED_ERROR;
724         return UDAT_HOUR_CYCLE_23;
725     }
726     switch (fDefaultHourFormatChar) {
727         case CAP_K:
728             return UDAT_HOUR_CYCLE_11;
729         case LOW_H:
730             return UDAT_HOUR_CYCLE_12;
731         case CAP_H:
732             return UDAT_HOUR_CYCLE_23;
733         case LOW_K:
734             return UDAT_HOUR_CYCLE_24;
735         default:
736             UPRV_UNREACHABLE;
737     }
738 }
739 
740 UnicodeString
getSkeleton(const UnicodeString & pattern,UErrorCode &)741 DateTimePatternGenerator::getSkeleton(const UnicodeString& pattern, UErrorCode&
742 /*status*/) {
743     FormatParser fp2;
744     DateTimeMatcher matcher;
745     PtnSkeleton localSkeleton;
746     matcher.set(pattern, &fp2, localSkeleton);
747     return localSkeleton.getSkeleton();
748 }
749 
750 UnicodeString
staticGetSkeleton(const UnicodeString & pattern,UErrorCode &)751 DateTimePatternGenerator::staticGetSkeleton(
752         const UnicodeString& pattern, UErrorCode& /*status*/) {
753     FormatParser fp;
754     DateTimeMatcher matcher;
755     PtnSkeleton localSkeleton;
756     matcher.set(pattern, &fp, localSkeleton);
757     return localSkeleton.getSkeleton();
758 }
759 
760 UnicodeString
getBaseSkeleton(const UnicodeString & pattern,UErrorCode &)761 DateTimePatternGenerator::getBaseSkeleton(const UnicodeString& pattern, UErrorCode& /*status*/) {
762     FormatParser fp2;
763     DateTimeMatcher matcher;
764     PtnSkeleton localSkeleton;
765     matcher.set(pattern, &fp2, localSkeleton);
766     return localSkeleton.getBaseSkeleton();
767 }
768 
769 UnicodeString
staticGetBaseSkeleton(const UnicodeString & pattern,UErrorCode &)770 DateTimePatternGenerator::staticGetBaseSkeleton(
771         const UnicodeString& pattern, UErrorCode& /*status*/) {
772     FormatParser fp;
773     DateTimeMatcher matcher;
774     PtnSkeleton localSkeleton;
775     matcher.set(pattern, &fp, localSkeleton);
776     return localSkeleton.getBaseSkeleton();
777 }
778 
779 void
addICUPatterns(const Locale & locale,UErrorCode & status)780 DateTimePatternGenerator::addICUPatterns(const Locale& locale, UErrorCode& status) {
781     if (U_FAILURE(status)) { return; }
782     UnicodeString dfPattern;
783     UnicodeString conflictingString;
784     DateFormat* df;
785 
786     // Load with ICU patterns
787     for (int32_t i=DateFormat::kFull; i<=DateFormat::kShort; i++) {
788         DateFormat::EStyle style = (DateFormat::EStyle)i;
789         df = DateFormat::createDateInstance(style, locale);
790         SimpleDateFormat* sdf;
791         if (df != nullptr && (sdf = dynamic_cast<SimpleDateFormat*>(df)) != nullptr) {
792             sdf->toPattern(dfPattern);
793             addPattern(dfPattern, FALSE, conflictingString, status);
794         }
795         // TODO Maybe we should return an error when the date format isn't simple.
796         delete df;
797         if (U_FAILURE(status)) { return; }
798 
799         df = DateFormat::createTimeInstance(style, locale);
800         if (df != nullptr && (sdf = dynamic_cast<SimpleDateFormat*>(df)) != nullptr) {
801             sdf->toPattern(dfPattern);
802             addPattern(dfPattern, FALSE, conflictingString, status);
803 
804             // TODO: C++ and Java are inconsistent (see #12568).
805             // C++ uses MEDIUM, but Java uses SHORT.
806             if ( i==DateFormat::kShort && !dfPattern.isEmpty() ) {
807                 consumeShortTimePattern(dfPattern, status);
808             }
809         }
810         // TODO Maybe we should return an error when the date format isn't simple.
811         delete df;
812         if (U_FAILURE(status)) { return; }
813     }
814 }
815 
816 void
hackTimes(const UnicodeString & hackPattern,UErrorCode & status)817 DateTimePatternGenerator::hackTimes(const UnicodeString& hackPattern, UErrorCode& status)  {
818     UnicodeString conflictingString;
819 
820     fp->set(hackPattern);
821     UnicodeString mmss;
822     UBool gotMm=FALSE;
823     for (int32_t i=0; i<fp->itemNumber; ++i) {
824         UnicodeString field = fp->items[i];
825         if ( fp->isQuoteLiteral(field) ) {
826             if ( gotMm ) {
827                UnicodeString quoteLiteral;
828                fp->getQuoteLiteral(quoteLiteral, &i);
829                mmss += quoteLiteral;
830             }
831         }
832         else {
833             if (fp->isPatternSeparator(field) && gotMm) {
834                 mmss+=field;
835             }
836             else {
837                 UChar ch=field.charAt(0);
838                 if (ch==LOW_M) {
839                     gotMm=TRUE;
840                     mmss+=field;
841                 }
842                 else {
843                     if (ch==LOW_S) {
844                         if (!gotMm) {
845                             break;
846                         }
847                         mmss+= field;
848                         addPattern(mmss, FALSE, conflictingString, status);
849                         break;
850                     }
851                     else {
852                         if (gotMm || ch==LOW_Z || ch==CAP_Z || ch==LOW_V || ch==CAP_V) {
853                             break;
854                         }
855                     }
856                 }
857             }
858         }
859     }
860 }
861 
862 #define ULOC_LOCALE_IDENTIFIER_CAPACITY (ULOC_FULLNAME_CAPACITY + 1 + ULOC_KEYWORD_AND_VALUES_CAPACITY)
863 
864 void
getCalendarTypeToUse(const Locale & locale,CharString & destination,UErrorCode & err)865 DateTimePatternGenerator::getCalendarTypeToUse(const Locale& locale, CharString& destination, UErrorCode& err) {
866     destination.clear().append(DT_DateTimeGregorianTag, -1, err); // initial default
867     if ( U_SUCCESS(err) ) {
868         UErrorCode localStatus = U_ZERO_ERROR;
869         char localeWithCalendarKey[ULOC_LOCALE_IDENTIFIER_CAPACITY];
870         // obtain a locale that always has the calendar key value that should be used
871         ures_getFunctionalEquivalent(
872             localeWithCalendarKey,
873             ULOC_LOCALE_IDENTIFIER_CAPACITY,
874             nullptr,
875             "calendar",
876             "calendar",
877             locale.getName(),
878             nullptr,
879             FALSE,
880             &localStatus);
881         localeWithCalendarKey[ULOC_LOCALE_IDENTIFIER_CAPACITY-1] = 0; // ensure null termination
882         // now get the calendar key value from that locale
883         char calendarType[ULOC_KEYWORDS_CAPACITY];
884         int32_t calendarTypeLen = uloc_getKeywordValue(
885             localeWithCalendarKey,
886             "calendar",
887             calendarType,
888             ULOC_KEYWORDS_CAPACITY,
889             &localStatus);
890         // If the input locale was invalid, don't fail with missing resource error, instead
891         // continue with default of Gregorian.
892         if (U_FAILURE(localStatus) && localStatus != U_MISSING_RESOURCE_ERROR) {
893             err = localStatus;
894             return;
895         }
896         if (calendarTypeLen < ULOC_KEYWORDS_CAPACITY) {
897             destination.clear().append(calendarType, -1, err);
898             if (U_FAILURE(err)) { return; }
899         }
900     }
901 }
902 
903 void
consumeShortTimePattern(const UnicodeString & shortTimePattern,UErrorCode & status)904 DateTimePatternGenerator::consumeShortTimePattern(const UnicodeString& shortTimePattern,
905         UErrorCode& status) {
906     if (U_FAILURE(status)) { return; }
907     // ICU-20383 No longer set fDefaultHourFormatChar to the hour format character from
908     // this pattern; instead it is set from localeToAllowedHourFormatsMap which now
909     // includes entries for both preferred and allowed formats.
910 
911     // HACK for hh:ss
912     hackTimes(shortTimePattern, status);
913 }
914 
915 struct DateTimePatternGenerator::AppendItemFormatsSink : public ResourceSink {
916 
917     // Destination for data, modified via setters.
918     DateTimePatternGenerator& dtpg;
919 
AppendItemFormatsSinkDateTimePatternGenerator::AppendItemFormatsSink920     AppendItemFormatsSink(DateTimePatternGenerator& _dtpg) : dtpg(_dtpg) {}
921     virtual ~AppendItemFormatsSink();
922 
putDateTimePatternGenerator::AppendItemFormatsSink923     virtual void put(const char *key, ResourceValue &value, UBool /*noFallback*/,
924             UErrorCode &errorCode) {
925         ResourceTable itemsTable = value.getTable(errorCode);
926         if (U_FAILURE(errorCode)) { return; }
927         for (int32_t i = 0; itemsTable.getKeyAndValue(i, key, value); ++i) {
928             UDateTimePatternField field = dtpg.getAppendFormatNumber(key);
929             if (field == UDATPG_FIELD_COUNT) { continue; }
930             const UnicodeString& valueStr = value.getUnicodeString(errorCode);
931             if (dtpg.getAppendItemFormat(field).isEmpty() && !valueStr.isEmpty()) {
932                 dtpg.setAppendItemFormat(field, valueStr);
933             }
934         }
935     }
936 
fillInMissingDateTimePatternGenerator::AppendItemFormatsSink937     void fillInMissing() {
938         UnicodeString defaultItemFormat(TRUE, UDATPG_ItemFormat, UPRV_LENGTHOF(UDATPG_ItemFormat)-1);  // Read-only alias.
939         for (int32_t i = 0; i < UDATPG_FIELD_COUNT; i++) {
940             UDateTimePatternField field = (UDateTimePatternField)i;
941             if (dtpg.getAppendItemFormat(field).isEmpty()) {
942                 dtpg.setAppendItemFormat(field, defaultItemFormat);
943             }
944         }
945     }
946 };
947 
948 struct DateTimePatternGenerator::AppendItemNamesSink : public ResourceSink {
949 
950     // Destination for data, modified via setters.
951     DateTimePatternGenerator& dtpg;
952 
AppendItemNamesSinkDateTimePatternGenerator::AppendItemNamesSink953     AppendItemNamesSink(DateTimePatternGenerator& _dtpg) : dtpg(_dtpg) {}
954     virtual ~AppendItemNamesSink();
955 
putDateTimePatternGenerator::AppendItemNamesSink956     virtual void put(const char *key, ResourceValue &value, UBool /*noFallback*/,
957             UErrorCode &errorCode) {
958         ResourceTable itemsTable = value.getTable(errorCode);
959         if (U_FAILURE(errorCode)) { return; }
960         for (int32_t i = 0; itemsTable.getKeyAndValue(i, key, value); ++i) {
961             UDateTimePGDisplayWidth width;
962             UDateTimePatternField field = dtpg.getFieldAndWidthIndices(key, &width);
963             if (field == UDATPG_FIELD_COUNT) { continue; }
964             ResourceTable detailsTable = value.getTable(errorCode);
965             if (U_FAILURE(errorCode)) { return; }
966             for (int32_t j = 0; detailsTable.getKeyAndValue(j, key, value); ++j) {
967                 if (uprv_strcmp(key, "dn") != 0) { continue; }
968                 const UnicodeString& valueStr = value.getUnicodeString(errorCode);
969                 if (dtpg.getFieldDisplayName(field,width).isEmpty() && !valueStr.isEmpty()) {
970                     dtpg.setFieldDisplayName(field,width,valueStr);
971                 }
972                 break;
973             }
974         }
975     }
976 
fillInMissingDateTimePatternGenerator::AppendItemNamesSink977     void fillInMissing() {
978         for (int32_t i = 0; i < UDATPG_FIELD_COUNT; i++) {
979             UnicodeString& valueStr = dtpg.getMutableFieldDisplayName((UDateTimePatternField)i, UDATPG_WIDE);
980             if (valueStr.isEmpty()) {
981                 valueStr = CAP_F;
982                 U_ASSERT(i < 20);
983                 if (i < 10) {
984                     // F0, F1, ..., F9
985                     valueStr += (UChar)(i+0x30);
986                 } else {
987                     // F10, F11, ...
988                     valueStr += (UChar)0x31;
989                     valueStr += (UChar)(i-10 + 0x30);
990                 }
991                 // NUL-terminate for the C API.
992                 valueStr.getTerminatedBuffer();
993             }
994             for (int32_t j = 1; j < UDATPG_WIDTH_COUNT; j++) {
995                 UnicodeString& valueStr2 = dtpg.getMutableFieldDisplayName((UDateTimePatternField)i, (UDateTimePGDisplayWidth)j);
996                 if (valueStr2.isEmpty()) {
997                     valueStr2 = dtpg.getFieldDisplayName((UDateTimePatternField)i, (UDateTimePGDisplayWidth)(j-1));
998                 }
999             }
1000         }
1001     }
1002 };
1003 
1004 struct DateTimePatternGenerator::AvailableFormatsSink : public ResourceSink {
1005 
1006     // Destination for data, modified via setters.
1007     DateTimePatternGenerator& dtpg;
1008 
1009     // Temporary variable, required for calling addPatternWithSkeleton.
1010     UnicodeString conflictingPattern;
1011 
AvailableFormatsSinkDateTimePatternGenerator::AvailableFormatsSink1012     AvailableFormatsSink(DateTimePatternGenerator& _dtpg) : dtpg(_dtpg) {}
1013     virtual ~AvailableFormatsSink();
1014 
putDateTimePatternGenerator::AvailableFormatsSink1015     virtual void put(const char *key, ResourceValue &value, UBool isRoot,
1016             UErrorCode &errorCode) {
1017         ResourceTable itemsTable = value.getTable(errorCode);
1018         if (U_FAILURE(errorCode)) { return; }
1019         for (int32_t i = 0; itemsTable.getKeyAndValue(i, key, value); ++i) {
1020             const UnicodeString formatKey(key, -1, US_INV);
1021             if (!dtpg.isAvailableFormatSet(formatKey) ) {
1022                 dtpg.setAvailableFormat(formatKey, errorCode);
1023                 // Add pattern with its associated skeleton. Override any duplicate
1024                 // derived from std patterns, but not a previous availableFormats entry:
1025                 const UnicodeString& formatValue = value.getUnicodeString(errorCode);
1026                 conflictingPattern.remove();
1027                 dtpg.addPatternWithSkeleton(formatValue, &formatKey, !isRoot, conflictingPattern, errorCode);
1028             }
1029         }
1030     }
1031 };
1032 
1033 // Virtual destructors must be defined out of line.
~AppendItemFormatsSink()1034 DateTimePatternGenerator::AppendItemFormatsSink::~AppendItemFormatsSink() {}
~AppendItemNamesSink()1035 DateTimePatternGenerator::AppendItemNamesSink::~AppendItemNamesSink() {}
~AvailableFormatsSink()1036 DateTimePatternGenerator::AvailableFormatsSink::~AvailableFormatsSink() {}
1037 
1038 void
addCLDRData(const Locale & locale,UErrorCode & errorCode)1039 DateTimePatternGenerator::addCLDRData(const Locale& locale, UErrorCode& errorCode) {
1040     if (U_FAILURE(errorCode)) { return; }
1041     UnicodeString rbPattern, value, field;
1042     CharString path;
1043 
1044     LocalUResourceBundlePointer rb(ures_open(nullptr, locale.getName(), &errorCode));
1045     if (U_FAILURE(errorCode)) { return; }
1046 
1047     CharString calendarTypeToUse; // to be filled in with the type to use, if all goes well
1048     getCalendarTypeToUse(locale, calendarTypeToUse, errorCode);
1049     if (U_FAILURE(errorCode)) { return; }
1050 
1051     // Local err to ignore resource not found exceptions
1052     UErrorCode err = U_ZERO_ERROR;
1053 
1054     // Load append item formats.
1055     AppendItemFormatsSink appendItemFormatsSink(*this);
1056     path.clear()
1057         .append(DT_DateTimeCalendarTag, errorCode)
1058         .append('/', errorCode)
1059         .append(calendarTypeToUse, errorCode)
1060         .append('/', errorCode)
1061         .append(DT_DateTimeAppendItemsTag, errorCode); // i.e., calendar/xxx/appendItems
1062     if (U_FAILURE(errorCode)) { return; }
1063     ures_getAllItemsWithFallback(rb.getAlias(), path.data(), appendItemFormatsSink, err);
1064     appendItemFormatsSink.fillInMissing();
1065 
1066     // Load CLDR item names.
1067     err = U_ZERO_ERROR;
1068     AppendItemNamesSink appendItemNamesSink(*this);
1069     ures_getAllItemsWithFallback(rb.getAlias(), DT_DateTimeFieldsTag, appendItemNamesSink, err);
1070     appendItemNamesSink.fillInMissing();
1071 
1072     // Load the available formats from CLDR.
1073     err = U_ZERO_ERROR;
1074     initHashtable(errorCode);
1075     if (U_FAILURE(errorCode)) { return; }
1076     AvailableFormatsSink availableFormatsSink(*this);
1077     path.clear()
1078         .append(DT_DateTimeCalendarTag, errorCode)
1079         .append('/', errorCode)
1080         .append(calendarTypeToUse, errorCode)
1081         .append('/', errorCode)
1082         .append(DT_DateTimeAvailableFormatsTag, errorCode); // i.e., calendar/xxx/availableFormats
1083     if (U_FAILURE(errorCode)) { return; }
1084     ures_getAllItemsWithFallback(rb.getAlias(), path.data(), availableFormatsSink, err);
1085 }
1086 
1087 void
initHashtable(UErrorCode & err)1088 DateTimePatternGenerator::initHashtable(UErrorCode& err) {
1089     if (U_FAILURE(err)) { return; }
1090     if (fAvailableFormatKeyHash!=nullptr) {
1091         return;
1092     }
1093     LocalPointer<Hashtable> hash(new Hashtable(FALSE, err), err);
1094     if (U_SUCCESS(err)) {
1095         fAvailableFormatKeyHash = hash.orphan();
1096     }
1097 }
1098 
1099 void
setAppendItemFormat(UDateTimePatternField field,const UnicodeString & value)1100 DateTimePatternGenerator::setAppendItemFormat(UDateTimePatternField field, const UnicodeString& value) {
1101     appendItemFormats[field] = value;
1102     // NUL-terminate for the C API.
1103     appendItemFormats[field].getTerminatedBuffer();
1104 }
1105 
1106 const UnicodeString&
getAppendItemFormat(UDateTimePatternField field) const1107 DateTimePatternGenerator::getAppendItemFormat(UDateTimePatternField field) const {
1108     return appendItemFormats[field];
1109 }
1110 
1111 void
setAppendItemName(UDateTimePatternField field,const UnicodeString & value)1112 DateTimePatternGenerator::setAppendItemName(UDateTimePatternField field, const UnicodeString& value) {
1113     setFieldDisplayName(field, UDATPG_WIDTH_APPENDITEM, value);
1114 }
1115 
1116 const UnicodeString&
getAppendItemName(UDateTimePatternField field) const1117 DateTimePatternGenerator::getAppendItemName(UDateTimePatternField field) const {
1118     return fieldDisplayNames[field][UDATPG_WIDTH_APPENDITEM];
1119 }
1120 
1121 void
setFieldDisplayName(UDateTimePatternField field,UDateTimePGDisplayWidth width,const UnicodeString & value)1122 DateTimePatternGenerator::setFieldDisplayName(UDateTimePatternField field, UDateTimePGDisplayWidth width, const UnicodeString& value) {
1123     fieldDisplayNames[field][width] = value;
1124     // NUL-terminate for the C API.
1125     fieldDisplayNames[field][width].getTerminatedBuffer();
1126 }
1127 
1128 UnicodeString
getFieldDisplayName(UDateTimePatternField field,UDateTimePGDisplayWidth width) const1129 DateTimePatternGenerator::getFieldDisplayName(UDateTimePatternField field, UDateTimePGDisplayWidth width) const {
1130     return fieldDisplayNames[field][width];
1131 }
1132 
1133 UnicodeString&
getMutableFieldDisplayName(UDateTimePatternField field,UDateTimePGDisplayWidth width)1134 DateTimePatternGenerator::getMutableFieldDisplayName(UDateTimePatternField field, UDateTimePGDisplayWidth width) {
1135     return fieldDisplayNames[field][width];
1136 }
1137 
1138 void
getAppendName(UDateTimePatternField field,UnicodeString & value)1139 DateTimePatternGenerator::getAppendName(UDateTimePatternField field, UnicodeString& value) {
1140     value = SINGLE_QUOTE;
1141     value += fieldDisplayNames[field][UDATPG_WIDTH_APPENDITEM];
1142     value += SINGLE_QUOTE;
1143 }
1144 
1145 UnicodeString
getBestPattern(const UnicodeString & patternForm,UErrorCode & status)1146 DateTimePatternGenerator::getBestPattern(const UnicodeString& patternForm, UErrorCode& status) {
1147     return getBestPattern(patternForm, UDATPG_MATCH_NO_OPTIONS, status);
1148 }
1149 
1150 UnicodeString
getBestPattern(const UnicodeString & patternForm,UDateTimePatternMatchOptions options,UErrorCode & status)1151 DateTimePatternGenerator::getBestPattern(const UnicodeString& patternForm, UDateTimePatternMatchOptions options, UErrorCode& status) {
1152     if (U_FAILURE(status)) {
1153         return UnicodeString();
1154     }
1155     if (U_FAILURE(internalErrorCode)) {
1156         status = internalErrorCode;
1157         return UnicodeString();
1158     }
1159     const UnicodeString *bestPattern = nullptr;
1160     UnicodeString dtFormat;
1161     UnicodeString resultPattern;
1162     int32_t flags = kDTPGNoFlags;
1163 
1164     int32_t dateMask=(1<<UDATPG_DAYPERIOD_FIELD) - 1;
1165     int32_t timeMask=(1<<UDATPG_FIELD_COUNT) - 1 - dateMask;
1166 
1167     // Replace hour metacharacters 'j', 'C' and 'J', set flags as necessary
1168     UnicodeString patternFormMapped = mapSkeletonMetacharacters(patternForm, &flags, status);
1169     if (U_FAILURE(status)) {
1170         return UnicodeString();
1171     }
1172 
1173     resultPattern.remove();
1174     dtMatcher->set(patternFormMapped, fp);
1175     const PtnSkeleton* specifiedSkeleton = nullptr;
1176     bestPattern=getBestRaw(*dtMatcher, -1, distanceInfo, status, &specifiedSkeleton);
1177     if (U_FAILURE(status)) {
1178         return UnicodeString();
1179     }
1180 
1181     if ( distanceInfo->missingFieldMask==0 && distanceInfo->extraFieldMask==0 ) {
1182         resultPattern = adjustFieldTypes(*bestPattern, specifiedSkeleton, flags, options);
1183 
1184         return resultPattern;
1185     }
1186     int32_t neededFields = dtMatcher->getFieldMask();
1187     UnicodeString datePattern=getBestAppending(neededFields & dateMask, flags, status, options);
1188     UnicodeString timePattern=getBestAppending(neededFields & timeMask, flags, status, options);
1189     if (U_FAILURE(status)) {
1190         return UnicodeString();
1191     }
1192     if (datePattern.length()==0) {
1193         if (timePattern.length()==0) {
1194             resultPattern.remove();
1195         }
1196         else {
1197             return timePattern;
1198         }
1199     }
1200     if (timePattern.length()==0) {
1201         return datePattern;
1202     }
1203     resultPattern.remove();
1204     status = U_ZERO_ERROR;
1205     dtFormat=getDateTimeFormat();
1206     SimpleFormatter(dtFormat, 2, 2, status).format(timePattern, datePattern, resultPattern, status);
1207     return resultPattern;
1208 }
1209 
1210 /*
1211  * Map a skeleton that may have metacharacters jJC to one without, by replacing
1212  * the metacharacters with locale-appropriate fields of h/H/k/K and of a/b/B
1213  * (depends on fDefaultHourFormatChar and fAllowedHourFormats being set, which in
1214  * turn depends on initData having been run). This method also updates the flags
1215  * as necessary. Returns the updated skeleton.
1216  */
1217 UnicodeString
mapSkeletonMetacharacters(const UnicodeString & patternForm,int32_t * flags,UErrorCode & status)1218 DateTimePatternGenerator::mapSkeletonMetacharacters(const UnicodeString& patternForm, int32_t* flags, UErrorCode& status) {
1219     UnicodeString patternFormMapped;
1220     patternFormMapped.remove();
1221     UBool inQuoted = FALSE;
1222     int32_t patPos, patLen = patternForm.length();
1223     for (patPos = 0; patPos < patLen; patPos++) {
1224         UChar patChr = patternForm.charAt(patPos);
1225         if (patChr == SINGLE_QUOTE) {
1226             inQuoted = !inQuoted;
1227         } else if (!inQuoted) {
1228             // Handle special mappings for 'j' and 'C' in which fields lengths
1229             // 1,3,5 => hour field length 1
1230             // 2,4,6 => hour field length 2
1231             // 1,2 => abbreviated dayPeriod (field length 1..3)
1232             // 3,4 => long dayPeriod (field length 4)
1233             // 5,6 => narrow dayPeriod (field length 5)
1234             if (patChr == LOW_J || patChr == CAP_C) {
1235                 int32_t extraLen = 0; // 1 less than total field length
1236                 while (patPos+1 < patLen && patternForm.charAt(patPos+1)==patChr) {
1237                     extraLen++;
1238                     patPos++;
1239                 }
1240                 int32_t hourLen = 1 + (extraLen & 1);
1241                 int32_t dayPeriodLen = (extraLen < 2)? 1: 3 + (extraLen >> 1);
1242                 UChar hourChar = LOW_H;
1243                 UChar dayPeriodChar = LOW_A;
1244                 if (patChr == LOW_J) {
1245                     hourChar = fDefaultHourFormatChar;
1246                 } else {
1247                     AllowedHourFormat bestAllowed;
1248                     if (fAllowedHourFormats[0] != ALLOWED_HOUR_FORMAT_UNKNOWN) {
1249                         bestAllowed = (AllowedHourFormat)fAllowedHourFormats[0];
1250                     } else {
1251                         status = U_INVALID_FORMAT_ERROR;
1252                         return UnicodeString();
1253                     }
1254                     if (bestAllowed == ALLOWED_HOUR_FORMAT_H || bestAllowed == ALLOWED_HOUR_FORMAT_HB || bestAllowed == ALLOWED_HOUR_FORMAT_Hb) {
1255                         hourChar = CAP_H;
1256                     } else if (bestAllowed == ALLOWED_HOUR_FORMAT_K || bestAllowed == ALLOWED_HOUR_FORMAT_KB || bestAllowed == ALLOWED_HOUR_FORMAT_Kb) {
1257                         hourChar = CAP_K;
1258                     } else if (bestAllowed == ALLOWED_HOUR_FORMAT_k) {
1259                         hourChar = LOW_K;
1260                     }
1261                     // in #13183 just add b/B to skeleton, no longer need to set special flags
1262                     if (bestAllowed == ALLOWED_HOUR_FORMAT_HB || bestAllowed == ALLOWED_HOUR_FORMAT_hB || bestAllowed == ALLOWED_HOUR_FORMAT_KB) {
1263                         dayPeriodChar = CAP_B;
1264                     } else if (bestAllowed == ALLOWED_HOUR_FORMAT_Hb || bestAllowed == ALLOWED_HOUR_FORMAT_hb || bestAllowed == ALLOWED_HOUR_FORMAT_Kb) {
1265                         dayPeriodChar = LOW_B;
1266                     }
1267                 }
1268                 if (hourChar==CAP_H || hourChar==LOW_K) {
1269                     dayPeriodLen = 0;
1270                 }
1271                 while (dayPeriodLen-- > 0) {
1272                     patternFormMapped.append(dayPeriodChar);
1273                 }
1274                 while (hourLen-- > 0) {
1275                     patternFormMapped.append(hourChar);
1276                 }
1277             } else if (patChr == CAP_J) {
1278                 // Get pattern for skeleton with H, then replace H or k
1279                 // with fDefaultHourFormatChar (if different)
1280                 patternFormMapped.append(CAP_H);
1281                 *flags |= kDTPGSkeletonUsesCapJ;
1282             } else {
1283                 patternFormMapped.append(patChr);
1284             }
1285         }
1286     }
1287     return patternFormMapped;
1288 }
1289 
1290 UnicodeString
replaceFieldTypes(const UnicodeString & pattern,const UnicodeString & skeleton,UErrorCode & status)1291 DateTimePatternGenerator::replaceFieldTypes(const UnicodeString& pattern,
1292                                             const UnicodeString& skeleton,
1293                                             UErrorCode& status) {
1294     return replaceFieldTypes(pattern, skeleton, UDATPG_MATCH_NO_OPTIONS, status);
1295 }
1296 
1297 UnicodeString
replaceFieldTypes(const UnicodeString & pattern,const UnicodeString & skeleton,UDateTimePatternMatchOptions options,UErrorCode & status)1298 DateTimePatternGenerator::replaceFieldTypes(const UnicodeString& pattern,
1299                                             const UnicodeString& skeleton,
1300                                             UDateTimePatternMatchOptions options,
1301                                             UErrorCode& status) {
1302     if (U_FAILURE(status)) {
1303         return UnicodeString();
1304     }
1305     if (U_FAILURE(internalErrorCode)) {
1306         status = internalErrorCode;
1307         return UnicodeString();
1308     }
1309     dtMatcher->set(skeleton, fp);
1310     UnicodeString result = adjustFieldTypes(pattern, nullptr, kDTPGNoFlags, options);
1311     return result;
1312 }
1313 
1314 void
setDecimal(const UnicodeString & newDecimal)1315 DateTimePatternGenerator::setDecimal(const UnicodeString& newDecimal) {
1316     this->decimal = newDecimal;
1317     // NUL-terminate for the C API.
1318     this->decimal.getTerminatedBuffer();
1319 }
1320 
1321 const UnicodeString&
getDecimal() const1322 DateTimePatternGenerator::getDecimal() const {
1323     return decimal;
1324 }
1325 
1326 void
addCanonicalItems(UErrorCode & status)1327 DateTimePatternGenerator::addCanonicalItems(UErrorCode& status) {
1328     if (U_FAILURE(status)) { return; }
1329     UnicodeString  conflictingPattern;
1330 
1331     for (int32_t i=0; i<UDATPG_FIELD_COUNT; i++) {
1332         if (Canonical_Items[i] > 0) {
1333             addPattern(UnicodeString(Canonical_Items[i]), FALSE, conflictingPattern, status);
1334         }
1335         if (U_FAILURE(status)) { return; }
1336     }
1337 }
1338 
1339 void
setDateTimeFormat(const UnicodeString & dtFormat)1340 DateTimePatternGenerator::setDateTimeFormat(const UnicodeString& dtFormat) {
1341     dateTimeFormat = dtFormat;
1342     // NUL-terminate for the C API.
1343     dateTimeFormat.getTerminatedBuffer();
1344 }
1345 
1346 const UnicodeString&
getDateTimeFormat() const1347 DateTimePatternGenerator::getDateTimeFormat() const {
1348     return dateTimeFormat;
1349 }
1350 
1351 void
setDateTimeFromCalendar(const Locale & locale,UErrorCode & status)1352 DateTimePatternGenerator::setDateTimeFromCalendar(const Locale& locale, UErrorCode& status) {
1353     if (U_FAILURE(status)) { return; }
1354 
1355     const UChar *resStr;
1356     int32_t resStrLen = 0;
1357 
1358     LocalPointer<Calendar> fCalendar(Calendar::createInstance(locale, status), status);
1359     if (U_FAILURE(status)) { return; }
1360 
1361     LocalUResourceBundlePointer calData(ures_open(nullptr, locale.getBaseName(), &status));
1362     if (U_FAILURE(status)) { return; }
1363     ures_getByKey(calData.getAlias(), DT_DateTimeCalendarTag, calData.getAlias(), &status);
1364     if (U_FAILURE(status)) { return; }
1365 
1366     LocalUResourceBundlePointer dateTimePatterns;
1367     if (fCalendar->getType() != nullptr && *fCalendar->getType() != '\0'
1368             && uprv_strcmp(fCalendar->getType(), DT_DateTimeGregorianTag) != 0) {
1369         dateTimePatterns.adoptInstead(ures_getByKeyWithFallback(calData.getAlias(), fCalendar->getType(),
1370                                                                 nullptr, &status));
1371         ures_getByKeyWithFallback(dateTimePatterns.getAlias(), DT_DateTimePatternsTag,
1372                                   dateTimePatterns.getAlias(), &status);
1373     }
1374 
1375     if (dateTimePatterns.isNull() || status == U_MISSING_RESOURCE_ERROR) {
1376         status = U_ZERO_ERROR;
1377         dateTimePatterns.adoptInstead(ures_getByKeyWithFallback(calData.getAlias(), DT_DateTimeGregorianTag,
1378                                                                 dateTimePatterns.orphan(), &status));
1379         ures_getByKeyWithFallback(dateTimePatterns.getAlias(), DT_DateTimePatternsTag,
1380                                   dateTimePatterns.getAlias(), &status);
1381     }
1382     if (U_FAILURE(status)) { return; }
1383 
1384     if (ures_getSize(dateTimePatterns.getAlias()) <= DateFormat::kDateTime)
1385     {
1386         status = U_INVALID_FORMAT_ERROR;
1387         return;
1388     }
1389     resStr = ures_getStringByIndex(dateTimePatterns.getAlias(), (int32_t)DateFormat::kDateTime, &resStrLen, &status);
1390     setDateTimeFormat(UnicodeString(TRUE, resStr, resStrLen));
1391 }
1392 
1393 void
setDecimalSymbols(const Locale & locale,UErrorCode & status)1394 DateTimePatternGenerator::setDecimalSymbols(const Locale& locale, UErrorCode& status) {
1395     DecimalFormatSymbols dfs = DecimalFormatSymbols(locale, status);
1396     if(U_SUCCESS(status)) {
1397         decimal = dfs.getSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol);
1398         // NUL-terminate for the C API.
1399         decimal.getTerminatedBuffer();
1400     }
1401 }
1402 
1403 UDateTimePatternConflict
addPattern(const UnicodeString & pattern,UBool override,UnicodeString & conflictingPattern,UErrorCode & status)1404 DateTimePatternGenerator::addPattern(
1405     const UnicodeString& pattern,
1406     UBool override,
1407     UnicodeString &conflictingPattern,
1408     UErrorCode& status)
1409 {
1410     if (U_FAILURE(internalErrorCode)) {
1411         status = internalErrorCode;
1412         return UDATPG_NO_CONFLICT;
1413     }
1414 
1415     return addPatternWithSkeleton(pattern, nullptr, override, conflictingPattern, status);
1416 }
1417 
1418 // For DateTimePatternGenerator::addPatternWithSkeleton -
1419 // If skeletonToUse is specified, then an availableFormats entry is being added. In this case:
1420 // 1. We pass that skeleton to matcher.set instead of having it derive a skeleton from the pattern.
1421 // 2. If the new entry's skeleton or basePattern does match an existing entry but that entry also had a skeleton specified
1422 // (i.e. it was also from availableFormats), then the new entry does not override it regardless of the value of the override
1423 // parameter. This prevents later availableFormats entries from a parent locale overriding earlier ones from the actual
1424 // specified locale. However, availableFormats entries *should* override entries with matching skeleton whose skeleton was
1425 // derived (i.e. entries derived from the standard date/time patters for the specified locale).
1426 // 3. When adding the pattern (patternMap->add), we set a new boolean to indicate that the added entry had a
1427 // specified skeleton (which sets a new field in the PtnElem in the PatternMap).
1428 UDateTimePatternConflict
addPatternWithSkeleton(const UnicodeString & pattern,const UnicodeString * skeletonToUse,UBool override,UnicodeString & conflictingPattern,UErrorCode & status)1429 DateTimePatternGenerator::addPatternWithSkeleton(
1430     const UnicodeString& pattern,
1431     const UnicodeString* skeletonToUse,
1432     UBool override,
1433     UnicodeString& conflictingPattern,
1434     UErrorCode& status)
1435 {
1436     if (U_FAILURE(internalErrorCode)) {
1437         status = internalErrorCode;
1438         return UDATPG_NO_CONFLICT;
1439     }
1440 
1441     UnicodeString basePattern;
1442     PtnSkeleton   skeleton;
1443     UDateTimePatternConflict conflictingStatus = UDATPG_NO_CONFLICT;
1444 
1445     DateTimeMatcher matcher;
1446     if ( skeletonToUse == nullptr ) {
1447         matcher.set(pattern, fp, skeleton);
1448         matcher.getBasePattern(basePattern);
1449     } else {
1450         matcher.set(*skeletonToUse, fp, skeleton); // no longer trims skeleton fields to max len 3, per #7930
1451         matcher.getBasePattern(basePattern); // or perhaps instead: basePattern = *skeletonToUse;
1452     }
1453     // We only care about base conflicts - and replacing the pattern associated with a base - if:
1454     // 1. the conflicting previous base pattern did *not* have an explicit skeleton; in that case the previous
1455     // base + pattern combination was derived from either (a) a canonical item, (b) a standard format, or
1456     // (c) a pattern specified programmatically with a previous call to addPattern (which would only happen
1457     // if we are getting here from a subsequent call to addPattern).
1458     // 2. a skeleton is specified for the current pattern, but override=false; in that case we are checking
1459     // availableFormats items from root, which should not override any previous entry with the same base.
1460     UBool entryHadSpecifiedSkeleton;
1461     const UnicodeString *duplicatePattern = patternMap->getPatternFromBasePattern(basePattern, entryHadSpecifiedSkeleton);
1462     if (duplicatePattern != nullptr && (!entryHadSpecifiedSkeleton || (skeletonToUse != nullptr && !override))) {
1463         conflictingStatus = UDATPG_BASE_CONFLICT;
1464         conflictingPattern = *duplicatePattern;
1465         if (!override) {
1466             return conflictingStatus;
1467         }
1468     }
1469     // The only time we get here with override=true and skeletonToUse!=null is when adding availableFormats
1470     // items from CLDR data. In that case, we don't want an item from a parent locale to replace an item with
1471     // same skeleton from the specified locale, so skip the current item if skeletonWasSpecified is true for
1472     // the previously-specified conflicting item.
1473     const PtnSkeleton* entrySpecifiedSkeleton = nullptr;
1474     duplicatePattern = patternMap->getPatternFromSkeleton(skeleton, &entrySpecifiedSkeleton);
1475     if (duplicatePattern != nullptr ) {
1476         conflictingStatus = UDATPG_CONFLICT;
1477         conflictingPattern = *duplicatePattern;
1478         if (!override || (skeletonToUse != nullptr && entrySpecifiedSkeleton != nullptr)) {
1479             return conflictingStatus;
1480         }
1481     }
1482     patternMap->add(basePattern, skeleton, pattern, skeletonToUse != nullptr, status);
1483     if(U_FAILURE(status)) {
1484         return conflictingStatus;
1485     }
1486 
1487     return UDATPG_NO_CONFLICT;
1488 }
1489 
1490 
1491 UDateTimePatternField
getAppendFormatNumber(const char * field) const1492 DateTimePatternGenerator::getAppendFormatNumber(const char* field) const {
1493     for (int32_t i=0; i<UDATPG_FIELD_COUNT; ++i ) {
1494         if (uprv_strcmp(CLDR_FIELD_APPEND[i], field)==0) {
1495             return (UDateTimePatternField)i;
1496         }
1497     }
1498     return UDATPG_FIELD_COUNT;
1499 }
1500 
1501 UDateTimePatternField
getFieldAndWidthIndices(const char * key,UDateTimePGDisplayWidth * widthP) const1502 DateTimePatternGenerator::getFieldAndWidthIndices(const char* key, UDateTimePGDisplayWidth* widthP) const {
1503     char cldrFieldKey[UDATPG_FIELD_KEY_MAX + 1];
1504     uprv_strncpy(cldrFieldKey, key, UDATPG_FIELD_KEY_MAX);
1505     cldrFieldKey[UDATPG_FIELD_KEY_MAX]=0; // ensure termination
1506     *widthP = UDATPG_WIDE;
1507     char* hyphenPtr = uprv_strchr(cldrFieldKey, '-');
1508     if (hyphenPtr) {
1509         for (int32_t i=UDATPG_WIDTH_COUNT-1; i>0; --i) {
1510             if (uprv_strcmp(CLDR_FIELD_WIDTH[i], hyphenPtr)==0) {
1511                 *widthP=(UDateTimePGDisplayWidth)i;
1512                 break;
1513             }
1514         }
1515         *hyphenPtr = 0; // now delete width portion of key
1516     }
1517     for (int32_t i=0; i<UDATPG_FIELD_COUNT; ++i ) {
1518         if (uprv_strcmp(CLDR_FIELD_NAME[i],cldrFieldKey)==0) {
1519             return (UDateTimePatternField)i;
1520         }
1521     }
1522     return UDATPG_FIELD_COUNT;
1523 }
1524 
1525 const UnicodeString*
getBestRaw(DateTimeMatcher & source,int32_t includeMask,DistanceInfo * missingFields,UErrorCode & status,const PtnSkeleton ** specifiedSkeletonPtr)1526 DateTimePatternGenerator::getBestRaw(DateTimeMatcher& source,
1527                                      int32_t includeMask,
1528                                      DistanceInfo* missingFields,
1529                                      UErrorCode &status,
1530                                      const PtnSkeleton** specifiedSkeletonPtr) {
1531     int32_t bestDistance = 0x7fffffff;
1532     int32_t bestMissingFieldMask = -1;
1533     DistanceInfo tempInfo;
1534     const UnicodeString *bestPattern=nullptr;
1535     const PtnSkeleton* specifiedSkeleton=nullptr;
1536 
1537     PatternMapIterator it(status);
1538     if (U_FAILURE(status)) { return nullptr; }
1539 
1540     for (it.set(*patternMap); it.hasNext(); ) {
1541         DateTimeMatcher trial = it.next();
1542         if (trial.equals(skipMatcher)) {
1543             continue;
1544         }
1545         int32_t distance=source.getDistance(trial, includeMask, tempInfo);
1546         // Because we iterate over a map the order is undefined. Can change between implementations,
1547         // versions, and will very likely be different between Java and C/C++.
1548         // So if we have patterns with the same distance we also look at the missingFieldMask,
1549         // and we favour the smallest one. Because the field is a bitmask this technically means we
1550         // favour differences in the "least significant fields". For example we prefer the one with differences
1551         // in seconds field vs one with difference in the hours field.
1552         if (distance<bestDistance || (distance==bestDistance && bestMissingFieldMask<tempInfo.missingFieldMask)) {
1553             bestDistance=distance;
1554             bestMissingFieldMask=tempInfo.missingFieldMask;
1555             bestPattern=patternMap->getPatternFromSkeleton(*trial.getSkeletonPtr(), &specifiedSkeleton);
1556             missingFields->setTo(tempInfo);
1557             if (distance==0) {
1558                 break;
1559             }
1560         }
1561     }
1562 
1563     // If the best raw match had a specified skeleton and that skeleton was requested by the caller,
1564     // then return it too. This generally happens when the caller needs to pass that skeleton
1565     // through to adjustFieldTypes so the latter can do a better job.
1566     if (bestPattern && specifiedSkeletonPtr) {
1567         *specifiedSkeletonPtr = specifiedSkeleton;
1568     }
1569     return bestPattern;
1570 }
1571 
1572 UnicodeString
adjustFieldTypes(const UnicodeString & pattern,const PtnSkeleton * specifiedSkeleton,int32_t flags,UDateTimePatternMatchOptions options)1573 DateTimePatternGenerator::adjustFieldTypes(const UnicodeString& pattern,
1574                                            const PtnSkeleton* specifiedSkeleton,
1575                                            int32_t flags,
1576                                            UDateTimePatternMatchOptions options) {
1577     UnicodeString newPattern;
1578     fp->set(pattern);
1579     for (int32_t i=0; i < fp->itemNumber; i++) {
1580         UnicodeString field = fp->items[i];
1581         if ( fp->isQuoteLiteral(field) ) {
1582 
1583             UnicodeString quoteLiteral;
1584             fp->getQuoteLiteral(quoteLiteral, &i);
1585             newPattern += quoteLiteral;
1586         }
1587         else {
1588             if (fp->isPatternSeparator(field)) {
1589                 newPattern+=field;
1590                 continue;
1591             }
1592             int32_t canonicalIndex = fp->getCanonicalIndex(field);
1593             if (canonicalIndex < 0) {
1594                 newPattern+=field;
1595                 continue;  // don't adjust
1596             }
1597             const dtTypeElem *row = &dtTypes[canonicalIndex];
1598             int32_t typeValue = row->field;
1599 
1600             // handle day periods - with #13183, no longer need special handling here, integrated with normal types
1601 
1602             if ((flags & kDTPGFixFractionalSeconds) != 0 && typeValue == UDATPG_SECOND_FIELD) {
1603                 field += decimal;
1604                 dtMatcher->skeleton.original.appendFieldTo(UDATPG_FRACTIONAL_SECOND_FIELD, field);
1605             } else if (dtMatcher->skeleton.type[typeValue]!=0) {
1606                     // Here:
1607                     // - "reqField" is the field from the originally requested skeleton after replacement
1608                     // of metacharacters 'j', 'C' and 'J', with length "reqFieldLen".
1609                     // - "field" is the field from the found pattern.
1610                     //
1611                     // The adjusted field should consist of characters from the originally requested
1612                     // skeleton, except in the case of UDATPG_MONTH_FIELD or
1613                     // UDATPG_WEEKDAY_FIELD or UDATPG_YEAR_FIELD, in which case it should consist
1614                     // of characters from the found pattern. In some cases of UDATPG_HOUR_FIELD,
1615                     // there is adjustment following the "defaultHourFormatChar". There is explanation
1616                     // how it is done below.
1617                     //
1618                     // The length of the adjusted field (adjFieldLen) should match that in the originally
1619                     // requested skeleton, except that in the following cases the length of the adjusted field
1620                     // should match that in the found pattern (i.e. the length of this pattern field should
1621                     // not be adjusted):
1622                     // 1. typeValue is UDATPG_HOUR_FIELD/MINUTE/SECOND and the corresponding bit in options is
1623                     //    not set (ticket #7180). Note, we may want to implement a similar change for other
1624                     //    numeric fields (MM, dd, etc.) so the default behavior is to get locale preference for
1625                     //    field length, but options bits can be used to override this.
1626                     // 2. There is a specified skeleton for the found pattern and one of the following is true:
1627                     //    a) The length of the field in the skeleton (skelFieldLen) is equal to reqFieldLen.
1628                     //    b) The pattern field is numeric and the skeleton field is not, or vice versa.
1629 
1630                     UChar reqFieldChar = dtMatcher->skeleton.original.getFieldChar(typeValue);
1631                     int32_t reqFieldLen = dtMatcher->skeleton.original.getFieldLength(typeValue);
1632                     if (reqFieldChar == CAP_E && reqFieldLen < 3)
1633                         reqFieldLen = 3; // 1-3 for E are equivalent to 3 for c,e
1634                     int32_t adjFieldLen = reqFieldLen;
1635                     if ( (typeValue==UDATPG_HOUR_FIELD && (options & UDATPG_MATCH_HOUR_FIELD_LENGTH)==0) ||
1636                          (typeValue==UDATPG_MINUTE_FIELD && (options & UDATPG_MATCH_MINUTE_FIELD_LENGTH)==0) ||
1637                          (typeValue==UDATPG_SECOND_FIELD && (options & UDATPG_MATCH_SECOND_FIELD_LENGTH)==0) ) {
1638                          adjFieldLen = field.length();
1639                     } else if (specifiedSkeleton) {
1640                         int32_t skelFieldLen = specifiedSkeleton->original.getFieldLength(typeValue);
1641                         UBool patFieldIsNumeric = (row->type > 0);
1642                         UBool skelFieldIsNumeric = (specifiedSkeleton->type[typeValue] > 0);
1643                         if (skelFieldLen == reqFieldLen || (patFieldIsNumeric && !skelFieldIsNumeric) || (skelFieldIsNumeric && !patFieldIsNumeric)) {
1644                             // don't adjust the field length in the found pattern
1645                             adjFieldLen = field.length();
1646                         }
1647                     }
1648                     UChar c = (typeValue!= UDATPG_HOUR_FIELD
1649                             && typeValue!= UDATPG_MONTH_FIELD
1650                             && typeValue!= UDATPG_WEEKDAY_FIELD
1651                             && (typeValue!= UDATPG_YEAR_FIELD || reqFieldChar==CAP_Y))
1652                             ? reqFieldChar
1653                             : field.charAt(0);
1654                     if (typeValue == UDATPG_HOUR_FIELD && fDefaultHourFormatChar != 0) {
1655                         // The adjustment here is required to match spec (https://www.unicode.org/reports/tr35/tr35-dates.html#dfst-hour).
1656                         // It is necessary to match the hour-cycle preferred by the Locale.
1657                         // Given that, we need to do the following adjustments:
1658                         // 1. When hour-cycle is h11 it should replace 'h' by 'K'.
1659                         // 2. When hour-cycle is h23 it should replace 'H' by 'k'.
1660                         // 3. When hour-cycle is h24 it should replace 'k' by 'H'.
1661                         // 4. When hour-cycle is h12 it should replace 'K' by 'h'.
1662 
1663                         if ((flags & kDTPGSkeletonUsesCapJ) != 0 || reqFieldChar == fDefaultHourFormatChar) {
1664                             c = fDefaultHourFormatChar;
1665                         } else if (reqFieldChar == LOW_H && fDefaultHourFormatChar == CAP_K) {
1666                             c = CAP_K;
1667                         } else if (reqFieldChar == CAP_H && fDefaultHourFormatChar == LOW_K) {
1668                             c = LOW_K;
1669                         } else if (reqFieldChar == LOW_K && fDefaultHourFormatChar == CAP_H) {
1670                             c = CAP_H;
1671                         } else if (reqFieldChar == CAP_K && fDefaultHourFormatChar == LOW_H) {
1672                             c = LOW_H;
1673                         }
1674                     }
1675 
1676                     field.remove();
1677                     for (int32_t j=adjFieldLen; j>0; --j) {
1678                         field += c;
1679                     }
1680             }
1681             newPattern+=field;
1682         }
1683     }
1684     return newPattern;
1685 }
1686 
1687 UnicodeString
getBestAppending(int32_t missingFields,int32_t flags,UErrorCode & status,UDateTimePatternMatchOptions options)1688 DateTimePatternGenerator::getBestAppending(int32_t missingFields, int32_t flags, UErrorCode &status, UDateTimePatternMatchOptions options) {
1689     if (U_FAILURE(status)) {
1690         return UnicodeString();
1691     }
1692     UnicodeString  resultPattern, tempPattern;
1693     const UnicodeString* tempPatternPtr;
1694     int32_t lastMissingFieldMask=0;
1695     if (missingFields!=0) {
1696         resultPattern=UnicodeString();
1697         const PtnSkeleton* specifiedSkeleton=nullptr;
1698         tempPatternPtr = getBestRaw(*dtMatcher, missingFields, distanceInfo, status, &specifiedSkeleton);
1699         if (U_FAILURE(status)) {
1700             return UnicodeString();
1701         }
1702         tempPattern = *tempPatternPtr;
1703         resultPattern = adjustFieldTypes(tempPattern, specifiedSkeleton, flags, options);
1704         if ( distanceInfo->missingFieldMask==0 ) {
1705             return resultPattern;
1706         }
1707         while (distanceInfo->missingFieldMask!=0) { // precondition: EVERY single field must work!
1708             if ( lastMissingFieldMask == distanceInfo->missingFieldMask ) {
1709                 break;  // cannot find the proper missing field
1710             }
1711             if (((distanceInfo->missingFieldMask & UDATPG_SECOND_AND_FRACTIONAL_MASK)==UDATPG_FRACTIONAL_MASK) &&
1712                 ((missingFields & UDATPG_SECOND_AND_FRACTIONAL_MASK) == UDATPG_SECOND_AND_FRACTIONAL_MASK)) {
1713                 resultPattern = adjustFieldTypes(resultPattern, specifiedSkeleton, flags | kDTPGFixFractionalSeconds, options);
1714                 distanceInfo->missingFieldMask &= ~UDATPG_FRACTIONAL_MASK;
1715                 continue;
1716             }
1717             int32_t startingMask = distanceInfo->missingFieldMask;
1718             tempPatternPtr = getBestRaw(*dtMatcher, distanceInfo->missingFieldMask, distanceInfo, status, &specifiedSkeleton);
1719             if (U_FAILURE(status)) {
1720                 return UnicodeString();
1721             }
1722             tempPattern = *tempPatternPtr;
1723             tempPattern = adjustFieldTypes(tempPattern, specifiedSkeleton, flags, options);
1724             int32_t foundMask=startingMask& ~distanceInfo->missingFieldMask;
1725             int32_t topField=getTopBitNumber(foundMask);
1726 
1727             if (appendItemFormats[topField].length() != 0) {
1728                 UnicodeString appendName;
1729                 getAppendName((UDateTimePatternField)topField, appendName);
1730                 const UnicodeString *values[3] = {
1731                     &resultPattern,
1732                     &tempPattern,
1733                     &appendName
1734                 };
1735                 SimpleFormatter(appendItemFormats[topField], 2, 3, status).
1736                     formatAndReplace(values, 3, resultPattern, nullptr, 0, status);
1737             }
1738             lastMissingFieldMask = distanceInfo->missingFieldMask;
1739         }
1740     }
1741     return resultPattern;
1742 }
1743 
1744 int32_t
getTopBitNumber(int32_t foundMask) const1745 DateTimePatternGenerator::getTopBitNumber(int32_t foundMask) const {
1746     if ( foundMask==0 ) {
1747         return 0;
1748     }
1749     int32_t i=0;
1750     while (foundMask!=0) {
1751         foundMask >>=1;
1752         ++i;
1753     }
1754     if (i-1 >UDATPG_ZONE_FIELD) {
1755         return UDATPG_ZONE_FIELD;
1756     }
1757     else
1758         return i-1;
1759 }
1760 
1761 void
setAvailableFormat(const UnicodeString & key,UErrorCode & err)1762 DateTimePatternGenerator::setAvailableFormat(const UnicodeString &key, UErrorCode& err)
1763 {
1764     fAvailableFormatKeyHash->puti(key, 1, err);
1765 }
1766 
1767 UBool
isAvailableFormatSet(const UnicodeString & key) const1768 DateTimePatternGenerator::isAvailableFormatSet(const UnicodeString &key) const {
1769     return (UBool)(fAvailableFormatKeyHash->geti(key) == 1);
1770 }
1771 
1772 void
copyHashtable(Hashtable * other,UErrorCode & status)1773 DateTimePatternGenerator::copyHashtable(Hashtable *other, UErrorCode &status) {
1774     if (other == nullptr || U_FAILURE(status)) {
1775         return;
1776     }
1777     if (fAvailableFormatKeyHash != nullptr) {
1778         delete fAvailableFormatKeyHash;
1779         fAvailableFormatKeyHash = nullptr;
1780     }
1781     initHashtable(status);
1782     if(U_FAILURE(status)){
1783         return;
1784     }
1785     int32_t pos = UHASH_FIRST;
1786     const UHashElement* elem = nullptr;
1787     // walk through the hash table and create a deep clone
1788     while((elem = other->nextElement(pos))!= nullptr){
1789         const UHashTok otherKeyTok = elem->key;
1790         UnicodeString* otherKey = (UnicodeString*)otherKeyTok.pointer;
1791         fAvailableFormatKeyHash->puti(*otherKey, 1, status);
1792         if(U_FAILURE(status)){
1793             return;
1794         }
1795     }
1796 }
1797 
1798 StringEnumeration*
getSkeletons(UErrorCode & status) const1799 DateTimePatternGenerator::getSkeletons(UErrorCode& status) const {
1800     if (U_FAILURE(status)) {
1801         return nullptr;
1802     }
1803     if (U_FAILURE(internalErrorCode)) {
1804         status = internalErrorCode;
1805         return nullptr;
1806     }
1807     LocalPointer<StringEnumeration> skeletonEnumerator(
1808         new DTSkeletonEnumeration(*patternMap, DT_SKELETON, status), status);
1809 
1810     return U_SUCCESS(status) ? skeletonEnumerator.orphan() : nullptr;
1811 }
1812 
1813 const UnicodeString&
getPatternForSkeleton(const UnicodeString & skeleton) const1814 DateTimePatternGenerator::getPatternForSkeleton(const UnicodeString& skeleton) const {
1815     PtnElem *curElem;
1816 
1817     if (skeleton.length() ==0) {
1818         return emptyString;
1819     }
1820     curElem = patternMap->getHeader(skeleton.charAt(0));
1821     while ( curElem != nullptr ) {
1822         if ( curElem->skeleton->getSkeleton()==skeleton ) {
1823             return curElem->pattern;
1824         }
1825         curElem = curElem->next.getAlias();
1826     }
1827     return emptyString;
1828 }
1829 
1830 StringEnumeration*
getBaseSkeletons(UErrorCode & status) const1831 DateTimePatternGenerator::getBaseSkeletons(UErrorCode& status) const {
1832     if (U_FAILURE(status)) {
1833         return nullptr;
1834     }
1835     if (U_FAILURE(internalErrorCode)) {
1836         status = internalErrorCode;
1837         return nullptr;
1838     }
1839     LocalPointer<StringEnumeration> baseSkeletonEnumerator(
1840         new DTSkeletonEnumeration(*patternMap, DT_BASESKELETON, status), status);
1841 
1842     return U_SUCCESS(status) ? baseSkeletonEnumerator.orphan() : nullptr;
1843 }
1844 
1845 StringEnumeration*
getRedundants(UErrorCode & status)1846 DateTimePatternGenerator::getRedundants(UErrorCode& status) {
1847     if (U_FAILURE(status)) { return nullptr; }
1848     if (U_FAILURE(internalErrorCode)) {
1849         status = internalErrorCode;
1850         return nullptr;
1851     }
1852     LocalPointer<StringEnumeration> output(new DTRedundantEnumeration(), status);
1853     if (U_FAILURE(status)) { return nullptr; }
1854     const UnicodeString *pattern;
1855     PatternMapIterator it(status);
1856     if (U_FAILURE(status)) { return nullptr; }
1857 
1858     for (it.set(*patternMap); it.hasNext(); ) {
1859         DateTimeMatcher current = it.next();
1860         pattern = patternMap->getPatternFromSkeleton(*(it.getSkeleton()));
1861         if ( isCanonicalItem(*pattern) ) {
1862             continue;
1863         }
1864         if ( skipMatcher == nullptr ) {
1865             skipMatcher = new DateTimeMatcher(current);
1866             if (skipMatcher == nullptr) {
1867                 status = U_MEMORY_ALLOCATION_ERROR;
1868                 return nullptr;
1869             }
1870         }
1871         else {
1872             *skipMatcher = current;
1873         }
1874         UnicodeString trial = getBestPattern(current.getPattern(), status);
1875         if (U_FAILURE(status)) { return nullptr; }
1876         if (trial == *pattern) {
1877             ((DTRedundantEnumeration *)output.getAlias())->add(*pattern, status);
1878             if (U_FAILURE(status)) { return nullptr; }
1879         }
1880         if (current.equals(skipMatcher)) {
1881             continue;
1882         }
1883     }
1884     return output.orphan();
1885 }
1886 
1887 UBool
isCanonicalItem(const UnicodeString & item) const1888 DateTimePatternGenerator::isCanonicalItem(const UnicodeString& item) const {
1889     if ( item.length() != 1 ) {
1890         return FALSE;
1891     }
1892     for (int32_t i=0; i<UDATPG_FIELD_COUNT; ++i) {
1893         if (item.charAt(0)==Canonical_Items[i]) {
1894             return TRUE;
1895         }
1896     }
1897     return FALSE;
1898 }
1899 
1900 
1901 DateTimePatternGenerator*
clone() const1902 DateTimePatternGenerator::clone() const {
1903     return new DateTimePatternGenerator(*this);
1904 }
1905 
PatternMap()1906 PatternMap::PatternMap() {
1907    for (int32_t i=0; i < MAX_PATTERN_ENTRIES; ++i ) {
1908        boot[i] = nullptr;
1909    }
1910    isDupAllowed = TRUE;
1911 }
1912 
1913 void
copyFrom(const PatternMap & other,UErrorCode & status)1914 PatternMap::copyFrom(const PatternMap& other, UErrorCode& status) {
1915     if (U_FAILURE(status)) {
1916         return;
1917     }
1918     this->isDupAllowed = other.isDupAllowed;
1919     for (int32_t bootIndex = 0; bootIndex < MAX_PATTERN_ENTRIES; ++bootIndex) {
1920         PtnElem *curElem, *otherElem, *prevElem=nullptr;
1921         otherElem = other.boot[bootIndex];
1922         while (otherElem != nullptr) {
1923             LocalPointer<PtnElem> newElem(new PtnElem(otherElem->basePattern, otherElem->pattern), status);
1924             if (U_FAILURE(status)) {
1925                 return; // out of memory
1926             }
1927             newElem->skeleton.adoptInsteadAndCheckErrorCode(new PtnSkeleton(*(otherElem->skeleton)), status);
1928             if (U_FAILURE(status)) {
1929                 return; // out of memory
1930             }
1931             newElem->skeletonWasSpecified = otherElem->skeletonWasSpecified;
1932 
1933             // Release ownership from the LocalPointer of the PtnElem object.
1934             // The PtnElem will now be owned by either the boot (for the first entry in the linked-list)
1935             // or owned by the previous PtnElem object in the linked-list.
1936             curElem = newElem.orphan();
1937 
1938             if (this->boot[bootIndex] == nullptr) {
1939                 this->boot[bootIndex] = curElem;
1940             } else {
1941                 if (prevElem != nullptr) {
1942                     prevElem->next.adoptInstead(curElem);
1943                 } else {
1944                     UPRV_UNREACHABLE;
1945                 }
1946             }
1947             prevElem = curElem;
1948             otherElem = otherElem->next.getAlias();
1949         }
1950 
1951     }
1952 }
1953 
1954 PtnElem*
getHeader(UChar baseChar) const1955 PatternMap::getHeader(UChar baseChar) const {
1956     PtnElem* curElem;
1957 
1958     if ( (baseChar >= CAP_A) && (baseChar <= CAP_Z) ) {
1959          curElem = boot[baseChar-CAP_A];
1960     }
1961     else {
1962         if ( (baseChar >=LOW_A) && (baseChar <= LOW_Z) ) {
1963             curElem = boot[26+baseChar-LOW_A];
1964         }
1965         else {
1966             return nullptr;
1967         }
1968     }
1969     return curElem;
1970 }
1971 
~PatternMap()1972 PatternMap::~PatternMap() {
1973    for (int32_t i=0; i < MAX_PATTERN_ENTRIES; ++i ) {
1974        if (boot[i] != nullptr ) {
1975            delete boot[i];
1976            boot[i] = nullptr;
1977        }
1978    }
1979 }  // PatternMap destructor
1980 
1981 void
add(const UnicodeString & basePattern,const PtnSkeleton & skeleton,const UnicodeString & value,UBool skeletonWasSpecified,UErrorCode & status)1982 PatternMap::add(const UnicodeString& basePattern,
1983                 const PtnSkeleton& skeleton,
1984                 const UnicodeString& value,// mapped pattern value
1985                 UBool skeletonWasSpecified,
1986                 UErrorCode &status) {
1987     UChar baseChar = basePattern.charAt(0);
1988     PtnElem *curElem, *baseElem;
1989     status = U_ZERO_ERROR;
1990 
1991     // the baseChar must be A-Z or a-z
1992     if ((baseChar >= CAP_A) && (baseChar <= CAP_Z)) {
1993         baseElem = boot[baseChar-CAP_A];
1994     }
1995     else {
1996         if ((baseChar >=LOW_A) && (baseChar <= LOW_Z)) {
1997             baseElem = boot[26+baseChar-LOW_A];
1998          }
1999          else {
2000              status = U_ILLEGAL_CHARACTER;
2001              return;
2002          }
2003     }
2004 
2005     if (baseElem == nullptr) {
2006         LocalPointer<PtnElem> newElem(new PtnElem(basePattern, value), status);
2007         if (U_FAILURE(status)) {
2008             return; // out of memory
2009         }
2010         newElem->skeleton.adoptInsteadAndCheckErrorCode(new PtnSkeleton(skeleton), status);
2011         if (U_FAILURE(status)) {
2012             return; // out of memory
2013         }
2014         newElem->skeletonWasSpecified = skeletonWasSpecified;
2015         if (baseChar >= LOW_A) {
2016             boot[26 + (baseChar - LOW_A)] = newElem.orphan(); // the boot array now owns the PtnElem.
2017         }
2018         else {
2019             boot[baseChar - CAP_A] = newElem.orphan(); // the boot array now owns the PtnElem.
2020         }
2021     }
2022     if ( baseElem != nullptr ) {
2023         curElem = getDuplicateElem(basePattern, skeleton, baseElem);
2024 
2025         if (curElem == nullptr) {
2026             // add new element to the list.
2027             curElem = baseElem;
2028             while( curElem -> next != nullptr )
2029             {
2030                 curElem = curElem->next.getAlias();
2031             }
2032 
2033             LocalPointer<PtnElem> newElem(new PtnElem(basePattern, value), status);
2034             if (U_FAILURE(status)) {
2035                 return; // out of memory
2036             }
2037             newElem->skeleton.adoptInsteadAndCheckErrorCode(new PtnSkeleton(skeleton), status);
2038             if (U_FAILURE(status)) {
2039                 return; // out of memory
2040             }
2041             newElem->skeletonWasSpecified = skeletonWasSpecified;
2042             curElem->next.adoptInstead(newElem.orphan());
2043             curElem = curElem->next.getAlias();
2044         }
2045         else {
2046             // Pattern exists in the list already.
2047             if ( !isDupAllowed ) {
2048                 return;
2049             }
2050             // Overwrite the value.
2051             curElem->pattern = value;
2052             // It was a bug that we were not doing the following previously,
2053             // though that bug hid other problems by making things partly work.
2054             curElem->skeletonWasSpecified = skeletonWasSpecified;
2055         }
2056     }
2057 }  // PatternMap::add
2058 
2059 // Find the pattern from the given basePattern string.
2060 const UnicodeString *
getPatternFromBasePattern(const UnicodeString & basePattern,UBool & skeletonWasSpecified) const2061 PatternMap::getPatternFromBasePattern(const UnicodeString& basePattern, UBool& skeletonWasSpecified) const { // key to search for
2062    PtnElem *curElem;
2063 
2064    if ((curElem=getHeader(basePattern.charAt(0)))==nullptr) {
2065        return nullptr;  // no match
2066    }
2067 
2068    do  {
2069        if ( basePattern.compare(curElem->basePattern)==0 ) {
2070           skeletonWasSpecified = curElem->skeletonWasSpecified;
2071           return &(curElem->pattern);
2072        }
2073        curElem = curElem->next.getAlias();
2074    } while (curElem != nullptr);
2075 
2076    return nullptr;
2077 }  // PatternMap::getFromBasePattern
2078 
2079 
2080 // Find the pattern from the given skeleton.
2081 // At least when this is called from getBestRaw & addPattern (in which case specifiedSkeletonPtr is non-NULL),
2082 // the comparison should be based on skeleton.original (which is unique and tied to the distance measurement in bestRaw)
2083 // and not skeleton.baseOriginal (which is not unique); otherwise we may pick a different skeleton than the one with the
2084 // optimum distance value in getBestRaw. When this is called from public getRedundants (specifiedSkeletonPtr is NULL),
2085 // for now it will continue to compare based on baseOriginal so as not to change the behavior unnecessarily.
2086 const UnicodeString *
getPatternFromSkeleton(const PtnSkeleton & skeleton,const PtnSkeleton ** specifiedSkeletonPtr) const2087 PatternMap::getPatternFromSkeleton(const PtnSkeleton& skeleton, const PtnSkeleton** specifiedSkeletonPtr) const { // key to search for
2088    PtnElem *curElem;
2089 
2090    if (specifiedSkeletonPtr) {
2091        *specifiedSkeletonPtr = nullptr;
2092    }
2093 
2094    // find boot entry
2095    UChar baseChar = skeleton.getFirstChar();
2096    if ((curElem=getHeader(baseChar))==nullptr) {
2097        return nullptr;  // no match
2098    }
2099 
2100    do  {
2101        UBool equal;
2102        if (specifiedSkeletonPtr != nullptr) { // called from DateTimePatternGenerator::getBestRaw or addPattern, use original
2103            equal = curElem->skeleton->original == skeleton.original;
2104        } else { // called from DateTimePatternGenerator::getRedundants, use baseOriginal
2105            equal = curElem->skeleton->baseOriginal == skeleton.baseOriginal;
2106        }
2107        if (equal) {
2108            if (specifiedSkeletonPtr && curElem->skeletonWasSpecified) {
2109                *specifiedSkeletonPtr = curElem->skeleton.getAlias();
2110            }
2111            return &(curElem->pattern);
2112        }
2113        curElem = curElem->next.getAlias();
2114    } while (curElem != nullptr);
2115 
2116    return nullptr;
2117 }
2118 
2119 UBool
equals(const PatternMap & other) const2120 PatternMap::equals(const PatternMap& other) const {
2121     if ( this==&other ) {
2122         return TRUE;
2123     }
2124     for (int32_t bootIndex = 0; bootIndex < MAX_PATTERN_ENTRIES; ++bootIndex) {
2125         if (boot[bootIndex] == other.boot[bootIndex]) {
2126             continue;
2127         }
2128         if ((boot[bootIndex] == nullptr) || (other.boot[bootIndex] == nullptr)) {
2129             return FALSE;
2130         }
2131         PtnElem *otherElem = other.boot[bootIndex];
2132         PtnElem *myElem = boot[bootIndex];
2133         while ((otherElem != nullptr) || (myElem != nullptr)) {
2134             if ( myElem == otherElem ) {
2135                 break;
2136             }
2137             if ((otherElem == nullptr) || (myElem == nullptr)) {
2138                 return FALSE;
2139             }
2140             if ( (myElem->basePattern != otherElem->basePattern) ||
2141                  (myElem->pattern != otherElem->pattern) ) {
2142                 return FALSE;
2143             }
2144             if ((myElem->skeleton.getAlias() != otherElem->skeleton.getAlias()) &&
2145                 !myElem->skeleton->equals(*(otherElem->skeleton))) {
2146                 return FALSE;
2147             }
2148             myElem = myElem->next.getAlias();
2149             otherElem = otherElem->next.getAlias();
2150         }
2151     }
2152     return TRUE;
2153 }
2154 
2155 // find any key existing in the mapping table already.
2156 // return TRUE if there is an existing key, otherwise return FALSE.
2157 PtnElem*
getDuplicateElem(const UnicodeString & basePattern,const PtnSkeleton & skeleton,PtnElem * baseElem)2158 PatternMap::getDuplicateElem(
2159             const UnicodeString &basePattern,
2160             const PtnSkeleton &skeleton,
2161             PtnElem *baseElem) {
2162    PtnElem *curElem;
2163 
2164    if ( baseElem == nullptr ) {
2165          return nullptr;
2166    }
2167    else {
2168          curElem = baseElem;
2169    }
2170    do {
2171      if ( basePattern.compare(curElem->basePattern)==0 ) {
2172          UBool isEqual = TRUE;
2173          for (int32_t i = 0; i < UDATPG_FIELD_COUNT; ++i) {
2174             if (curElem->skeleton->type[i] != skeleton.type[i] ) {
2175                 isEqual = FALSE;
2176                 break;
2177             }
2178         }
2179         if (isEqual) {
2180             return curElem;
2181         }
2182      }
2183      curElem = curElem->next.getAlias();
2184    } while( curElem != nullptr );
2185 
2186    // end of the list
2187    return nullptr;
2188 
2189 }  // PatternMap::getDuplicateElem
2190 
DateTimeMatcher(void)2191 DateTimeMatcher::DateTimeMatcher(void) {
2192 }
2193 
~DateTimeMatcher()2194 DateTimeMatcher::~DateTimeMatcher() {}
2195 
DateTimeMatcher(const DateTimeMatcher & other)2196 DateTimeMatcher::DateTimeMatcher(const DateTimeMatcher& other) {
2197     copyFrom(other.skeleton);
2198 }
2199 
operator =(const DateTimeMatcher & other)2200 DateTimeMatcher& DateTimeMatcher::operator=(const DateTimeMatcher& other) {
2201     copyFrom(other.skeleton);
2202     return *this;
2203 }
2204 
2205 
2206 void
set(const UnicodeString & pattern,FormatParser * fp)2207 DateTimeMatcher::set(const UnicodeString& pattern, FormatParser* fp) {
2208     PtnSkeleton localSkeleton;
2209     return set(pattern, fp, localSkeleton);
2210 }
2211 
2212 void
set(const UnicodeString & pattern,FormatParser * fp,PtnSkeleton & skeletonResult)2213 DateTimeMatcher::set(const UnicodeString& pattern, FormatParser* fp, PtnSkeleton& skeletonResult) {
2214     int32_t i;
2215     for (i=0; i<UDATPG_FIELD_COUNT; ++i) {
2216         skeletonResult.type[i] = NONE;
2217     }
2218     skeletonResult.original.clear();
2219     skeletonResult.baseOriginal.clear();
2220     skeletonResult.addedDefaultDayPeriod = FALSE;
2221 
2222     fp->set(pattern);
2223     for (i=0; i < fp->itemNumber; i++) {
2224         const UnicodeString& value = fp->items[i];
2225         // don't skip 'a' anymore, dayPeriod handled specially below
2226 
2227         if ( fp->isQuoteLiteral(value) ) {
2228             UnicodeString quoteLiteral;
2229             fp->getQuoteLiteral(quoteLiteral, &i);
2230             continue;
2231         }
2232         int32_t canonicalIndex = fp->getCanonicalIndex(value);
2233         if (canonicalIndex < 0) {
2234             continue;
2235         }
2236         const dtTypeElem *row = &dtTypes[canonicalIndex];
2237         int32_t field = row->field;
2238         skeletonResult.original.populate(field, value);
2239         UChar repeatChar = row->patternChar;
2240         int32_t repeatCount = row->minLen;
2241         skeletonResult.baseOriginal.populate(field, repeatChar, repeatCount);
2242         int16_t subField = row->type;
2243         if (row->type > 0) {
2244             U_ASSERT(value.length() < INT16_MAX);
2245             subField += static_cast<int16_t>(value.length());
2246         }
2247         skeletonResult.type[field] = subField;
2248     }
2249 
2250     // #20739, we have a skeleton with minutes and milliseconds, but no seconds
2251     //
2252     // Theoretically we would need to check and fix all fields with "gaps":
2253     // for example year-day (no month), month-hour (no day), and so on, All the possible field combinations.
2254     // Plus some smartness: year + hour => should we add month, or add day-of-year?
2255     // What about month + day-of-week, or month + am/pm indicator.
2256     // I think beyond a certain point we should not try to fix bad developer input and try guessing what they mean.
2257     // Garbage in, garbage out.
2258     if (!skeletonResult.original.isFieldEmpty(UDATPG_MINUTE_FIELD)
2259         && !skeletonResult.original.isFieldEmpty(UDATPG_FRACTIONAL_SECOND_FIELD)
2260         && skeletonResult.original.isFieldEmpty(UDATPG_SECOND_FIELD)) {
2261         // Force the use of seconds
2262         for (i = 0; dtTypes[i].patternChar != 0; i++) {
2263             if (dtTypes[i].field == UDATPG_SECOND_FIELD) {
2264                 // first entry for UDATPG_SECOND_FIELD
2265                 skeletonResult.original.populate(UDATPG_SECOND_FIELD, dtTypes[i].patternChar, dtTypes[i].minLen);
2266                 skeletonResult.baseOriginal.populate(UDATPG_SECOND_FIELD, dtTypes[i].patternChar, dtTypes[i].minLen);
2267                 // We add value.length, same as above, when type is first initialized.
2268                 // The value we want to "fake" here is "s", and 1 means "s".length()
2269                 int16_t subField = dtTypes[i].type;
2270                 skeletonResult.type[UDATPG_SECOND_FIELD] = (subField > 0) ? subField + 1 : subField;
2271                 break;
2272             }
2273         }
2274     }
2275 
2276     // #13183, handle special behavior for day period characters (a, b, B)
2277     if (!skeletonResult.original.isFieldEmpty(UDATPG_HOUR_FIELD)) {
2278         if (skeletonResult.original.getFieldChar(UDATPG_HOUR_FIELD)==LOW_H || skeletonResult.original.getFieldChar(UDATPG_HOUR_FIELD)==CAP_K) {
2279             // We have a skeleton with 12-hour-cycle format
2280             if (skeletonResult.original.isFieldEmpty(UDATPG_DAYPERIOD_FIELD)) {
2281                 // But we do not have a day period in the skeleton; add the default DAYPERIOD (currently "a")
2282                 for (i = 0; dtTypes[i].patternChar != 0; i++) {
2283                     if ( dtTypes[i].field == UDATPG_DAYPERIOD_FIELD ) {
2284                         // first entry for UDATPG_DAYPERIOD_FIELD
2285                         skeletonResult.original.populate(UDATPG_DAYPERIOD_FIELD, dtTypes[i].patternChar, dtTypes[i].minLen);
2286                         skeletonResult.baseOriginal.populate(UDATPG_DAYPERIOD_FIELD, dtTypes[i].patternChar, dtTypes[i].minLen);
2287                         skeletonResult.type[UDATPG_DAYPERIOD_FIELD] = dtTypes[i].type;
2288                         skeletonResult.addedDefaultDayPeriod = TRUE;
2289                         break;
2290                     }
2291                 }
2292             }
2293         } else {
2294             // Skeleton has 24-hour-cycle hour format and has dayPeriod, delete dayPeriod (i.e. ignore it)
2295             skeletonResult.original.clearField(UDATPG_DAYPERIOD_FIELD);
2296             skeletonResult.baseOriginal.clearField(UDATPG_DAYPERIOD_FIELD);
2297             skeletonResult.type[UDATPG_DAYPERIOD_FIELD] = NONE;
2298         }
2299     }
2300     copyFrom(skeletonResult);
2301 }
2302 
2303 void
getBasePattern(UnicodeString & result)2304 DateTimeMatcher::getBasePattern(UnicodeString &result ) {
2305     result.remove(); // Reset the result first.
2306     skeleton.baseOriginal.appendTo(result);
2307 }
2308 
2309 UnicodeString
getPattern()2310 DateTimeMatcher::getPattern() {
2311     UnicodeString result;
2312     return skeleton.original.appendTo(result);
2313 }
2314 
2315 int32_t
getDistance(const DateTimeMatcher & other,int32_t includeMask,DistanceInfo & distanceInfo) const2316 DateTimeMatcher::getDistance(const DateTimeMatcher& other, int32_t includeMask, DistanceInfo& distanceInfo) const {
2317     int32_t result = 0;
2318     distanceInfo.clear();
2319     for (int32_t i=0; i<UDATPG_FIELD_COUNT; ++i ) {
2320         int32_t myType = (includeMask&(1<<i))==0 ? 0 : skeleton.type[i];
2321         int32_t otherType = other.skeleton.type[i];
2322         if (myType==otherType) {
2323             continue;
2324         }
2325         if (myType==0) {// and other is not
2326             result += EXTRA_FIELD;
2327             distanceInfo.addExtra(i);
2328         }
2329         else {
2330             if (otherType==0) {
2331                 result += MISSING_FIELD;
2332                 distanceInfo.addMissing(i);
2333             }
2334             else {
2335                 result += abs(myType - otherType);
2336             }
2337         }
2338 
2339     }
2340     return result;
2341 }
2342 
2343 void
copyFrom(const PtnSkeleton & newSkeleton)2344 DateTimeMatcher::copyFrom(const PtnSkeleton& newSkeleton) {
2345     skeleton.copyFrom(newSkeleton);
2346 }
2347 
2348 void
copyFrom()2349 DateTimeMatcher::copyFrom() {
2350     // same as clear
2351     skeleton.clear();
2352 }
2353 
2354 UBool
equals(const DateTimeMatcher * other) const2355 DateTimeMatcher::equals(const DateTimeMatcher* other) const {
2356     if (other==nullptr) { return FALSE; }
2357     return skeleton.original == other->skeleton.original;
2358 }
2359 
2360 int32_t
getFieldMask() const2361 DateTimeMatcher::getFieldMask() const {
2362     int32_t result = 0;
2363 
2364     for (int32_t i=0; i<UDATPG_FIELD_COUNT; ++i) {
2365         if (skeleton.type[i]!=0) {
2366             result |= (1<<i);
2367         }
2368     }
2369     return result;
2370 }
2371 
2372 PtnSkeleton*
getSkeletonPtr()2373 DateTimeMatcher::getSkeletonPtr() {
2374     return &skeleton;
2375 }
2376 
FormatParser()2377 FormatParser::FormatParser () {
2378     status = START;
2379     itemNumber = 0;
2380 }
2381 
2382 
~FormatParser()2383 FormatParser::~FormatParser () {
2384 }
2385 
2386 
2387 // Find the next token with the starting position and length
2388 // Note: the startPos may
2389 FormatParser::TokenStatus
setTokens(const UnicodeString & pattern,int32_t startPos,int32_t * len)2390 FormatParser::setTokens(const UnicodeString& pattern, int32_t startPos, int32_t *len) {
2391     int32_t curLoc = startPos;
2392     if ( curLoc >= pattern.length()) {
2393         return DONE;
2394     }
2395     // check the current char is between A-Z or a-z
2396     do {
2397         UChar c=pattern.charAt(curLoc);
2398         if ( (c>=CAP_A && c<=CAP_Z) || (c>=LOW_A && c<=LOW_Z) ) {
2399            curLoc++;
2400         }
2401         else {
2402                startPos = curLoc;
2403                *len=1;
2404                return ADD_TOKEN;
2405         }
2406 
2407         if ( pattern.charAt(curLoc)!= pattern.charAt(startPos) ) {
2408             break;  // not the same token
2409         }
2410     } while(curLoc <= pattern.length());
2411     *len = curLoc-startPos;
2412     return ADD_TOKEN;
2413 }
2414 
2415 void
set(const UnicodeString & pattern)2416 FormatParser::set(const UnicodeString& pattern) {
2417     int32_t startPos = 0;
2418     TokenStatus result = START;
2419     int32_t len = 0;
2420     itemNumber = 0;
2421 
2422     do {
2423         result = setTokens( pattern, startPos, &len );
2424         if ( result == ADD_TOKEN )
2425         {
2426             items[itemNumber++] = UnicodeString(pattern, startPos, len );
2427             startPos += len;
2428         }
2429         else {
2430             break;
2431         }
2432     } while (result==ADD_TOKEN && itemNumber < MAX_DT_TOKEN);
2433 }
2434 
2435 int32_t
getCanonicalIndex(const UnicodeString & s,UBool strict)2436 FormatParser::getCanonicalIndex(const UnicodeString& s, UBool strict) {
2437     int32_t len = s.length();
2438     if (len == 0) {
2439         return -1;
2440     }
2441     UChar ch = s.charAt(0);
2442 
2443     // Verify that all are the same character.
2444     for (int32_t l = 1; l < len; l++) {
2445         if (ch != s.charAt(l)) {
2446             return -1;
2447         }
2448     }
2449     int32_t i = 0;
2450     int32_t bestRow = -1;
2451     while (dtTypes[i].patternChar != 0x0000) {
2452         if ( dtTypes[i].patternChar != ch ) {
2453             ++i;
2454             continue;
2455         }
2456         bestRow = i;
2457         if (dtTypes[i].patternChar != dtTypes[i+1].patternChar) {
2458             return i;
2459         }
2460         if (dtTypes[i+1].minLen <= len) {
2461             ++i;
2462             continue;
2463         }
2464         return i;
2465     }
2466     return strict ? -1 : bestRow;
2467 }
2468 
2469 UBool
isQuoteLiteral(const UnicodeString & s)2470 FormatParser::isQuoteLiteral(const UnicodeString& s) {
2471     return (UBool)(s.charAt(0) == SINGLE_QUOTE);
2472 }
2473 
2474 // This function assumes the current itemIndex points to the quote literal.
2475 // Please call isQuoteLiteral prior to this function.
2476 void
getQuoteLiteral(UnicodeString & quote,int32_t * itemIndex)2477 FormatParser::getQuoteLiteral(UnicodeString& quote, int32_t *itemIndex) {
2478     int32_t i = *itemIndex;
2479 
2480     quote.remove();
2481     if (items[i].charAt(0)==SINGLE_QUOTE) {
2482         quote += items[i];
2483         ++i;
2484     }
2485     while ( i < itemNumber ) {
2486         if ( items[i].charAt(0)==SINGLE_QUOTE ) {
2487             if ( (i+1<itemNumber) && (items[i+1].charAt(0)==SINGLE_QUOTE)) {
2488                 // two single quotes e.g. 'o''clock'
2489                 quote += items[i++];
2490                 quote += items[i++];
2491                 continue;
2492             }
2493             else {
2494                 quote += items[i];
2495                 break;
2496             }
2497         }
2498         else {
2499             quote += items[i];
2500         }
2501         ++i;
2502     }
2503     *itemIndex=i;
2504 }
2505 
2506 UBool
isPatternSeparator(const UnicodeString & field) const2507 FormatParser::isPatternSeparator(const UnicodeString& field) const {
2508     for (int32_t i=0; i<field.length(); ++i ) {
2509         UChar c= field.charAt(i);
2510         if ( (c==SINGLE_QUOTE) || (c==BACKSLASH) || (c==SPACE) || (c==COLON) ||
2511              (c==QUOTATION_MARK) || (c==COMMA) || (c==HYPHEN) ||(items[i].charAt(0)==DOT) ) {
2512             continue;
2513         }
2514         else {
2515             return FALSE;
2516         }
2517     }
2518     return TRUE;
2519 }
2520 
~DistanceInfo()2521 DistanceInfo::~DistanceInfo() {}
2522 
2523 void
setTo(const DistanceInfo & other)2524 DistanceInfo::setTo(const DistanceInfo& other) {
2525     missingFieldMask = other.missingFieldMask;
2526     extraFieldMask= other.extraFieldMask;
2527 }
2528 
PatternMapIterator(UErrorCode & status)2529 PatternMapIterator::PatternMapIterator(UErrorCode& status) :
2530     bootIndex(0), nodePtr(nullptr), matcher(nullptr), patternMap(nullptr)
2531 {
2532     if (U_FAILURE(status)) { return; }
2533     matcher.adoptInsteadAndCheckErrorCode(new DateTimeMatcher(), status);
2534 }
2535 
~PatternMapIterator()2536 PatternMapIterator::~PatternMapIterator() {
2537 }
2538 
2539 void
set(PatternMap & newPatternMap)2540 PatternMapIterator::set(PatternMap& newPatternMap) {
2541     this->patternMap=&newPatternMap;
2542 }
2543 
2544 PtnSkeleton*
getSkeleton() const2545 PatternMapIterator::getSkeleton() const {
2546     if ( nodePtr == nullptr ) {
2547         return nullptr;
2548     }
2549     else {
2550         return nodePtr->skeleton.getAlias();
2551     }
2552 }
2553 
2554 UBool
hasNext() const2555 PatternMapIterator::hasNext() const {
2556     int32_t headIndex = bootIndex;
2557     PtnElem *curPtr = nodePtr;
2558 
2559     if (patternMap==nullptr) {
2560         return FALSE;
2561     }
2562     while ( headIndex < MAX_PATTERN_ENTRIES ) {
2563         if ( curPtr != nullptr ) {
2564             if ( curPtr->next != nullptr ) {
2565                 return TRUE;
2566             }
2567             else {
2568                 headIndex++;
2569                 curPtr=nullptr;
2570                 continue;
2571             }
2572         }
2573         else {
2574             if ( patternMap->boot[headIndex] != nullptr ) {
2575                 return TRUE;
2576             }
2577             else {
2578                 headIndex++;
2579                 continue;
2580             }
2581         }
2582     }
2583     return FALSE;
2584 }
2585 
2586 DateTimeMatcher&
next()2587 PatternMapIterator::next() {
2588     while ( bootIndex < MAX_PATTERN_ENTRIES ) {
2589         if ( nodePtr != nullptr ) {
2590             if ( nodePtr->next != nullptr ) {
2591                 nodePtr = nodePtr->next.getAlias();
2592                 break;
2593             }
2594             else {
2595                 bootIndex++;
2596                 nodePtr=nullptr;
2597                 continue;
2598             }
2599         }
2600         else {
2601             if ( patternMap->boot[bootIndex] != nullptr ) {
2602                 nodePtr = patternMap->boot[bootIndex];
2603                 break;
2604             }
2605             else {
2606                 bootIndex++;
2607                 continue;
2608             }
2609         }
2610     }
2611     if (nodePtr!=nullptr) {
2612         matcher->copyFrom(*nodePtr->skeleton);
2613     }
2614     else {
2615         matcher->copyFrom();
2616     }
2617     return *matcher;
2618 }
2619 
2620 
SkeletonFields()2621 SkeletonFields::SkeletonFields() {
2622     // Set initial values to zero
2623     clear();
2624 }
2625 
clear()2626 void SkeletonFields::clear() {
2627     uprv_memset(chars, 0, sizeof(chars));
2628     uprv_memset(lengths, 0, sizeof(lengths));
2629 }
2630 
copyFrom(const SkeletonFields & other)2631 void SkeletonFields::copyFrom(const SkeletonFields& other) {
2632     uprv_memcpy(chars, other.chars, sizeof(chars));
2633     uprv_memcpy(lengths, other.lengths, sizeof(lengths));
2634 }
2635 
clearField(int32_t field)2636 void SkeletonFields::clearField(int32_t field) {
2637     chars[field] = 0;
2638     lengths[field] = 0;
2639 }
2640 
getFieldChar(int32_t field) const2641 UChar SkeletonFields::getFieldChar(int32_t field) const {
2642     return chars[field];
2643 }
2644 
getFieldLength(int32_t field) const2645 int32_t SkeletonFields::getFieldLength(int32_t field) const {
2646     return lengths[field];
2647 }
2648 
populate(int32_t field,const UnicodeString & value)2649 void SkeletonFields::populate(int32_t field, const UnicodeString& value) {
2650     populate(field, value.charAt(0), value.length());
2651 }
2652 
populate(int32_t field,UChar ch,int32_t length)2653 void SkeletonFields::populate(int32_t field, UChar ch, int32_t length) {
2654     chars[field] = (int8_t) ch;
2655     lengths[field] = (int8_t) length;
2656 }
2657 
isFieldEmpty(int32_t field) const2658 UBool SkeletonFields::isFieldEmpty(int32_t field) const {
2659     return lengths[field] == 0;
2660 }
2661 
appendTo(UnicodeString & string) const2662 UnicodeString& SkeletonFields::appendTo(UnicodeString& string) const {
2663     for (int32_t i = 0; i < UDATPG_FIELD_COUNT; ++i) {
2664         appendFieldTo(i, string);
2665     }
2666     return string;
2667 }
2668 
appendFieldTo(int32_t field,UnicodeString & string) const2669 UnicodeString& SkeletonFields::appendFieldTo(int32_t field, UnicodeString& string) const {
2670     UChar ch(chars[field]);
2671     int32_t length = (int32_t) lengths[field];
2672 
2673     for (int32_t i=0; i<length; i++) {
2674         string += ch;
2675     }
2676     return string;
2677 }
2678 
getFirstChar() const2679 UChar SkeletonFields::getFirstChar() const {
2680     for (int32_t i = 0; i < UDATPG_FIELD_COUNT; ++i) {
2681         if (lengths[i] != 0) {
2682             return chars[i];
2683         }
2684     }
2685     return '\0';
2686 }
2687 
2688 
PtnSkeleton()2689 PtnSkeleton::PtnSkeleton()
2690     : addedDefaultDayPeriod(FALSE) {
2691 }
2692 
PtnSkeleton(const PtnSkeleton & other)2693 PtnSkeleton::PtnSkeleton(const PtnSkeleton& other) {
2694     copyFrom(other);
2695 }
2696 
copyFrom(const PtnSkeleton & other)2697 void PtnSkeleton::copyFrom(const PtnSkeleton& other) {
2698     uprv_memcpy(type, other.type, sizeof(type));
2699     original.copyFrom(other.original);
2700     baseOriginal.copyFrom(other.baseOriginal);
2701     addedDefaultDayPeriod = other.addedDefaultDayPeriod;
2702 }
2703 
clear()2704 void PtnSkeleton::clear() {
2705     uprv_memset(type, 0, sizeof(type));
2706     original.clear();
2707     baseOriginal.clear();
2708 }
2709 
2710 UBool
equals(const PtnSkeleton & other) const2711 PtnSkeleton::equals(const PtnSkeleton& other) const  {
2712     return (original == other.original)
2713         && (baseOriginal == other.baseOriginal)
2714         && (uprv_memcmp(type, other.type, sizeof(type)) == 0);
2715 }
2716 
2717 UnicodeString
getSkeleton() const2718 PtnSkeleton::getSkeleton() const {
2719     UnicodeString result;
2720     result = original.appendTo(result);
2721     int32_t pos;
2722     if (addedDefaultDayPeriod && (pos = result.indexOf(LOW_A)) >= 0) {
2723         // for backward compatibility: if DateTimeMatcher.set added a single 'a' that
2724         // was not in the provided skeleton, remove it here before returning skeleton.
2725         result.remove(pos, 1);
2726     }
2727     return result;
2728 }
2729 
2730 UnicodeString
getBaseSkeleton() const2731 PtnSkeleton::getBaseSkeleton() const {
2732     UnicodeString result;
2733     result = baseOriginal.appendTo(result);
2734     int32_t pos;
2735     if (addedDefaultDayPeriod && (pos = result.indexOf(LOW_A)) >= 0) {
2736         // for backward compatibility: if DateTimeMatcher.set added a single 'a' that
2737         // was not in the provided skeleton, remove it here before returning skeleton.
2738         result.remove(pos, 1);
2739     }
2740     return result;
2741 }
2742 
2743 UChar
getFirstChar() const2744 PtnSkeleton::getFirstChar() const {
2745     return baseOriginal.getFirstChar();
2746 }
2747 
~PtnSkeleton()2748 PtnSkeleton::~PtnSkeleton() {
2749 }
2750 
PtnElem(const UnicodeString & basePat,const UnicodeString & pat)2751 PtnElem::PtnElem(const UnicodeString &basePat, const UnicodeString &pat) :
2752     basePattern(basePat), skeleton(nullptr), pattern(pat), next(nullptr)
2753 {
2754 }
2755 
~PtnElem()2756 PtnElem::~PtnElem() {
2757 }
2758 
DTSkeletonEnumeration(PatternMap & patternMap,dtStrEnum type,UErrorCode & status)2759 DTSkeletonEnumeration::DTSkeletonEnumeration(PatternMap& patternMap, dtStrEnum type, UErrorCode& status) : fSkeletons(nullptr) {
2760     PtnElem  *curElem;
2761     PtnSkeleton *curSkeleton;
2762     UnicodeString s;
2763     int32_t bootIndex;
2764 
2765     pos=0;
2766     fSkeletons.adoptInsteadAndCheckErrorCode(new UVector(status), status);
2767     if (U_FAILURE(status)) {
2768         return;
2769     }
2770 
2771     for (bootIndex=0; bootIndex<MAX_PATTERN_ENTRIES; ++bootIndex ) {
2772         curElem = patternMap.boot[bootIndex];
2773         while (curElem!=nullptr) {
2774             switch(type) {
2775                 case DT_BASESKELETON:
2776                     s=curElem->basePattern;
2777                     break;
2778                 case DT_PATTERN:
2779                     s=curElem->pattern;
2780                     break;
2781                 case DT_SKELETON:
2782                     curSkeleton=curElem->skeleton.getAlias();
2783                     s=curSkeleton->getSkeleton();
2784                     break;
2785             }
2786             if ( !isCanonicalItem(s) ) {
2787                 LocalPointer<UnicodeString> newElem(new UnicodeString(s), status);
2788                 if (U_FAILURE(status)) {
2789                     return;
2790                 }
2791                 fSkeletons->addElement(newElem.getAlias(), status);
2792                 if (U_FAILURE(status)) {
2793                     fSkeletons.adoptInstead(nullptr);
2794                     return;
2795                 }
2796                 newElem.orphan(); // fSkeletons vector now owns the UnicodeString.
2797             }
2798             curElem = curElem->next.getAlias();
2799         }
2800     }
2801     if ((bootIndex==MAX_PATTERN_ENTRIES) && (curElem!=nullptr) ) {
2802         status = U_BUFFER_OVERFLOW_ERROR;
2803     }
2804 }
2805 
2806 const UnicodeString*
snext(UErrorCode & status)2807 DTSkeletonEnumeration::snext(UErrorCode& status) {
2808     if (U_SUCCESS(status) && fSkeletons.isValid() && pos < fSkeletons->size()) {
2809         return (const UnicodeString*)fSkeletons->elementAt(pos++);
2810     }
2811     return nullptr;
2812 }
2813 
2814 void
reset(UErrorCode &)2815 DTSkeletonEnumeration::reset(UErrorCode& /*status*/) {
2816     pos=0;
2817 }
2818 
2819 int32_t
count(UErrorCode &) const2820 DTSkeletonEnumeration::count(UErrorCode& /*status*/) const {
2821    return (fSkeletons.isNull()) ? 0 : fSkeletons->size();
2822 }
2823 
2824 UBool
isCanonicalItem(const UnicodeString & item)2825 DTSkeletonEnumeration::isCanonicalItem(const UnicodeString& item) {
2826     if ( item.length() != 1 ) {
2827         return FALSE;
2828     }
2829     for (int32_t i=0; i<UDATPG_FIELD_COUNT; ++i) {
2830         if (item.charAt(0)==Canonical_Items[i]) {
2831             return TRUE;
2832         }
2833     }
2834     return FALSE;
2835 }
2836 
~DTSkeletonEnumeration()2837 DTSkeletonEnumeration::~DTSkeletonEnumeration() {
2838     UnicodeString *s;
2839     if (fSkeletons.isValid()) {
2840         for (int32_t i = 0; i < fSkeletons->size(); ++i) {
2841             if ((s = (UnicodeString *)fSkeletons->elementAt(i)) != nullptr) {
2842                 delete s;
2843             }
2844         }
2845     }
2846 }
2847 
DTRedundantEnumeration()2848 DTRedundantEnumeration::DTRedundantEnumeration() : pos(0), fPatterns(nullptr) {
2849 }
2850 
2851 void
add(const UnicodeString & pattern,UErrorCode & status)2852 DTRedundantEnumeration::add(const UnicodeString& pattern, UErrorCode& status) {
2853     if (U_FAILURE(status)) { return; }
2854     if (fPatterns.isNull())  {
2855         fPatterns.adoptInsteadAndCheckErrorCode(new UVector(status), status);
2856         if (U_FAILURE(status)) {
2857             return;
2858        }
2859     }
2860     LocalPointer<UnicodeString> newElem(new UnicodeString(pattern), status);
2861     if (U_FAILURE(status)) {
2862         return;
2863     }
2864     fPatterns->addElement(newElem.getAlias(), status);
2865     if (U_FAILURE(status)) {
2866         fPatterns.adoptInstead(nullptr);
2867         return;
2868     }
2869     newElem.orphan(); // fPatterns now owns the string.
2870 }
2871 
2872 const UnicodeString*
snext(UErrorCode & status)2873 DTRedundantEnumeration::snext(UErrorCode& status) {
2874     if (U_SUCCESS(status) && fPatterns.isValid() && pos < fPatterns->size()) {
2875         return (const UnicodeString*)fPatterns->elementAt(pos++);
2876     }
2877     return nullptr;
2878 }
2879 
2880 void
reset(UErrorCode &)2881 DTRedundantEnumeration::reset(UErrorCode& /*status*/) {
2882     pos=0;
2883 }
2884 
2885 int32_t
count(UErrorCode &) const2886 DTRedundantEnumeration::count(UErrorCode& /*status*/) const {
2887     return (fPatterns.isNull()) ? 0 : fPatterns->size();
2888 }
2889 
2890 UBool
isCanonicalItem(const UnicodeString & item) const2891 DTRedundantEnumeration::isCanonicalItem(const UnicodeString& item) const {
2892     if ( item.length() != 1 ) {
2893         return FALSE;
2894     }
2895     for (int32_t i=0; i<UDATPG_FIELD_COUNT; ++i) {
2896         if (item.charAt(0)==Canonical_Items[i]) {
2897             return TRUE;
2898         }
2899     }
2900     return FALSE;
2901 }
2902 
~DTRedundantEnumeration()2903 DTRedundantEnumeration::~DTRedundantEnumeration() {
2904     UnicodeString *s;
2905     if (fPatterns.isValid()) {
2906         for (int32_t i = 0; i < fPatterns->size(); ++i) {
2907             if ((s = (UnicodeString *)fPatterns->elementAt(i)) != nullptr) {
2908                 delete s;
2909             }
2910         }
2911     }
2912 }
2913 
2914 U_NAMESPACE_END
2915 
2916 
2917 #endif /* #if !UCONFIG_NO_FORMATTING */
2918 
2919 //eof
2920