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