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