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