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