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