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