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