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