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