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