Debian Codegraph @

intl/icu/source/i18n/smpdtfmt.cpp

raw
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 *******************************************************************************
5 * Copyright (C) 1997-2016, International Business Machines Corporation and *
6 * others. All Rights Reserved. *
7 *******************************************************************************
8 *
9 * File SMPDTFMT.CPP
10 *
11 * Modification History:
12 *
13 * Date Name Description
14 * 02/19/97 aliu Converted from java.
15 * 03/31/97 aliu Modified extensively to work with 50 locales.
16 * 04/01/97 aliu Added support for centuries.
17 * 07/09/97 helena Made ParsePosition into a class.
18 * 07/21/98 stephen Added initializeDefaultCentury.
19 * Removed getZoneIndex (added in DateFormatSymbols)
20 * Removed subParseLong
21 * Removed chk
22 * 02/22/99 stephen Removed character literals for EBCDIC safety
23 * 10/14/99 aliu Updated 2-digit year parsing so that only "00" thru
24 * "99" are recognized. {j28 4182066}
25 * 11/15/99 weiv Added support for week of year/day of week format
26 ********************************************************************************
27 */
28
29 #define ZID_KEY_MAX 128
30
31 #include "unicode/utypes.h"
32
33 #if !UCONFIG_NO_FORMATTING
34 #include "unicode/smpdtfmt.h"
35 #include "unicode/dtfmtsym.h"
36 #include "unicode/ures.h"
37 #include "unicode/msgfmt.h"
38 #include "unicode/calendar.h"
39 #include "unicode/gregocal.h"
40 #include "unicode/timezone.h"
41 #include "unicode/decimfmt.h"
42 #include "unicode/dcfmtsym.h"
43 #include "unicode/uchar.h"
44 #include "unicode/uniset.h"
45 #include "unicode/ustring.h"
46 #include "unicode/basictz.h"
47 #include "unicode/simpleformatter.h"
48 #include "unicode/simplenumberformatter.h"
49 #include "unicode/simpletz.h"
50 #include "unicode/rbtz.h"
51 #include "unicode/tzfmt.h"
52 #include "unicode/ucasemap.h"
53 #include "unicode/utf16.h"
54 #include "unicode/vtzone.h"
55 #include "unicode/udisplaycontext.h"
56 #include "unicode/brkiter.h"
57 #include "unicode/rbnf.h"
58 #include "unicode/dtptngen.h"
59 #include "uresimp.h"
60 #include "olsontz.h"
61 #include "patternprops.h"
62 #include "fphdlimp.h"
63 #include "hebrwcal.h"
64 #include "cstring.h"
65 #include "uassert.h"
66 #include "cmemory.h"
67 #include "umutex.h"
68 #include "mutex.h"
69 #include <float.h>
70 #include "smpdtfst.h"
71 #include "sharednumberformat.h"
72 #include "ucasemap_imp.h"
73 #include "ustr_imp.h"
74 #include "charstr.h"
75 #include "uvector.h"
76 #include "cstr.h"
77 #include "dayperiodrules.h"
78 #include "tznames_impl.h" // ZONE_NAME_U16_MAX
79 #include "number_utypes.h"
80 #include "chnsecal.h"
81 #include "dangical.h"
82 #include "japancal.h"
83 #include <typeinfo>
84
85 #if defined( U_DEBUG_CALSVC ) || defined (U_DEBUG_CAL)
86 #include <stdio.h>
87 #endif
88
89 // *****************************************************************************
90 // class SimpleDateFormat
91 // *****************************************************************************
92
93 U_NAMESPACE_BEGIN
94
95 /**
96 * Last-resort string to use for "GMT" when constructing time zone strings.
97 */
98 // For time zones that have no names, use strings GMT+minutes and
99 // GMT-minutes. For instance, in France the time zone is GMT+60.
100 // Also accepted are GMT+H:MM or GMT-H:MM.
101 // Currently not being used
102 //static const char16_t gGmt[] = {0x0047, 0x004D, 0x0054, 0x0000}; // "GMT"
103 //static const char16_t gGmtPlus[] = {0x0047, 0x004D, 0x0054, 0x002B, 0x0000}; // "GMT+"
104 //static const char16_t gGmtMinus[] = {0x0047, 0x004D, 0x0054, 0x002D, 0x0000}; // "GMT-"
105 //static const char16_t gDefGmtPat[] = {0x0047, 0x004D, 0x0054, 0x007B, 0x0030, 0x007D, 0x0000}; /* GMT{0} */
106 //static const char16_t gDefGmtNegHmsPat[] = {0x002D, 0x0048, 0x0048, 0x003A, 0x006D, 0x006D, 0x003A, 0x0073, 0x0073, 0x0000}; /* -HH:mm:ss */
107 //static const char16_t gDefGmtNegHmPat[] = {0x002D, 0x0048, 0x0048, 0x003A, 0x006D, 0x006D, 0x0000}; /* -HH:mm */
108 //static const char16_t gDefGmtPosHmsPat[] = {0x002B, 0x0048, 0x0048, 0x003A, 0x006D, 0x006D, 0x003A, 0x0073, 0x0073, 0x0000}; /* +HH:mm:ss */
109 //static const char16_t gDefGmtPosHmPat[] = {0x002B, 0x0048, 0x0048, 0x003A, 0x006D, 0x006D, 0x0000}; /* +HH:mm */
110 //static const char16_t gUt[] = {0x0055, 0x0054, 0x0000}; // "UT"
111 //static const char16_t gUtc[] = {0x0055, 0x0054, 0x0043, 0x0000}; // "UT"
112
113 typedef enum GmtPatSize {
114 kGmtLen = 3,
115 kGmtPatLen = 6,
116 kNegHmsLen = 9,
117 kNegHmLen = 6,
118 kPosHmsLen = 9,
119 kPosHmLen = 6,
120 kUtLen = 2,
121 kUtcLen = 3
122 } GmtPatSize;
123
124 // Stuff needed for numbering system overrides
125
126 typedef enum OvrStrType {
127 kOvrStrDate = 0,
128 kOvrStrTime = 1,
129 kOvrStrBoth = 2
130 } OvrStrType;
131
132 static const UDateFormatField kDateFields[] = {
133 UDAT_YEAR_FIELD,
134 UDAT_MONTH_FIELD,
135 UDAT_DATE_FIELD,
136 UDAT_DAY_OF_YEAR_FIELD,
137 UDAT_DAY_OF_WEEK_IN_MONTH_FIELD,
138 UDAT_WEEK_OF_YEAR_FIELD,
139 UDAT_WEEK_OF_MONTH_FIELD,
140 UDAT_YEAR_WOY_FIELD,
141 UDAT_EXTENDED_YEAR_FIELD,
142 UDAT_JULIAN_DAY_FIELD,
143 UDAT_STANDALONE_DAY_FIELD,
144 UDAT_STANDALONE_MONTH_FIELD,
145 UDAT_QUARTER_FIELD,
146 UDAT_STANDALONE_QUARTER_FIELD,
147 UDAT_YEAR_NAME_FIELD,
148 UDAT_RELATED_YEAR_FIELD };
149 static const int8_t kDateFieldsCount = 16;
150
151 static const UDateFormatField kTimeFields[] = {
152 UDAT_HOUR_OF_DAY1_FIELD,
153 UDAT_HOUR_OF_DAY0_FIELD,
154 UDAT_MINUTE_FIELD,
155 UDAT_SECOND_FIELD,
156 UDAT_FRACTIONAL_SECOND_FIELD,
157 UDAT_HOUR1_FIELD,
158 UDAT_HOUR0_FIELD,
159 UDAT_MILLISECONDS_IN_DAY_FIELD,
160 UDAT_TIMEZONE_RFC_FIELD,
161 UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD };
162 static const int8_t kTimeFieldsCount = 10;
163
164
165 // This is a pattern-of-last-resort used when we can't load a usable pattern out
166 // of a resource.
167 static const char16_t gDefaultPattern[] =
168 {
169 0x79, 0x4D, 0x4D, 0x64, 0x64, 0x20, 0x68, 0x68, 0x3A, 0x6D, 0x6D, 0x20, 0x61, 0
170 }; /* "yMMdd hh:mm a" */
171
172 // This prefix is designed to NEVER MATCH real text, in order to
173 // suppress the parsing of negative numbers. Adjust as needed (if
174 // this becomes valid Unicode).
175 static const char16_t SUPPRESS_NEGATIVE_PREFIX[] = {0xAB00, 0};
176
177 /**
178 * These are the tags we expect to see in normal resource bundle files associated
179 * with a locale.
180 */
181 static const char16_t QUOTE = 0x27; // Single quote
182
183 /*
184 * The field range check bias for each UDateFormatField.
185 * The bias is added to the minimum and maximum values
186 * before they are compared to the parsed number.
187 * For example, the calendar stores zero-based month numbers
188 * but the parsed month numbers start at 1, so the bias is 1.
189 *
190 * A value of -1 means that the value is not checked.
191 */
192 static const int32_t gFieldRangeBias[] = {
193 -1, // 'G' - UDAT_ERA_FIELD
194 -1, // 'y' - UDAT_YEAR_FIELD
195 1, // 'M' - UDAT_MONTH_FIELD
196 0, // 'd' - UDAT_DATE_FIELD
197 -1, // 'k' - UDAT_HOUR_OF_DAY1_FIELD
198 -1, // 'H' - UDAT_HOUR_OF_DAY0_FIELD
199 0, // 'm' - UDAT_MINUTE_FIELD
200 0, // 's' - UDAT_SECOND_FIELD
201 -1, // 'S' - UDAT_FRACTIONAL_SECOND_FIELD (0-999?)
202 -1, // 'E' - UDAT_DAY_OF_WEEK_FIELD (1-7?)
203 -1, // 'D' - UDAT_DAY_OF_YEAR_FIELD (1 - 366?)
204 -1, // 'F' - UDAT_DAY_OF_WEEK_IN_MONTH_FIELD (1-5?)
205 -1, // 'w' - UDAT_WEEK_OF_YEAR_FIELD (1-52?)
206 -1, // 'W' - UDAT_WEEK_OF_MONTH_FIELD (1-5?)
207 -1, // 'a' - UDAT_AM_PM_FIELD
208 -1, // 'h' - UDAT_HOUR1_FIELD
209 -1, // 'K' - UDAT_HOUR0_FIELD
210 -1, // 'z' - UDAT_TIMEZONE_FIELD
211 -1, // 'Y' - UDAT_YEAR_WOY_FIELD
212 -1, // 'e' - UDAT_DOW_LOCAL_FIELD
213 -1, // 'u' - UDAT_EXTENDED_YEAR_FIELD
214 -1, // 'g' - UDAT_JULIAN_DAY_FIELD
215 -1, // 'A' - UDAT_MILLISECONDS_IN_DAY_FIELD
216 -1, // 'Z' - UDAT_TIMEZONE_RFC_FIELD
217 -1, // 'v' - UDAT_TIMEZONE_GENERIC_FIELD
218 0, // 'c' - UDAT_STANDALONE_DAY_FIELD
219 1, // 'L' - UDAT_STANDALONE_MONTH_FIELD
220 -1, // 'Q' - UDAT_QUARTER_FIELD (1-4?)
221 -1, // 'q' - UDAT_STANDALONE_QUARTER_FIELD
222 -1, // 'V' - UDAT_TIMEZONE_SPECIAL_FIELD
223 -1, // 'U' - UDAT_YEAR_NAME_FIELD
224 -1, // 'O' - UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD
225 -1, // 'X' - UDAT_TIMEZONE_ISO_FIELD
226 -1, // 'x' - UDAT_TIMEZONE_ISO_LOCAL_FIELD
227 -1, // 'r' - UDAT_RELATED_YEAR_FIELD
228 #if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR
229 -1, // ':' - UDAT_TIME_SEPARATOR_FIELD
230 #else
231 -1, // (no pattern character currently) - UDAT_TIME_SEPARATOR_FIELD
232 #endif
233 };
234
235 // When calendar uses hebr numbering (i.e. he@calendar=hebrew),
236 // offset the years within the current millennium down to 1-999
237 static const int32_t HEBREW_CAL_CUR_MILLENIUM_START_YEAR = 5000;
238 static const int32_t HEBREW_CAL_CUR_MILLENIUM_END_YEAR = 6000;
239
240 /**
241 * Maximum range for detecting daylight offset of a time zone when parsed time zone
242 * string indicates it's daylight saving time, but the detected time zone does not
243 * observe daylight saving time at the parsed date.
244 */
245 static const double MAX_DAYLIGHT_DETECTION_RANGE = 30*365*24*60*60*1000.0;
246
247 static UMutex LOCK;
248
249 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(SimpleDateFormat)
250
251 SimpleDateFormat::NSOverride::~NSOverride() {
252 if (snf != nullptr) {
253 snf->removeRef();
254 }
255 }
256
257
258 void SimpleDateFormat::NSOverride::free() {
259 NSOverride *cur = this;
260 while (cur) {
261 NSOverride *next_temp = cur->next;
262 delete cur;
263 cur = next_temp;
264 }
265 }
266
267 // no matter what the locale's default number format looked like, we want
268 // to modify it so that it doesn't use thousands separators, doesn't always
269 // show the decimal point, and recognizes integers only when parsing
270 static void fixNumberFormatForDates(NumberFormat &nf) {
271 nf.setGroupingUsed(false);
272 DecimalFormat* decfmt = dynamic_cast<DecimalFormat*>(&nf);
273 if (decfmt != nullptr) {
274 decfmt->setDecimalSeparatorAlwaysShown(false);
275 }
276 nf.setParseIntegerOnly(true);
277 nf.setMinimumFractionDigits(0); // To prevent "Jan 1.00, 1997.00"
278 }
279
280 static const SharedNumberFormat *createSharedNumberFormat(
281 NumberFormat *nfToAdopt) {
282 fixNumberFormatForDates(*nfToAdopt);
283 const SharedNumberFormat *result = new SharedNumberFormat(nfToAdopt);
284 if (result == nullptr) {
285 delete nfToAdopt;
286 }
287 return result;
288 }
289
290 static const SharedNumberFormat *createSharedNumberFormat(
291 const Locale &loc, UErrorCode &status) {
292 NumberFormat *nf = NumberFormat::createInstance(loc, status);
293 if (U_FAILURE(status)) {
294 return nullptr;
295 }
296 const SharedNumberFormat *result = createSharedNumberFormat(nf);
297 if (result == nullptr) {
298 status = U_MEMORY_ALLOCATION_ERROR;
299 }
300 return result;
301 }
302
303 static const SharedNumberFormat **allocSharedNumberFormatters() {
304 const SharedNumberFormat** result = static_cast<const SharedNumberFormat**>(
305 uprv_malloc(UDAT_FIELD_COUNT * sizeof(const SharedNumberFormat*)));
306 if (result == nullptr) {
307 return nullptr;
308 }
309 for (int32_t i = 0; i < UDAT_FIELD_COUNT; ++i) {
310 result[i] = nullptr;
311 }
312 return result;
313 }
314
315 static void freeSharedNumberFormatters(const SharedNumberFormat ** list) {
316 for (int32_t i = 0; i < UDAT_FIELD_COUNT; ++i) {
317 SharedObject::clearPtr(list[i]);
318 }
319 uprv_free(list);
320 }
321
322 const NumberFormat *SimpleDateFormat::getNumberFormatByIndex(
323 UDateFormatField index) const {
324 if (fSharedNumberFormatters == nullptr ||
325 fSharedNumberFormatters[index] == nullptr) {
326 return fNumberFormat;
327 }
328 return &(**fSharedNumberFormatters[index]);
329 }
330
331 //----------------------------------------------------------------------
332
333 SimpleDateFormat::~SimpleDateFormat()
334 {
335 delete fSymbols;
336 if (fSharedNumberFormatters) {
337 freeSharedNumberFormatters(fSharedNumberFormatters);
338 }
339 delete fTimeZoneFormat;
340 delete fSimpleNumberFormatter;
341
342 #if !UCONFIG_NO_BREAK_ITERATION
343 delete fCapitalizationBrkIter;
344 #endif
345 }
346
347 //----------------------------------------------------------------------
348
349 SimpleDateFormat::SimpleDateFormat(UErrorCode& status)
350 : fLocale(Locale::getDefault())
351 {
352 initializeBooleanAttributes();
353 construct(kShort, static_cast<EStyle>(kShort + kDateOffset), fLocale, status);
354 initializeDefaultCentury();
355 }
356
357 //----------------------------------------------------------------------
358
359 SimpleDateFormat::SimpleDateFormat(const UnicodeString& pattern,
360 UErrorCode &status)
361 : fPattern(pattern),
362 fLocale(Locale::getDefault())
363 {
364 fDateOverride.setToBogus();
365 fTimeOverride.setToBogus();
366 initializeBooleanAttributes();
367 initializeCalendar(nullptr,fLocale,status);
368 fSymbols = DateFormatSymbols::createForLocale(fLocale, status);
369 initialize(fLocale, status);
370 initializeDefaultCentury();
371
372 }
373 //----------------------------------------------------------------------
374
375 SimpleDateFormat::SimpleDateFormat(const UnicodeString& pattern,
376 const UnicodeString& override,
377 UErrorCode &status)
378 : fPattern(pattern),
379 fLocale(Locale::getDefault())
380 {
381 fDateOverride.setTo(override);
382 fTimeOverride.setToBogus();
383 initializeBooleanAttributes();
384 initializeCalendar(nullptr,fLocale,status);
385 fSymbols = DateFormatSymbols::createForLocale(fLocale, status);
386 initialize(fLocale, status);
387 initializeDefaultCentury();
388
389 processOverrideString(fLocale,override,kOvrStrBoth,status);
390
391 }
392
393 //----------------------------------------------------------------------
394
395 SimpleDateFormat::SimpleDateFormat(const UnicodeString& pattern,
396 const Locale& locale,
397 UErrorCode& status)
398 : fPattern(pattern),
399 fLocale(locale)
400 {
401
402 fDateOverride.setToBogus();
403 fTimeOverride.setToBogus();
404 initializeBooleanAttributes();
405
406 initializeCalendar(nullptr,fLocale,status);
407 fSymbols = DateFormatSymbols::createForLocale(fLocale, status);
408 initialize(fLocale, status);
409 initializeDefaultCentury();
410 }
411
412 //----------------------------------------------------------------------
413
414 SimpleDateFormat::SimpleDateFormat(const UnicodeString& pattern,
415 const UnicodeString& override,
416 const Locale& locale,
417 UErrorCode& status)
418 : fPattern(pattern),
419 fLocale(locale)
420 {
421
422 fDateOverride.setTo(override);
423 fTimeOverride.setToBogus();
424 initializeBooleanAttributes();
425
426 initializeCalendar(nullptr,fLocale,status);
427 fSymbols = DateFormatSymbols::createForLocale(fLocale, status);
428 initialize(fLocale, status);
429 initializeDefaultCentury();
430
431 processOverrideString(locale,override,kOvrStrBoth,status);
432
433 }
434
435 //----------------------------------------------------------------------
436
437 SimpleDateFormat::SimpleDateFormat(const UnicodeString& pattern,
438 DateFormatSymbols* symbolsToAdopt,
439 UErrorCode& status)
440 : fPattern(pattern),
441 fLocale(Locale::getDefault()),
442 fSymbols(symbolsToAdopt)
443 {
444
445 fDateOverride.setToBogus();
446 fTimeOverride.setToBogus();
447 initializeBooleanAttributes();
448
449 initializeCalendar(nullptr,fLocale,status);
450 initialize(fLocale, status);
451 initializeDefaultCentury();
452 }
453
454 //----------------------------------------------------------------------
455
456 SimpleDateFormat::SimpleDateFormat(const UnicodeString& pattern,
457 const DateFormatSymbols& symbols,
458 UErrorCode& status)
459 : fPattern(pattern),
460 fLocale(Locale::getDefault()),
461 fSymbols(new DateFormatSymbols(symbols))
462 {
463
464 fDateOverride.setToBogus();
465 fTimeOverride.setToBogus();
466 initializeBooleanAttributes();
467
468 initializeCalendar(nullptr, fLocale, status);
469 initialize(fLocale, status);
470 initializeDefaultCentury();
471 }
472
473 //----------------------------------------------------------------------
474
475 // Not for public consumption; used by DateFormat
476 SimpleDateFormat::SimpleDateFormat(EStyle timeStyle,
477 EStyle dateStyle,
478 const Locale& locale,
479 UErrorCode& status)
480 : fLocale(locale)
481 {
482 initializeBooleanAttributes();
483 construct(timeStyle, dateStyle, fLocale, status);
484 if(U_SUCCESS(status)) {
485 initializeDefaultCentury();
486 }
487 }
488
489 //----------------------------------------------------------------------
490
491 /**
492 * Not for public consumption; used by DateFormat. This constructor
493 * never fails. If the resource data is not available, it uses the
494 * the last resort symbols.
495 */
496 SimpleDateFormat::SimpleDateFormat(const Locale& locale,
497 UErrorCode& status)
498 : fPattern(gDefaultPattern),
499 fLocale(locale)
500 {
501 if (U_FAILURE(status)) return;
502 initializeBooleanAttributes();
503 initializeCalendar(nullptr, fLocale, status);
504 fSymbols = DateFormatSymbols::createForLocale(fLocale, status);
505 if (U_FAILURE(status))
506 {
507 status = U_ZERO_ERROR;
508 delete fSymbols;
509 // This constructor doesn't fail; it uses last resort data
510 fSymbols = new DateFormatSymbols(status);
511 /* test for nullptr */
512 if (fSymbols == nullptr) {
513 status = U_MEMORY_ALLOCATION_ERROR;
514 return;
515 }
516 }
517
518 fDateOverride.setToBogus();
519 fTimeOverride.setToBogus();
520
521 initialize(fLocale, status);
522 if(U_SUCCESS(status)) {
523 initializeDefaultCentury();
524 }
525 }
526
527 //----------------------------------------------------------------------
528
529 SimpleDateFormat::SimpleDateFormat(const SimpleDateFormat& other)
530 : DateFormat(other),
531 fLocale(other.fLocale)
532 {
533 initializeBooleanAttributes();
534 *this = other;
535 }
536
537 //----------------------------------------------------------------------
538
539 SimpleDateFormat& SimpleDateFormat::operator=(const SimpleDateFormat& other)
540 {
541 if (this == &other) {
542 return *this;
543 }
544
545 // fSimpleNumberFormatter references fNumberFormatter, delete it
546 // before we call the = operator which may invalidate fNumberFormatter
547 delete fSimpleNumberFormatter;
548 fSimpleNumberFormatter = nullptr;
549
550 DateFormat::operator=(other);
551 fDateOverride = other.fDateOverride;
552 fTimeOverride = other.fTimeOverride;
553
554 delete fSymbols;
555 fSymbols = nullptr;
556
557 if (other.fSymbols)
558 fSymbols = new DateFormatSymbols(*other.fSymbols);
559
560 fDefaultCenturyStart = other.fDefaultCenturyStart;
561 fDefaultCenturyStartYear = other.fDefaultCenturyStartYear;
562 fHaveDefaultCentury = other.fHaveDefaultCentury;
563
564 fPattern = other.fPattern;
565 fHasMinute = other.fHasMinute;
566 fHasSecond = other.fHasSecond;
567
568 fLocale = other.fLocale;
569
570 // TimeZoneFormat can now be set independently via setter.
571 // If it is nullptr, it will be lazily initialized from locale.
572 delete fTimeZoneFormat;
573 fTimeZoneFormat = nullptr;
574 TimeZoneFormat *otherTZFormat;
575 {
576 // Synchronization is required here, when accessing other.fTimeZoneFormat,
577 // because another thread may be concurrently executing other.tzFormat(),
578 // a logically const function that lazily creates other.fTimeZoneFormat.
579 //
580 // Without synchronization, reordered memory writes could allow us
581 // to see a non-null fTimeZoneFormat before the object itself was
582 // fully initialized. In case of a race, it doesn't matter whether
583 // we see a null or a fully initialized other.fTimeZoneFormat,
584 // only that we avoid seeing a partially initialized object.
585 //
586 // Once initialized, no const function can modify fTimeZoneFormat,
587 // meaning that once we have safely grabbed the other.fTimeZoneFormat
588 // pointer, continued synchronization is not required to use it.
589 Mutex m(&LOCK);
590 otherTZFormat = other.fTimeZoneFormat;
591 }
592 if (otherTZFormat) {
593 fTimeZoneFormat = new TimeZoneFormat(*otherTZFormat);
594 }
595
596 #if !UCONFIG_NO_BREAK_ITERATION
597 if (other.fCapitalizationBrkIter != nullptr) {
598 fCapitalizationBrkIter = (other.fCapitalizationBrkIter)->clone();
599 }
600 #endif
601
602 if (fSharedNumberFormatters != nullptr) {
603 freeSharedNumberFormatters(fSharedNumberFormatters);
604 fSharedNumberFormatters = nullptr;
605 }
606 if (other.fSharedNumberFormatters != nullptr) {
607 fSharedNumberFormatters = allocSharedNumberFormatters();
608 if (fSharedNumberFormatters) {
609 for (int32_t i = 0; i < UDAT_FIELD_COUNT; ++i) {
610 SharedObject::copyPtr(
611 other.fSharedNumberFormatters[i],
612 fSharedNumberFormatters[i]);
613 }
614 }
615 }
616
617 UErrorCode localStatus = U_ZERO_ERROR;
618 // SimpleNumberFormatter does not have a copy constructor. Furthermore,
619 // it references data from an internal field, fNumberFormatter,
620 // so we must rematerialize that reference after copying over the number formatter.
621 initSimpleNumberFormatter(localStatus);
622 return *this;
623 }
624
625 //----------------------------------------------------------------------
626
627 SimpleDateFormat*
628 SimpleDateFormat::clone() const
629 {
630 return new SimpleDateFormat(*this);
631 }
632
633 //----------------------------------------------------------------------
634
635 bool
636 SimpleDateFormat::operator==(const Format& other) const
637 {
638 if (DateFormat::operator==(other)) {
639 // The DateFormat::operator== check for fCapitalizationContext equality above
640 // is sufficient to check equality of all derived context-related data.
641 // DateFormat::operator== guarantees following cast is safe
642 SimpleDateFormat* that = (SimpleDateFormat*)&other;
643 return (fPattern == that->fPattern &&
644 fSymbols != nullptr && // Check for pathological object
645 that->fSymbols != nullptr && // Check for pathological object
646 *fSymbols == *that->fSymbols &&
647 fHaveDefaultCentury == that->fHaveDefaultCentury &&
648 fDefaultCenturyStart == that->fDefaultCenturyStart);
649 }
650 return false;
651 }
652
653 //----------------------------------------------------------------------
654 static const char16_t* timeSkeletons[4] = {
655 u"jmmsszzzz", // kFull
656 u"jmmssz", // kLong
657 u"jmmss", // kMedium
658 u"jmm", // kShort
659 };
660
661 void SimpleDateFormat::construct(EStyle timeStyle,
662 EStyle dateStyle,
663 const Locale& locale,
664 UErrorCode& status)
665 {
666 // called by several constructors to load pattern data from the resources
667 if (U_FAILURE(status)) return;
668
669 // We will need the calendar to know what type of symbols to load.
670 initializeCalendar(nullptr, locale, status);
671 if (U_FAILURE(status)) return;
672
673 // Load date time patterns directly from resources.
674 const char* cType = fCalendar ? fCalendar->getType() : nullptr;
675 LocalUResourceBundlePointer bundle(ures_open(nullptr, locale.getBaseName(), &status));
676 if (U_FAILURE(status)) return;
677
678 UBool cTypeIsGregorian = true;
679 LocalUResourceBundlePointer dateTimePatterns;
680 if (cType != nullptr && uprv_strcmp(cType, "gregorian") != 0) {
681 CharString resourcePath("calendar/", status);
682 resourcePath.append(cType, status).append("/DateTimePatterns", status);
683 dateTimePatterns.adoptInstead(
684 ures_getByKeyWithFallback(bundle.getAlias(), resourcePath.data(),
685 (UResourceBundle*)nullptr, &status));
686 cTypeIsGregorian = false;
687 }
688
689 // Check for "gregorian" fallback.
690 if (cTypeIsGregorian || status == U_MISSING_RESOURCE_ERROR) {
691 status = U_ZERO_ERROR;
692 dateTimePatterns.adoptInstead(
693 ures_getByKeyWithFallback(bundle.getAlias(),
694 "calendar/gregorian/DateTimePatterns",
695 (UResourceBundle*)nullptr, &status));
696 }
697 if (U_FAILURE(status)) return;
698
699 LocalUResourceBundlePointer currentBundle;
700
701 if (ures_getSize(dateTimePatterns.getAlias()) <= kDateTime)
702 {
703 status = U_INVALID_FORMAT_ERROR;
704 return;
705 }
706
707 setLocaleIDs(ures_getLocaleByType(dateTimePatterns.getAlias(), ULOC_VALID_LOCALE, &status),
708 ures_getLocaleByType(dateTimePatterns.getAlias(), ULOC_ACTUAL_LOCALE, &status));
709
710 // create a symbols object from the locale
711 fSymbols = DateFormatSymbols::createForLocale(locale, status);
712 if (U_FAILURE(status)) return;
713 /* test for nullptr */
714 if (fSymbols == nullptr) {
715 status = U_MEMORY_ALLOCATION_ERROR;
716 return;
717 }
718
719 const char16_t *resStr,*ovrStr;
720 int32_t resStrLen,ovrStrLen = 0;
721 fDateOverride.setToBogus();
722 fTimeOverride.setToBogus();
723
724 UnicodeString timePattern;
725 if (timeStyle >= kFull && timeStyle <= kShort) {
726 bool hasRgOrHcSubtag = false;
727 // also use DTPG if the locale has the "rg" or "hc" ("hours") subtag-- even if the overriding region
728 // or hour cycle is the same as the one we get by default, we go through the DateTimePatternGenerator
729 UErrorCode dummyErr1 = U_ZERO_ERROR, dummyErr2 = U_ZERO_ERROR;
730 if (locale.getKeywordValue("rg", nullptr, 0, dummyErr1) > 0 || locale.getKeywordValue("hours", nullptr, 0, dummyErr2) > 0) {
731 hasRgOrHcSubtag = true;
732 }
733
734 const char* baseLocID = locale.getBaseName();
735 if (baseLocID != nullptr && uprv_strcmp(baseLocID,"und")!=0) {
736 UErrorCode useStatus = U_ZERO_ERROR;
737 Locale baseLoc(baseLocID);
738 Locale validLoc(getLocale(ULOC_VALID_LOCALE, useStatus));
739 if (hasRgOrHcSubtag || (U_SUCCESS(useStatus) && validLoc!=baseLoc)) {
740 bool useDTPG = hasRgOrHcSubtag;
741 const char* baseReg = baseLoc.getCountry(); // empty string if no region
742 if ((baseReg != nullptr && baseReg[0] != 0 &&
743 uprv_strncmp(baseReg,validLoc.getCountry(),ULOC_COUNTRY_CAPACITY)!=0)
744 || uprv_strncmp(baseLoc.getLanguage(),validLoc.getLanguage(),ULOC_LANG_CAPACITY)!=0) {
745 // use DTPG if
746 // * baseLoc has a region and validLoc does not have the same one (or has none), OR
747 // * validLoc has a different language code than baseLoc
748 // * the original locale has the rg or hc subtag
749 useDTPG = true;
750 }
751 if (useDTPG) {
752 // The standard time formats may have the wrong time cycle, because:
753 // the valid locale differs in important ways (region, language) from
754 // the base locale.
755 // We could *also* check whether they do actually have a mismatch with
756 // the time cycle preferences for the region, but that is a lot more
757 // work for little or no additional benefit, since just going ahead
758 // and always synthesizing the time format as per the following should
759 // create a locale-appropriate pattern with cycle that matches the
760 // region preferences anyway.
761 LocalPointer<DateTimePatternGenerator> dtpg(DateTimePatternGenerator::createInstanceNoStdPat(locale, useStatus));
762 if (U_SUCCESS(useStatus)) {
763 UnicodeString timeSkeleton(true, timeSkeletons[timeStyle], -1);
764 timePattern = dtpg->getBestPattern(timeSkeleton, useStatus);
765 }
766 }
767 }
768 }
769 }
770
771 // if the pattern should include both date and time information, use the date/time
772 // pattern string as a guide to tell use how to glue together the appropriate date
773 // and time pattern strings.
774 if ((timeStyle != kNone) && (dateStyle != kNone))
775 {
776 UnicodeString tempus1(timePattern);
777 if (tempus1.length() == 0) {
778 currentBundle.adoptInstead(
779 ures_getByIndex(dateTimePatterns.getAlias(), static_cast<int32_t>(timeStyle), nullptr, &status));
780 if (U_FAILURE(status)) {
781 status = U_INVALID_FORMAT_ERROR;
782 return;
783 }
784 switch (ures_getType(currentBundle.getAlias())) {
785 case URES_STRING: {
786 resStr = ures_getString(currentBundle.getAlias(), &resStrLen, &status);
787 break;
788 }
789 case URES_ARRAY: {
790 resStr = ures_getStringByIndex(currentBundle.getAlias(), 0, &resStrLen, &status);
791 ovrStr = ures_getStringByIndex(currentBundle.getAlias(), 1, &ovrStrLen, &status);
792 fTimeOverride.setTo(true, ovrStr, ovrStrLen);
793 break;
794 }
795 default: {
796 status = U_INVALID_FORMAT_ERROR;
797 return;
798 }
799 }
800
801 tempus1.setTo(true, resStr, resStrLen);
802 }
803
804 currentBundle.adoptInstead(
805 ures_getByIndex(dateTimePatterns.getAlias(), static_cast<int32_t>(dateStyle), nullptr, &status));
806 if (U_FAILURE(status)) {
807 status = U_INVALID_FORMAT_ERROR;
808 return;
809 }
810 switch (ures_getType(currentBundle.getAlias())) {
811 case URES_STRING: {
812 resStr = ures_getString(currentBundle.getAlias(), &resStrLen, &status);
813 break;
814 }
815 case URES_ARRAY: {
816 resStr = ures_getStringByIndex(currentBundle.getAlias(), 0, &resStrLen, &status);
817 ovrStr = ures_getStringByIndex(currentBundle.getAlias(), 1, &ovrStrLen, &status);
818 fDateOverride.setTo(true, ovrStr, ovrStrLen);
819 break;
820 }
821 default: {
822 status = U_INVALID_FORMAT_ERROR;
823 return;
824 }
825 }
826
827 UnicodeString tempus2(true, resStr, resStrLen);
828
829 // Currently, for compatibility with pre-CLDR-42 data, we default to the "atTime"
830 // combining patterns. Depending on guidance in CLDR 42 spec and on DisplayOptions,
831 // we may change this.
832 LocalUResourceBundlePointer dateAtTimePatterns;
833 if (!cTypeIsGregorian) {
834 CharString resourcePath("calendar/", status);
835 resourcePath.append(cType, status).append("/DateTimePatterns%atTime", status);
836 dateAtTimePatterns.adoptInstead(
837 ures_getByKeyWithFallback(bundle.getAlias(), resourcePath.data(),
838 nullptr, &status));
839 }
840 if (cTypeIsGregorian || status == U_MISSING_RESOURCE_ERROR) {
841 status = U_ZERO_ERROR;
842 dateAtTimePatterns.adoptInstead(
843 ures_getByKeyWithFallback(bundle.getAlias(),
844 "calendar/gregorian/DateTimePatterns%atTime",
845 nullptr, &status));
846 }
847 if (U_SUCCESS(status) && ures_getSize(dateAtTimePatterns.getAlias()) >= 4) {
848 resStr = ures_getStringByIndex(dateAtTimePatterns.getAlias(), dateStyle - kDateOffset, &resStrLen, &status);
849 } else {
850 status = U_ZERO_ERROR;
851 int32_t glueIndex = kDateTime;
852 int32_t patternsSize = ures_getSize(dateTimePatterns.getAlias());
853 if (patternsSize >= (kDateTimeOffset + kShort + 1)) {
854 // Get proper date time format
855 glueIndex = static_cast<int32_t>(kDateTimeOffset + (dateStyle - kDateOffset));
856 }
857
858 resStr = ures_getStringByIndex(dateTimePatterns.getAlias(), glueIndex, &resStrLen, &status);
859 }
860 SimpleFormatter(UnicodeString(true, resStr, resStrLen), 2, 2, status).
861 format(tempus1, tempus2, fPattern, status);
862 }
863 // if the pattern includes just time data or just date date, load the appropriate
864 // pattern string from the resources
865 // setTo() - see DateFormatSymbols::assignArray comments
866 else if (timeStyle != kNone) {
867 fPattern.setTo(timePattern);
868 if (fPattern.length() == 0) {
869 currentBundle.adoptInstead(
870 ures_getByIndex(dateTimePatterns.getAlias(), static_cast<int32_t>(timeStyle), nullptr, &status));
871 if (U_FAILURE(status)) {
872 status = U_INVALID_FORMAT_ERROR;
873 return;
874 }
875 switch (ures_getType(currentBundle.getAlias())) {
876 case URES_STRING: {
877 resStr = ures_getString(currentBundle.getAlias(), &resStrLen, &status);
878 break;
879 }
880 case URES_ARRAY: {
881 resStr = ures_getStringByIndex(currentBundle.getAlias(), 0, &resStrLen, &status);
882 ovrStr = ures_getStringByIndex(currentBundle.getAlias(), 1, &ovrStrLen, &status);
883 fDateOverride.setTo(true, ovrStr, ovrStrLen);
884 break;
885 }
886 default: {
887 status = U_INVALID_FORMAT_ERROR;
888 return;
889 }
890 }
891 fPattern.setTo(true, resStr, resStrLen);
892 }
893 }
894 else if (dateStyle != kNone) {
895 currentBundle.adoptInstead(
896 ures_getByIndex(dateTimePatterns.getAlias(), static_cast<int32_t>(dateStyle), nullptr, &status));
897 if (U_FAILURE(status)) {
898 status = U_INVALID_FORMAT_ERROR;
899 return;
900 }
901 switch (ures_getType(currentBundle.getAlias())) {
902 case URES_STRING: {
903 resStr = ures_getString(currentBundle.getAlias(), &resStrLen, &status);
904 break;
905 }
906 case URES_ARRAY: {
907 resStr = ures_getStringByIndex(currentBundle.getAlias(), 0, &resStrLen, &status);
908 ovrStr = ures_getStringByIndex(currentBundle.getAlias(), 1, &ovrStrLen, &status);
909 fDateOverride.setTo(true, ovrStr, ovrStrLen);
910 break;
911 }
912 default: {
913 status = U_INVALID_FORMAT_ERROR;
914 return;
915 }
916 }
917 fPattern.setTo(true, resStr, resStrLen);
918 }
919
920 // and if it includes _neither_, that's an error
921 else
922 status = U_INVALID_FORMAT_ERROR;
923
924 // finally, finish initializing by creating a Calendar and a NumberFormat
925 initialize(locale, status);
926 }
927
928 //----------------------------------------------------------------------
929
930 Calendar*
931 SimpleDateFormat::initializeCalendar(TimeZone* adoptZone, const Locale& locale, UErrorCode& status)
932 {
933 if(!U_FAILURE(status)) {
934 fCalendar = Calendar::createInstance(
935 adoptZone ? adoptZone : TimeZone::forLocaleOrDefault(locale), locale, status);
936 }
937 return fCalendar;
938 }
939
940 void
941 SimpleDateFormat::initialize(const Locale& locale,
942 UErrorCode& status)
943 {
944 if (U_FAILURE(status)) return;
945
946 parsePattern(); // Need this before initNumberFormatters(), to set fHasHanYearChar
947
948 // Simple-minded hack to force Gannen year numbering for ja@calendar=japanese
949 // if format is non-numeric (includes 年) and fDateOverride is not already specified.
950 // Now this does get updated if applyPattern subsequently changes the pattern type.
951 if (fDateOverride.isBogus() && fHasHanYearChar &&
952 fCalendar != nullptr &&
953 typeid(*fCalendar) == typeid(JapaneseCalendar) &&
954 uprv_strcmp(fLocale.getLanguage(),"ja") == 0) {
955 fDateOverride.setTo(u"y=jpanyear", -1);
956 }
957
958 // We don't need to check that the row count is >= 1, since all 2d arrays have at
959 // least one row
960 fNumberFormat = NumberFormat::createInstance(locale, status);
961 if (fNumberFormat != nullptr && U_SUCCESS(status))
962 {
963 fixNumberFormatForDates(*fNumberFormat);
964 //fNumberFormat->setLenient(true); // Java uses a custom DateNumberFormat to format/parse
965
966 initNumberFormatters(locale, status);
967 initSimpleNumberFormatter(status);
968
969 }
970 else if (U_SUCCESS(status))
971 {
972 status = U_MISSING_RESOURCE_ERROR;
973 }
974 }
975
976 /* Initialize the fields we use to disambiguate ambiguous years. Separate
977 * so we can call it from readObject().
978 */
979 void SimpleDateFormat::initializeDefaultCentury()
980 {
981 if(fCalendar) {
982 fHaveDefaultCentury = fCalendar->haveDefaultCentury();
983 if(fHaveDefaultCentury) {
984 fDefaultCenturyStart = fCalendar->defaultCenturyStart();
985 fDefaultCenturyStartYear = fCalendar->defaultCenturyStartYear();
986 } else {
987 fDefaultCenturyStart = DBL_MIN;
988 fDefaultCenturyStartYear = -1;
989 }
990 }
991 }
992
993 /*
994 * Initialize the boolean attributes. Separate so we can call it from all constructors.
995 */
996 void SimpleDateFormat::initializeBooleanAttributes()
997 {
998 UErrorCode status = U_ZERO_ERROR;
999
1000 setBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, true, status);
1001 setBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, true, status);
1002 setBooleanAttribute(UDAT_PARSE_PARTIAL_LITERAL_MATCH, true, status);
1003 setBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, true, status);
1004 }
1005
1006 /* Define one-century window into which to disambiguate dates using
1007 * two-digit years. Make public in JDK 1.2.
1008 */
1009 void SimpleDateFormat::parseAmbiguousDatesAsAfter(UDate startDate, UErrorCode& status)
1010 {
1011 if(U_FAILURE(status)) {
1012 return;
1013 }
1014 if(!fCalendar) {
1015 status = U_ILLEGAL_ARGUMENT_ERROR;
1016 return;
1017 }
1018
1019 fCalendar->setTime(startDate, status);
1020 if(U_SUCCESS(status)) {
1021 fHaveDefaultCentury = true;
1022 fDefaultCenturyStart = startDate;
1023 fDefaultCenturyStartYear = fCalendar->get(UCAL_YEAR, status);
1024 }
1025 }
1026
1027 //----------------------------------------------------------------------
1028
1029 UnicodeString&
1030 SimpleDateFormat::format(Calendar& cal, UnicodeString& appendTo, FieldPosition& pos) const
1031 {
1032 UErrorCode status = U_ZERO_ERROR;
1033 FieldPositionOnlyHandler handler(pos);
1034 return _format(cal, appendTo, handler, status);
1035 }
1036
1037 //----------------------------------------------------------------------
1038
1039 UnicodeString&
1040 SimpleDateFormat::format(Calendar& cal, UnicodeString& appendTo,
1041 FieldPositionIterator* posIter, UErrorCode& status) const
1042 {
1043 FieldPositionIteratorHandler handler(posIter, status);
1044 return _format(cal, appendTo, handler, status);
1045 }
1046
1047 //----------------------------------------------------------------------
1048
1049 UnicodeString&
1050 SimpleDateFormat::_format(Calendar& cal, UnicodeString& appendTo,
1051 FieldPositionHandler& handler, UErrorCode& status) const
1052 {
1053 if ( U_FAILURE(status) ) {
1054 return appendTo;
1055 }
1056 Calendar* workCal = &cal;
1057 Calendar* calClone = nullptr;
1058 if (&cal != fCalendar && typeid(cal) != typeid(*fCalendar)) {
1059 // Different calendar type
1060 // We use the time and time zone from the input calendar, but
1061 // do not use the input calendar for field calculation.
1062 calClone = fCalendar->clone();
1063 if (calClone != nullptr) {
1064 UDate t = cal.getTime(status);
1065 calClone->setTime(t, status);
1066 calClone->setTimeZone(cal.getTimeZone());
1067 workCal = calClone;
1068 } else {
1069 status = U_MEMORY_ALLOCATION_ERROR;
1070 return appendTo;
1071 }
1072 }
1073
1074 UBool inQuote = false;
1075 char16_t prevCh = 0;
1076 int32_t count = 0;
1077 int32_t fieldNum = 0;
1078 UDisplayContext capitalizationContext = getContext(UDISPCTX_TYPE_CAPITALIZATION, status);
1079
1080 // loop through the pattern string character by character
1081 int32_t patternLength = fPattern.length();
1082 for (int32_t i = 0; i < patternLength && U_SUCCESS(status); ++i) {
1083 char16_t ch = fPattern[i];
1084
1085 // Use subFormat() to format a repeated pattern character
1086 // when a different pattern or non-pattern character is seen
1087 if (ch != prevCh && count > 0) {
1088 subFormat(appendTo, prevCh, count, capitalizationContext, fieldNum++,
1089 prevCh, handler, *workCal, status);
1090 count = 0;
1091 }
1092 if (ch == QUOTE) {
1093 // Consecutive single quotes are a single quote literal,
1094 // either outside of quotes or between quotes
1095 if ((i+1) < patternLength && fPattern[i+1] == QUOTE) {
1096 appendTo += QUOTE;
1097 ++i;
1098 } else {
1099 inQuote = ! inQuote;
1100 }
1101 }
1102 else if (!inQuote && isSyntaxChar(ch)) {
1103 // ch is a date-time pattern character to be interpreted
1104 // by subFormat(); count the number of times it is repeated
1105 prevCh = ch;
1106 ++count;
1107 }
1108 else {
1109 // Append quoted characters and unquoted non-pattern characters
1110 appendTo += ch;
1111 }
1112 }
1113
1114 // Format the last item in the pattern, if any
1115 if (count > 0) {
1116 subFormat(appendTo, prevCh, count, capitalizationContext, fieldNum++,
1117 prevCh, handler, *workCal, status);
1118 }
1119
1120 delete calClone;
1121
1122 return appendTo;
1123 }
1124
1125 //----------------------------------------------------------------------
1126
1127 /* Map calendar field into calendar field level.
1128 * the larger the level, the smaller the field unit.
1129 * For example, UCAL_ERA level is 0, UCAL_YEAR level is 10,
1130 * UCAL_MONTH level is 20.
1131 * NOTE: if new fields adds in, the table needs to update.
1132 */
1133 const int32_t
1134 SimpleDateFormat::fgCalendarFieldToLevel[] =
1135 {
1136 /*GyM*/ 0, 10, 20,
1137 /*wW*/ 20, 30,
1138 /*dDEF*/ 30, 20, 30, 30,
1139 /*ahHm*/ 40, 50, 50, 60,
1140 /*sS*/ 70, 80,
1141 /*z?Y*/ 0, 0, 10,
1142 /*eug*/ 30, 10, 0,
1143 /*A?.*/ 40, 0, 0
1144 };
1145
1146 int32_t SimpleDateFormat::getLevelFromChar(char16_t ch) {
1147 // Map date field LETTER into calendar field level.
1148 // the larger the level, the smaller the field unit.
1149 // NOTE: if new fields adds in, the table needs to update.
1150 static const int32_t mapCharToLevel[] = {
1151 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1152 //
1153 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1154 // ! " # $ % & ' ( ) * + , - . /
1155 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1156 #if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR
1157 // 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
1158 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1,
1159 #else
1160 // 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
1161 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1162 #endif
1163 // @ A B C D E F G H I J K L M N O
1164 -1, 40, -1, -1, 20, 30, 30, 0, 50, -1, -1, 50, 20, 20, -1, 0,
1165 // P Q R S T U V W X Y Z [ \ ] ^ _
1166 -1, 20, -1, 80, -1, 10, 0, 30, 0, 10, 0, -1, -1, -1, -1, -1,
1167 // ` a b c d e f g h i j k l m n o
1168 -1, 40, -1, 30, 30, 30, -1, 0, 50, -1, -1, 50, 0, 60, -1, -1,
1169 // p q r s t u v w x y z { | } ~
1170 -1, 20, 10, 70, -1, 10, 0, 20, 0, 10, 0, -1, -1, -1, -1, -1
1171 };
1172
1173 return ch < UPRV_LENGTHOF(mapCharToLevel) ? mapCharToLevel[ch] : -1;
1174 }
1175
1176 UBool SimpleDateFormat::isSyntaxChar(char16_t ch) {
1177 static const UBool mapCharToIsSyntax[] = {
1178 //
1179 false, false, false, false, false, false, false, false,
1180 //
1181 false, false, false, false, false, false, false, false,
1182 //
1183 false, false, false, false, false, false, false, false,
1184 //
1185 false, false, false, false, false, false, false, false,
1186 // ! " # $ % & '
1187 false, false, false, false, false, false, false, false,
1188 // ( ) * + , - . /
1189 false, false, false, false, false, false, false, false,
1190 // 0 1 2 3 4 5 6 7
1191 false, false, false, false, false, false, false, false,
1192 #if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR
1193 // 8 9 : ; < = > ?
1194 false, false, true, false, false, false, false, false,
1195 #else
1196 // 8 9 : ; < = > ?
1197 false, false, false, false, false, false, false, false,
1198 #endif
1199 // @ A B C D E F G
1200 false, true, true, true, true, true, true, true,
1201 // H I J K L M N O
1202 true, true, true, true, true, true, true, true,
1203 // P Q R S T U V W
1204 true, true, true, true, true, true, true, true,
1205 // X Y Z [ \ ] ^ _
1206 true, true, true, false, false, false, false, false,
1207 // ` a b c d e f g
1208 false, true, true, true, true, true, true, true,
1209 // h i j k l m n o
1210 true, true, true, true, true, true, true, true,
1211 // p q r s t u v w
1212 true, true, true, true, true, true, true, true,
1213 // x y z { | } ~
1214 true, true, true, false, false, false, false, false
1215 };
1216
1217 return ch < UPRV_LENGTHOF(mapCharToIsSyntax) ? mapCharToIsSyntax[ch] : false;
1218 }
1219
1220 // Map index into pattern character string to Calendar field number.
1221 const UCalendarDateFields
1222 SimpleDateFormat::fgPatternIndexToCalendarField[] =
1223 {
1224 /*GyM*/ UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
1225 /*dkH*/ UCAL_DATE, UCAL_HOUR_OF_DAY, UCAL_HOUR_OF_DAY,
1226 /*msS*/ UCAL_MINUTE, UCAL_SECOND, UCAL_MILLISECOND,
1227 /*EDF*/ UCAL_DAY_OF_WEEK, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK_IN_MONTH,
1228 /*wWa*/ UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_AM_PM,
1229 /*hKz*/ UCAL_HOUR, UCAL_HOUR, UCAL_ZONE_OFFSET,
1230 /*Yeu*/ UCAL_YEAR_WOY, UCAL_DOW_LOCAL, UCAL_EXTENDED_YEAR,
1231 /*gAZ*/ UCAL_JULIAN_DAY, UCAL_MILLISECONDS_IN_DAY, UCAL_ZONE_OFFSET,
1232 /*v*/ UCAL_ZONE_OFFSET,
1233 /*c*/ UCAL_DOW_LOCAL,
1234 /*L*/ UCAL_MONTH,
1235 /*Q*/ UCAL_MONTH,
1236 /*q*/ UCAL_MONTH,
1237 /*V*/ UCAL_ZONE_OFFSET,
1238 /*U*/ UCAL_YEAR,
1239 /*O*/ UCAL_ZONE_OFFSET,
1240 /*Xx*/ UCAL_ZONE_OFFSET, UCAL_ZONE_OFFSET,
1241 /*r*/ UCAL_EXTENDED_YEAR,
1242 /*bB*/ UCAL_FIELD_COUNT, UCAL_FIELD_COUNT, // no mappings to calendar fields
1243 #if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR
1244 /*:*/ UCAL_FIELD_COUNT, /* => no useful mapping to any calendar field */
1245 #else
1246 /*no pattern char for UDAT_TIME_SEPARATOR_FIELD*/ UCAL_FIELD_COUNT, /* => no useful mapping to any calendar field */
1247 #endif
1248 };
1249
1250 // Map index into pattern character string to DateFormat field number
1251 const UDateFormatField
1252 SimpleDateFormat::fgPatternIndexToDateFormatField[] = {
1253 /*GyM*/ UDAT_ERA_FIELD, UDAT_YEAR_FIELD, UDAT_MONTH_FIELD,
1254 /*dkH*/ UDAT_DATE_FIELD, UDAT_HOUR_OF_DAY1_FIELD, UDAT_HOUR_OF_DAY0_FIELD,
1255 /*msS*/ UDAT_MINUTE_FIELD, UDAT_SECOND_FIELD, UDAT_FRACTIONAL_SECOND_FIELD,
1256 /*EDF*/ UDAT_DAY_OF_WEEK_FIELD, UDAT_DAY_OF_YEAR_FIELD, UDAT_DAY_OF_WEEK_IN_MONTH_FIELD,
1257 /*wWa*/ UDAT_WEEK_OF_YEAR_FIELD, UDAT_WEEK_OF_MONTH_FIELD, UDAT_AM_PM_FIELD,
1258 /*hKz*/ UDAT_HOUR1_FIELD, UDAT_HOUR0_FIELD, UDAT_TIMEZONE_FIELD,
1259 /*Yeu*/ UDAT_YEAR_WOY_FIELD, UDAT_DOW_LOCAL_FIELD, UDAT_EXTENDED_YEAR_FIELD,
1260 /*gAZ*/ UDAT_JULIAN_DAY_FIELD, UDAT_MILLISECONDS_IN_DAY_FIELD, UDAT_TIMEZONE_RFC_FIELD,
1261 /*v*/ UDAT_TIMEZONE_GENERIC_FIELD,
1262 /*c*/ UDAT_STANDALONE_DAY_FIELD,
1263 /*L*/ UDAT_STANDALONE_MONTH_FIELD,
1264 /*Q*/ UDAT_QUARTER_FIELD,
1265 /*q*/ UDAT_STANDALONE_QUARTER_FIELD,
1266 /*V*/ UDAT_TIMEZONE_SPECIAL_FIELD,
1267 /*U*/ UDAT_YEAR_NAME_FIELD,
1268 /*O*/ UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD,
1269 /*Xx*/ UDAT_TIMEZONE_ISO_FIELD, UDAT_TIMEZONE_ISO_LOCAL_FIELD,
1270 /*r*/ UDAT_RELATED_YEAR_FIELD,
1271 /*bB*/ UDAT_AM_PM_MIDNIGHT_NOON_FIELD, UDAT_FLEXIBLE_DAY_PERIOD_FIELD,
1272 #if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR
1273 /*:*/ UDAT_TIME_SEPARATOR_FIELD,
1274 #else
1275 /*no pattern char for UDAT_TIME_SEPARATOR_FIELD*/ UDAT_TIME_SEPARATOR_FIELD,
1276 #endif
1277 };
1278
1279 //----------------------------------------------------------------------
1280
1281 /**
1282 * Append symbols[value] to dst. Make sure the array index is not out
1283 * of bounds.
1284 */
1285 static inline void
1286 _appendSymbol(UnicodeString& dst,
1287 int32_t value,
1288 const UnicodeString* symbols,
1289 int32_t symbolsCount) {
1290 U_ASSERT(0 <= value && value < symbolsCount);
1291 if (0 <= value && value < symbolsCount) {
1292 dst += symbols[value];
1293 }
1294 }
1295
1296 static inline void
1297 _appendSymbolWithMonthPattern(UnicodeString& dst, int32_t value, const UnicodeString* symbols, int32_t symbolsCount,
1298 const UnicodeString* monthPattern, UErrorCode& status) {
1299 U_ASSERT(0 <= value && value < symbolsCount);
1300 if (0 <= value && value < symbolsCount) {
1301 if (monthPattern == nullptr) {
1302 dst += symbols[value];
1303 } else {
1304 SimpleFormatter(*monthPattern, 1, 1, status).format(symbols[value], dst, status);
1305 }
1306 }
1307 }
1308
1309 //----------------------------------------------------------------------
1310
1311 void
1312 SimpleDateFormat::initSimpleNumberFormatter(UErrorCode &status) {
1313 if (U_FAILURE(status)) {
1314 return;
1315 }
1316 const auto* df = dynamic_cast<const DecimalFormat*>(fNumberFormat);
1317 if (df == nullptr) {
1318 return;
1319 }
1320 const DecimalFormatSymbols* syms = df->getDecimalFormatSymbols();
1321 if (syms == nullptr) {
1322 return;
1323 }
1324 fSimpleNumberFormatter = new number::SimpleNumberFormatter(
1325 number::SimpleNumberFormatter::forLocaleAndSymbolsAndGroupingStrategy(
1326 fLocale, *syms, UNUM_GROUPING_OFF, status
1327 )
1328 );
1329 if (fSimpleNumberFormatter == nullptr) {
1330 status = U_MEMORY_ALLOCATION_ERROR;
1331 }
1332 }
1333
1334 void
1335 SimpleDateFormat::initNumberFormatters(const Locale &locale,UErrorCode &status) {
1336 if (U_FAILURE(status)) {
1337 return;
1338 }
1339 if ( fDateOverride.isBogus() && fTimeOverride.isBogus() ) {
1340 return;
1341 }
1342 umtx_lock(&LOCK);
1343 if (fSharedNumberFormatters == nullptr) {
1344 fSharedNumberFormatters = allocSharedNumberFormatters();
1345 if (fSharedNumberFormatters == nullptr) {
1346 status = U_MEMORY_ALLOCATION_ERROR;
1347 }
1348 }
1349 umtx_unlock(&LOCK);
1350
1351 if (U_FAILURE(status)) {
1352 return;
1353 }
1354
1355 processOverrideString(locale,fDateOverride,kOvrStrDate,status);
1356 processOverrideString(locale,fTimeOverride,kOvrStrTime,status);
1357 }
1358
1359 void
1360 SimpleDateFormat::processOverrideString(const Locale &locale, const UnicodeString &str, int8_t type, UErrorCode &status) {
1361 if (str.isBogus() || U_FAILURE(status)) {
1362 return;
1363 }
1364
1365 int32_t start = 0;
1366 int32_t len;
1367 UnicodeString nsName;
1368 UnicodeString ovrField;
1369 UBool moreToProcess = true;
1370 NSOverride *overrideList = nullptr;
1371
1372 while (moreToProcess) {
1373 int32_t delimiterPosition = str.indexOf(static_cast<char16_t>(ULOC_KEYWORD_ITEM_SEPARATOR_UNICODE), start);
1374 if (delimiterPosition == -1) {
1375 moreToProcess = false;
1376 len = str.length() - start;
1377 } else {
1378 len = delimiterPosition - start;
1379 }
1380 UnicodeString currentString(str,start,len);
1381 int32_t equalSignPosition = currentString.indexOf(static_cast<char16_t>(ULOC_KEYWORD_ASSIGN_UNICODE), 0);
1382 if (equalSignPosition == -1) { // Simple override string such as "hebrew"
1383 nsName.setTo(currentString);
1384 ovrField.setToBogus();
1385 } else { // Field specific override string such as "y=hebrew"
1386 nsName.setTo(currentString,equalSignPosition+1);
1387 ovrField.setTo(currentString,0,1); // We just need the first character.
1388 }
1389
1390 int32_t nsNameHash = nsName.hashCode();
1391 // See if the numbering system is in the override list, if not, then add it.
1392 NSOverride *curr = overrideList;
1393 const SharedNumberFormat *snf = nullptr;
1394 UBool found = false;
1395 while ( curr && !found ) {
1396 if ( curr->hash == nsNameHash ) {
1397 snf = curr->snf;
1398 found = true;
1399 }
1400 curr = curr->next;
1401 }
1402
1403 if (!found) {
1404 LocalPointer<NSOverride> cur(new NSOverride);
1405 if (!cur.isNull()) {
1406 char kw[ULOC_KEYWORD_AND_VALUES_CAPACITY];
1407 uprv_strcpy(kw,"numbers=");
1408 nsName.extract(0,len,kw+8,ULOC_KEYWORD_AND_VALUES_CAPACITY-8,US_INV);
1409
1410 Locale ovrLoc(locale.getLanguage(),locale.getCountry(),locale.getVariant(),kw);
1411 cur->hash = nsNameHash;
1412 cur->next = overrideList;
1413 SharedObject::copyPtr(
1414 createSharedNumberFormat(ovrLoc, status), cur->snf);
1415 if (U_FAILURE(status)) {
1416 if (overrideList) {
1417 overrideList->free();
1418 }
1419 return;
1420 }
1421 snf = cur->snf;
1422 overrideList = cur.orphan();
1423 } else {
1424 status = U_MEMORY_ALLOCATION_ERROR;
1425 if (overrideList) {
1426 overrideList->free();
1427 }
1428 return;
1429 }
1430 }
1431
1432 // Now that we have an appropriate number formatter, fill in the appropriate spaces in the
1433 // number formatters table.
1434 if (ovrField.isBogus()) {
1435 switch (type) {
1436 case kOvrStrDate:
1437 case kOvrStrBoth: {
1438 for ( int8_t i=0 ; i<kDateFieldsCount; i++ ) {
1439 SharedObject::copyPtr(snf, fSharedNumberFormatters[kDateFields[i]]);
1440 }
1441 if (type==kOvrStrDate) {
1442 break;
1443 }
1444 U_FALLTHROUGH;
1445 }
1446 case kOvrStrTime : {
1447 for ( int8_t i=0 ; i<kTimeFieldsCount; i++ ) {
1448 SharedObject::copyPtr(snf, fSharedNumberFormatters[kTimeFields[i]]);
1449 }
1450 break;
1451 }
1452 }
1453 } else {
1454 // if the pattern character is unrecognized, signal an error and bail out
1455 UDateFormatField patternCharIndex =
1456 DateFormatSymbols::getPatternCharIndex(ovrField.charAt(0));
1457 if (patternCharIndex == UDAT_FIELD_COUNT) {
1458 status = U_INVALID_FORMAT_ERROR;
1459 if (overrideList) {
1460 overrideList->free();
1461 }
1462 return;
1463 }
1464 SharedObject::copyPtr(snf, fSharedNumberFormatters[patternCharIndex]);
1465 }
1466
1467 start = delimiterPosition + 1;
1468 }
1469 if (overrideList) {
1470 overrideList->free();
1471 }
1472 }
1473
1474 //---------------------------------------------------------------------
1475 void
1476 SimpleDateFormat::subFormat(UnicodeString &appendTo,
1477 char16_t ch,
1478 int32_t count,
1479 UDisplayContext capitalizationContext,
1480 int32_t fieldNum,
1481 char16_t fieldToOutput,
1482 FieldPositionHandler& handler,
1483 Calendar& cal,
1484 UErrorCode& status) const
1485 {
1486 static const int32_t maxIntCount = 10;
1487 static const UnicodeString hebr(u"hebr");
1488
1489 if (U_FAILURE(status)) {
1490 return;
1491 }
1492
1493 // this function gets called by format() to produce the appropriate substitution
1494 // text for an individual pattern symbol (e.g., "HH" or "yyyy")
1495
1496 UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(ch);
1497 int32_t beginOffset = appendTo.length();
1498 DateFormatSymbols::ECapitalizationContextUsageType capContextUsageType = DateFormatSymbols::kCapContextUsageOther;
1499
1500 // if the pattern character is unrecognized, signal an error and dump out
1501 if (patternCharIndex == UDAT_FIELD_COUNT)
1502 {
1503 if (ch != 0x6C) { // pattern char 'l' (SMALL LETTER L) just gets ignored
1504 status = U_INVALID_FORMAT_ERROR;
1505 }
1506 return;
1507 }
1508
1509 UCalendarDateFields field = fgPatternIndexToCalendarField[patternCharIndex];
1510 int32_t value = 0;
1511 // Don't get value unless it is useful
1512 if (field < UCAL_FIELD_COUNT) {
1513 value = (patternCharIndex != UDAT_RELATED_YEAR_FIELD)? cal.get(field, status): cal.getRelatedYear(status);
1514 if (U_FAILURE(status)) {
1515 return;
1516 }
1517 }
1518
1519 const NumberFormat *currentNumberFormat = getNumberFormatByIndex(patternCharIndex);
1520 if (currentNumberFormat == nullptr) {
1521 status = U_INTERNAL_PROGRAM_ERROR;
1522 return;
1523 }
1524
1525 switch (patternCharIndex) {
1526
1527 // for any "G" symbol, write out the appropriate era string
1528 // "GGGG" is wide era name, "GGGGG" is narrow era name, anything else is abbreviated name
1529 case UDAT_ERA_FIELD:
1530 {
1531 if (typeid(cal) == typeid(ChineseCalendar) ||
1532 typeid(cal) == typeid(DangiCalendar)) {
1533 zeroPaddingNumber(currentNumberFormat,appendTo, value, 1, 9); // as in ICU4J
1534 } else {
1535 if (count == 5) {
1536 _appendSymbol(appendTo, value, fSymbols->fNarrowEras, fSymbols->fNarrowErasCount);
1537 capContextUsageType = DateFormatSymbols::kCapContextUsageEraNarrow;
1538 } else if (count == 4) {
1539 _appendSymbol(appendTo, value, fSymbols->fEraNames, fSymbols->fEraNamesCount);
1540 capContextUsageType = DateFormatSymbols::kCapContextUsageEraWide;
1541 } else {
1542 _appendSymbol(appendTo, value, fSymbols->fEras, fSymbols->fErasCount);
1543 capContextUsageType = DateFormatSymbols::kCapContextUsageEraAbbrev;
1544 }
1545 }
1546 }
1547 break;
1548
1549 case UDAT_YEAR_NAME_FIELD:
1550 if (fSymbols->fShortYearNames != nullptr && value <= fSymbols->fShortYearNamesCount) {
1551 // the Calendar YEAR field runs 1 through 60 for cyclic years
1552 _appendSymbol(appendTo, value - 1, fSymbols->fShortYearNames, fSymbols->fShortYearNamesCount);
1553 break;
1554 }
1555 // else fall through to numeric year handling, do not break here
1556 U_FALLTHROUGH;
1557
1558 // OLD: for "yyyy", write out the whole year; for "yy", write out the last 2 digits
1559 // NEW: UTS#35:
1560 //Year y yy yyy yyyy yyyyy
1561 //AD 1 1 01 001 0001 00001
1562 //AD 12 12 12 012 0012 00012
1563 //AD 123 123 23 123 0123 00123
1564 //AD 1234 1234 34 1234 1234 01234
1565 //AD 12345 12345 45 12345 12345 12345
1566 case UDAT_YEAR_FIELD:
1567 case UDAT_YEAR_WOY_FIELD:
1568 if (fDateOverride.compare(hebr)==0 && value>HEBREW_CAL_CUR_MILLENIUM_START_YEAR && value<HEBREW_CAL_CUR_MILLENIUM_END_YEAR) {
1569 value-=HEBREW_CAL_CUR_MILLENIUM_START_YEAR;
1570 }
1571 if(count == 2)
1572 zeroPaddingNumber(currentNumberFormat, appendTo, value, 2, 2);
1573 else
1574 zeroPaddingNumber(currentNumberFormat, appendTo, value, count, maxIntCount);
1575 break;
1576
1577 // for "MMMM"/"LLLL", write out the whole month name, for "MMM"/"LLL", write out the month
1578 // abbreviation, for "M"/"L" or "MM"/"LL", write out the month as a number with the
1579 // appropriate number of digits
1580 // for "MMMMM"/"LLLLL", use the narrow form
1581 case UDAT_MONTH_FIELD:
1582 case UDAT_STANDALONE_MONTH_FIELD:
1583 if (typeid(cal) == typeid(HebrewCalendar)) {
1584 if (HebrewCalendar::isLeapYear(cal.get(UCAL_YEAR,status)) && value == 6 && count >= 3 )
1585 value = 13; // Show alternate form for Adar II in leap years in Hebrew calendar.
1586 if (!HebrewCalendar::isLeapYear(cal.get(UCAL_YEAR,status)) && value >= 6 && count < 3 )
1587 value--; // Adjust the month number down 1 in Hebrew non-leap years, i.e. Adar is 6, not 7.
1588 }
1589 {
1590 int32_t isLeapMonth = (fSymbols->fLeapMonthPatterns != nullptr && fSymbols->fLeapMonthPatternsCount >= DateFormatSymbols::kMonthPatternsCount)?
1591 cal.get(UCAL_IS_LEAP_MONTH, status): 0;
1592 // should consolidate the next section by using arrays of pointers & counts for the right symbols...
1593 if (count == 5) {
1594 if (patternCharIndex == UDAT_MONTH_FIELD) {
1595 _appendSymbolWithMonthPattern(appendTo, value, fSymbols->fNarrowMonths, fSymbols->fNarrowMonthsCount,
1596 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatNarrow]): nullptr, status);
1597 } else {
1598 _appendSymbolWithMonthPattern(appendTo, value, fSymbols->fStandaloneNarrowMonths, fSymbols->fStandaloneNarrowMonthsCount,
1599 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneNarrow]): nullptr, status);
1600 }
1601 capContextUsageType = DateFormatSymbols::kCapContextUsageMonthNarrow;
1602 } else if (count == 4) {
1603 if (patternCharIndex == UDAT_MONTH_FIELD) {
1604 _appendSymbolWithMonthPattern(appendTo, value, fSymbols->fMonths, fSymbols->fMonthsCount,
1605 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatWide]): nullptr, status);
1606 capContextUsageType = DateFormatSymbols::kCapContextUsageMonthFormat;
1607 } else {
1608 _appendSymbolWithMonthPattern(appendTo, value, fSymbols->fStandaloneMonths, fSymbols->fStandaloneMonthsCount,
1609 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneWide]): nullptr, status);
1610 capContextUsageType = DateFormatSymbols::kCapContextUsageMonthStandalone;
1611 }
1612 } else if (count == 3) {
1613 if (patternCharIndex == UDAT_MONTH_FIELD) {
1614 _appendSymbolWithMonthPattern(appendTo, value, fSymbols->fShortMonths, fSymbols->fShortMonthsCount,
1615 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatAbbrev]): nullptr, status);
1616 capContextUsageType = DateFormatSymbols::kCapContextUsageMonthFormat;
1617 } else {
1618 _appendSymbolWithMonthPattern(appendTo, value, fSymbols->fStandaloneShortMonths, fSymbols->fStandaloneShortMonthsCount,
1619 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneAbbrev]): nullptr, status);
1620 capContextUsageType = DateFormatSymbols::kCapContextUsageMonthStandalone;
1621 }
1622 } else {
1623 UnicodeString monthNumber;
1624 zeroPaddingNumber(currentNumberFormat,monthNumber, value + 1, count, maxIntCount);
1625 _appendSymbolWithMonthPattern(appendTo, 0, &monthNumber, 1,
1626 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternNumeric]): nullptr, status);
1627 }
1628 }
1629 break;
1630
1631 // for "k" and "kk", write out the hour, adjusting midnight to appear as "24"
1632 case UDAT_HOUR_OF_DAY1_FIELD:
1633 if (value == 0)
1634 zeroPaddingNumber(currentNumberFormat,appendTo, cal.getMaximum(UCAL_HOUR_OF_DAY) + 1, count, maxIntCount);
1635 else
1636 zeroPaddingNumber(currentNumberFormat,appendTo, value, count, maxIntCount);
1637 break;
1638
1639 case UDAT_FRACTIONAL_SECOND_FIELD:
1640 // Fractional seconds left-justify
1641 {
1642 int32_t minDigits = (count > 3) ? 3 : count;
1643 if (count == 1) {
1644 value /= 100;
1645 } else if (count == 2) {
1646 value /= 10;
1647 }
1648 zeroPaddingNumber(currentNumberFormat, appendTo, value, minDigits, maxIntCount);
1649 if (count > 3) {
1650 zeroPaddingNumber(currentNumberFormat, appendTo, 0, count - 3, maxIntCount);
1651 }
1652 }
1653 break;
1654
1655 // for "ee" or "e", use local numeric day-of-the-week
1656 // for "EEEEEE" or "eeeeee", write out the short day-of-the-week name
1657 // for "EEEEE" or "eeeee", write out the narrow day-of-the-week name
1658 // for "EEEE" or "eeee", write out the wide day-of-the-week name
1659 // for "EEE" or "EE" or "E" or "eee", write out the abbreviated day-of-the-week name
1660 case UDAT_DOW_LOCAL_FIELD:
1661 if ( count < 3 ) {
1662 zeroPaddingNumber(currentNumberFormat,appendTo, value, count, maxIntCount);
1663 break;
1664 }
1665 // fall through to EEEEE-EEE handling, but for that we don't want local day-of-week,
1666 // we want standard day-of-week, so first fix value to work for EEEEE-EEE.
1667 value = cal.get(UCAL_DAY_OF_WEEK, status);
1668 if (U_FAILURE(status)) {
1669 return;
1670 }
1671 // fall through, do not break here
1672 U_FALLTHROUGH;
1673 case UDAT_DAY_OF_WEEK_FIELD:
1674 if (count == 5) {
1675 _appendSymbol(appendTo, value, fSymbols->fNarrowWeekdays,
1676 fSymbols->fNarrowWeekdaysCount);
1677 capContextUsageType = DateFormatSymbols::kCapContextUsageDayNarrow;
1678 } else if (count == 4) {
1679 _appendSymbol(appendTo, value, fSymbols->fWeekdays,
1680 fSymbols->fWeekdaysCount);
1681 capContextUsageType = DateFormatSymbols::kCapContextUsageDayFormat;
1682 } else if (count == 6) {
1683 _appendSymbol(appendTo, value, fSymbols->fShorterWeekdays,
1684 fSymbols->fShorterWeekdaysCount);
1685 capContextUsageType = DateFormatSymbols::kCapContextUsageDayFormat;
1686 } else {
1687 _appendSymbol(appendTo, value, fSymbols->fShortWeekdays,
1688 fSymbols->fShortWeekdaysCount);
1689 capContextUsageType = DateFormatSymbols::kCapContextUsageDayFormat;
1690 }
1691 break;
1692
1693 // for "ccc", write out the abbreviated day-of-the-week name
1694 // for "cccc", write out the wide day-of-the-week name
1695 // for "ccccc", use the narrow day-of-the-week name
1696 // for "ccccc", use the short day-of-the-week name
1697 case UDAT_STANDALONE_DAY_FIELD:
1698 if ( count < 3 ) {
1699 zeroPaddingNumber(currentNumberFormat,appendTo, value, 1, maxIntCount);
1700 break;
1701 }
1702 // fall through to alpha DOW handling, but for that we don't want local day-of-week,
1703 // we want standard day-of-week, so first fix value.
1704 value = cal.get(UCAL_DAY_OF_WEEK, status);
1705 if (U_FAILURE(status)) {
1706 return;
1707 }
1708 if (count == 5) {
1709 _appendSymbol(appendTo, value, fSymbols->fStandaloneNarrowWeekdays,
1710 fSymbols->fStandaloneNarrowWeekdaysCount);
1711 capContextUsageType = DateFormatSymbols::kCapContextUsageDayNarrow;
1712 } else if (count == 4) {
1713 _appendSymbol(appendTo, value, fSymbols->fStandaloneWeekdays,
1714 fSymbols->fStandaloneWeekdaysCount);
1715 capContextUsageType = DateFormatSymbols::kCapContextUsageDayStandalone;
1716 } else if (count == 6) {
1717 _appendSymbol(appendTo, value, fSymbols->fStandaloneShorterWeekdays,
1718 fSymbols->fStandaloneShorterWeekdaysCount);
1719 capContextUsageType = DateFormatSymbols::kCapContextUsageDayStandalone;
1720 } else { // count == 3
1721 _appendSymbol(appendTo, value, fSymbols->fStandaloneShortWeekdays,
1722 fSymbols->fStandaloneShortWeekdaysCount);
1723 capContextUsageType = DateFormatSymbols::kCapContextUsageDayStandalone;
1724 }
1725 break;
1726
1727 // for "a" symbol, write out the whole AM/PM string
1728 case UDAT_AM_PM_FIELD:
1729 if (count < 5) {
1730 _appendSymbol(appendTo, value, fSymbols->fAmPms,
1731 fSymbols->fAmPmsCount);
1732 } else {
1733 _appendSymbol(appendTo, value, fSymbols->fNarrowAmPms,
1734 fSymbols->fNarrowAmPmsCount);
1735 }
1736 break;
1737
1738 // if we see pattern character for UDAT_TIME_SEPARATOR_FIELD (none currently defined),
1739 // write out the time separator string. Leave support in for future definition.
1740 case UDAT_TIME_SEPARATOR_FIELD:
1741 {
1742 UnicodeString separator;
1743 appendTo += fSymbols->getTimeSeparatorString(separator);
1744 }
1745 break;
1746
1747 // for "h" and "hh", write out the hour, adjusting noon and midnight to show up
1748 // as "12"
1749 case UDAT_HOUR1_FIELD:
1750 if (value == 0)
1751 zeroPaddingNumber(currentNumberFormat,appendTo, cal.getLeastMaximum(UCAL_HOUR) + 1, count, maxIntCount);
1752 else
1753 zeroPaddingNumber(currentNumberFormat,appendTo, value, count, maxIntCount);
1754 break;
1755
1756 case UDAT_TIMEZONE_FIELD: // 'z'
1757 case UDAT_TIMEZONE_RFC_FIELD: // 'Z'
1758 case UDAT_TIMEZONE_GENERIC_FIELD: // 'v'
1759 case UDAT_TIMEZONE_SPECIAL_FIELD: // 'V'
1760 case UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD: // 'O'
1761 case UDAT_TIMEZONE_ISO_FIELD: // 'X'
1762 case UDAT_TIMEZONE_ISO_LOCAL_FIELD: // 'x'
1763 {
1764 char16_t zsbuf[ZONE_NAME_U16_MAX];
1765 UnicodeString zoneString(zsbuf, 0, UPRV_LENGTHOF(zsbuf));
1766 const TimeZone& tz = cal.getTimeZone();
1767 UDate date = cal.getTime(status);
1768 const TimeZoneFormat *tzfmt = tzFormat(status);
1769 if (U_SUCCESS(status)) {
1770 switch (patternCharIndex) {
1771 case UDAT_TIMEZONE_FIELD:
1772 if (count < 4) {
1773 // "z", "zz", "zzz"
1774 tzfmt->format(UTZFMT_STYLE_SPECIFIC_SHORT, tz, date, zoneString);
1775 capContextUsageType = DateFormatSymbols::kCapContextUsageMetazoneShort;
1776 } else {
1777 // "zzzz" or longer
1778 tzfmt->format(UTZFMT_STYLE_SPECIFIC_LONG, tz, date, zoneString);
1779 capContextUsageType = DateFormatSymbols::kCapContextUsageMetazoneLong;
1780 }
1781 break;
1782 case UDAT_TIMEZONE_RFC_FIELD:
1783 if (count < 4) {
1784 // "Z"
1785 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL, tz, date, zoneString);
1786 } else if (count == 5) {
1787 // "ZZZZZ"
1788 tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_FULL, tz, date, zoneString);
1789 } else {
1790 // "ZZ", "ZZZ", "ZZZZ"
1791 tzfmt->format(UTZFMT_STYLE_LOCALIZED_GMT, tz, date, zoneString);
1792 }
1793 break;
1794 case UDAT_TIMEZONE_GENERIC_FIELD:
1795 if (count == 1) {
1796 // "v"
1797 tzfmt->format(UTZFMT_STYLE_GENERIC_SHORT, tz, date, zoneString);
1798 capContextUsageType = DateFormatSymbols::kCapContextUsageMetazoneShort;
1799 } else if (count == 4) {
1800 // "vvvv"
1801 tzfmt->format(UTZFMT_STYLE_GENERIC_LONG, tz, date, zoneString);
1802 capContextUsageType = DateFormatSymbols::kCapContextUsageMetazoneLong;
1803 }
1804 break;
1805 case UDAT_TIMEZONE_SPECIAL_FIELD:
1806 if (count == 1) {
1807 // "V"
1808 tzfmt->format(UTZFMT_STYLE_ZONE_ID_SHORT, tz, date, zoneString);
1809 } else if (count == 2) {
1810 // "VV"
1811 tzfmt->format(UTZFMT_STYLE_ZONE_ID, tz, date, zoneString);
1812 } else if (count == 3) {
1813 // "VVV"
1814 tzfmt->format(UTZFMT_STYLE_EXEMPLAR_LOCATION, tz, date, zoneString);
1815 } else if (count == 4) {
1816 // "VVVV"
1817 tzfmt->format(UTZFMT_STYLE_GENERIC_LOCATION, tz, date, zoneString);
1818 capContextUsageType = DateFormatSymbols::kCapContextUsageZoneLong;
1819 }
1820 break;
1821 case UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD:
1822 if (count == 1) {
1823 // "O"
1824 tzfmt->format(UTZFMT_STYLE_LOCALIZED_GMT_SHORT, tz, date, zoneString);
1825 } else if (count == 4) {
1826 // "OOOO"
1827 tzfmt->format(UTZFMT_STYLE_LOCALIZED_GMT, tz, date, zoneString);
1828 }
1829 break;
1830 case UDAT_TIMEZONE_ISO_FIELD:
1831 if (count == 1) {
1832 // "X"
1833 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_SHORT, tz, date, zoneString);
1834 } else if (count == 2) {
1835 // "XX"
1836 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_FIXED, tz, date, zoneString);
1837 } else if (count == 3) {
1838 // "XXX"
1839 tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_FIXED, tz, date, zoneString);
1840 } else if (count == 4) {
1841 // "XXXX"
1842 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_FULL, tz, date, zoneString);
1843 } else if (count == 5) {
1844 // "XXXXX"
1845 tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_FULL, tz, date, zoneString);
1846 }
1847 break;
1848 case UDAT_TIMEZONE_ISO_LOCAL_FIELD:
1849 if (count == 1) {
1850 // "x"
1851 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_LOCAL_SHORT, tz, date, zoneString);
1852 } else if (count == 2) {
1853 // "xx"
1854 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_LOCAL_FIXED, tz, date, zoneString);
1855 } else if (count == 3) {
1856 // "xxx"
1857 tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FIXED, tz, date, zoneString);
1858 } else if (count == 4) {
1859 // "xxxx"
1860 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL, tz, date, zoneString);
1861 } else if (count == 5) {
1862 // "xxxxx"
1863 tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FULL, tz, date, zoneString);
1864 }
1865 break;
1866 default:
1867 UPRV_UNREACHABLE_EXIT;
1868 }
1869 }
1870 appendTo += zoneString;
1871 }
1872 break;
1873
1874 case UDAT_QUARTER_FIELD:
1875 if (count >= 5)
1876 _appendSymbol(appendTo, value/3, fSymbols->fNarrowQuarters,
1877 fSymbols->fNarrowQuartersCount);
1878 else if (count == 4)
1879 _appendSymbol(appendTo, value/3, fSymbols->fQuarters,
1880 fSymbols->fQuartersCount);
1881 else if (count == 3)
1882 _appendSymbol(appendTo, value/3, fSymbols->fShortQuarters,
1883 fSymbols->fShortQuartersCount);
1884 else
1885 zeroPaddingNumber(currentNumberFormat,appendTo, (value/3) + 1, count, maxIntCount);
1886 break;
1887
1888 case UDAT_STANDALONE_QUARTER_FIELD:
1889 if (count >= 5)
1890 _appendSymbol(appendTo, value/3, fSymbols->fStandaloneNarrowQuarters,
1891 fSymbols->fStandaloneNarrowQuartersCount);
1892 else if (count == 4)
1893 _appendSymbol(appendTo, value/3, fSymbols->fStandaloneQuarters,
1894 fSymbols->fStandaloneQuartersCount);
1895 else if (count == 3)
1896 _appendSymbol(appendTo, value/3, fSymbols->fStandaloneShortQuarters,
1897 fSymbols->fStandaloneShortQuartersCount);
1898 else
1899 zeroPaddingNumber(currentNumberFormat,appendTo, (value/3) + 1, count, maxIntCount);
1900 break;
1901
1902 case UDAT_AM_PM_MIDNIGHT_NOON_FIELD:
1903 {
1904 const UnicodeString *toAppend = nullptr;
1905 int32_t hour = cal.get(UCAL_HOUR_OF_DAY, status);
1906
1907 // Note: "midnight" can be ambiguous as to whether it refers to beginning of day or end of day.
1908 // For ICU 57 output of "midnight" is temporarily suppressed.
1909
1910 // For "midnight" and "noon":
1911 // Time, as displayed, must be exactly noon or midnight.
1912 // This means minutes and seconds, if present, must be zero.
1913 if ((/*hour == 0 ||*/ hour == 12) &&
1914 (!fHasMinute || cal.get(UCAL_MINUTE, status) == 0) &&
1915 (!fHasSecond || cal.get(UCAL_SECOND, status) == 0)) {
1916 // Stealing am/pm value to use as our array index.
1917 // It works out: am/midnight are both 0, pm/noon are both 1,
1918 // 12 am is 12 midnight, and 12 pm is 12 noon.
1919 int32_t val = cal.get(UCAL_AM_PM, status);
1920
1921 if (count <= 3) {
1922 toAppend = &fSymbols->fAbbreviatedDayPeriods[val];
1923 } else if (count == 4 || count > 5) {
1924 toAppend = &fSymbols->fWideDayPeriods[val];
1925 } else { // count == 5
1926 toAppend = &fSymbols->fNarrowDayPeriods[val];
1927 }
1928 }
1929
1930 // toAppend is nullptr if time isn't exactly midnight or noon (as displayed).
1931 // toAppend is bogus if time is midnight or noon, but no localized string exists.
1932 // In either case, fall back to am/pm.
1933 if (toAppend == nullptr || toAppend->isBogus()) {
1934 // Reformat with identical arguments except ch, now changed to 'a'.
1935 // We are passing a different fieldToOutput because we want to add
1936 // 'b' to field position. This makes this fallback stable when
1937 // there is a data change on locales.
1938 subFormat(appendTo, u'a', count, capitalizationContext, fieldNum, u'b', handler, cal, status);
1939 return;
1940 } else {
1941 appendTo += *toAppend;
1942 }
1943
1944 break;
1945 }
1946
1947 case UDAT_FLEXIBLE_DAY_PERIOD_FIELD:
1948 {
1949 // TODO: Maybe fetch the DayperiodRules during initialization (instead of at the first
1950 // loading of an instance) if a relevant pattern character (b or B) is used.
1951 const DayPeriodRules *ruleSet = DayPeriodRules::getInstance(this->getSmpFmtLocale(), status);
1952 if (U_FAILURE(status)) {
1953 // Data doesn't conform to spec, therefore loading failed.
1954 break;
1955 }
1956 if (ruleSet == nullptr) {
1957 // Data doesn't exist for the locale we're looking for.
1958 // Falling back to am/pm.
1959 // We are passing a different fieldToOutput because we want to add
1960 // 'B' to field position. This makes this fallback stable when
1961 // there is a data change on locales.
1962 subFormat(appendTo, u'a', count, capitalizationContext, fieldNum, u'B', handler, cal, status);
1963 return;
1964 }
1965
1966 // Get current display time.
1967 int32_t hour = cal.get(UCAL_HOUR_OF_DAY, status);
1968 int32_t minute = 0;
1969 if (fHasMinute) {
1970 minute = cal.get(UCAL_MINUTE, status);
1971 }
1972 int32_t second = 0;
1973 if (fHasSecond) {
1974 second = cal.get(UCAL_SECOND, status);
1975 }
1976
1977 // Determine day period.
1978 DayPeriodRules::DayPeriod periodType;
1979 if (hour == 0 && minute == 0 && second == 0 && ruleSet->hasMidnight()) {
1980 periodType = DayPeriodRules::DAYPERIOD_MIDNIGHT;
1981 } else if (hour == 12 && minute == 0 && second == 0 && ruleSet->hasNoon()) {
1982 periodType = DayPeriodRules::DAYPERIOD_NOON;
1983 } else {
1984 periodType = ruleSet->getDayPeriodForHour(hour);
1985 }
1986
1987 // Rule set exists, therefore periodType can't be UNKNOWN.
1988 // Get localized string.
1989 U_ASSERT(periodType != DayPeriodRules::DAYPERIOD_UNKNOWN);
1990 UnicodeString *toAppend = nullptr;
1991 int32_t index;
1992
1993 // Note: "midnight" can be ambiguous as to whether it refers to beginning of day or end of day.
1994 // For ICU 57 output of "midnight" is temporarily suppressed.
1995
1996 if (periodType != DayPeriodRules::DAYPERIOD_AM &&
1997 periodType != DayPeriodRules::DAYPERIOD_PM &&
1998 periodType != DayPeriodRules::DAYPERIOD_MIDNIGHT) {
1999 index = static_cast<int32_t>(periodType);
2000 if (count <= 3) {
2001 toAppend = &fSymbols->fAbbreviatedDayPeriods[index]; // i.e. short
2002 } else if (count == 4 || count > 5) {
2003 toAppend = &fSymbols->fWideDayPeriods[index];
2004 } else { // count == 5
2005 toAppend = &fSymbols->fNarrowDayPeriods[index];
2006 }
2007 }
2008
2009 // Fallback schedule:
2010 // Midnight/Noon -> General Periods -> AM/PM.
2011
2012 // Midnight/Noon -> General Periods.
2013 if ((toAppend == nullptr || toAppend->isBogus()) &&
2014 (periodType == DayPeriodRules::DAYPERIOD_MIDNIGHT ||
2015 periodType == DayPeriodRules::DAYPERIOD_NOON)) {
2016 periodType = ruleSet->getDayPeriodForHour(hour);
2017 index = static_cast<int32_t>(periodType);
2018
2019 if (count <= 3) {
2020 toAppend = &fSymbols->fAbbreviatedDayPeriods[index]; // i.e. short
2021 } else if (count == 4 || count > 5) {
2022 toAppend = &fSymbols->fWideDayPeriods[index];
2023 } else { // count == 5
2024 toAppend = &fSymbols->fNarrowDayPeriods[index];
2025 }
2026 }
2027
2028 // General Periods -> AM/PM.
2029 if (periodType == DayPeriodRules::DAYPERIOD_AM ||
2030 periodType == DayPeriodRules::DAYPERIOD_PM ||
2031 toAppend->isBogus()) {
2032 // We are passing a different fieldToOutput because we want to add
2033 // 'B' to field position iterator. This makes this fallback stable when
2034 // there is a data change on locales.
2035 subFormat(appendTo, u'a', count, capitalizationContext, fieldNum, u'B', handler, cal, status);
2036 return;
2037 }
2038 else {
2039 appendTo += *toAppend;
2040 }
2041
2042 break;
2043 }
2044
2045 // all of the other pattern symbols can be formatted as simple numbers with
2046 // appropriate zero padding
2047 default:
2048 zeroPaddingNumber(currentNumberFormat,appendTo, value, count, maxIntCount);
2049 break;
2050 }
2051 #if !UCONFIG_NO_BREAK_ITERATION
2052 // if first field, check to see whether we need to and are able to titlecase it
2053 if (fieldNum == 0 && fCapitalizationBrkIter != nullptr && appendTo.length() > beginOffset &&
2054 u_islower(appendTo.char32At(beginOffset))) {
2055 UBool titlecase = false;
2056 switch (capitalizationContext) {
2057 case UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE:
2058 titlecase = true;
2059 break;
2060 case UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU:
2061 titlecase = fSymbols->fCapitalization[capContextUsageType][0];
2062 break;
2063 case UDISPCTX_CAPITALIZATION_FOR_STANDALONE:
2064 titlecase = fSymbols->fCapitalization[capContextUsageType][1];
2065 break;
2066 default:
2067 // titlecase = false;
2068 break;
2069 }
2070 if (titlecase) {
2071 BreakIterator* const mutableCapitalizationBrkIter = fCapitalizationBrkIter->clone();
2072 UnicodeString firstField(appendTo, beginOffset);
2073 firstField.toTitle(mutableCapitalizationBrkIter, fLocale, U_TITLECASE_NO_LOWERCASE | U_TITLECASE_NO_BREAK_ADJUSTMENT);
2074 appendTo.replaceBetween(beginOffset, appendTo.length(), firstField);
2075 delete mutableCapitalizationBrkIter;
2076 }
2077 }
2078 #endif
2079
2080 handler.addAttribute(DateFormatSymbols::getPatternCharIndex(fieldToOutput), beginOffset, appendTo.length());
2081 }
2082
2083 //----------------------------------------------------------------------
2084
2085 void SimpleDateFormat::adoptNumberFormat(NumberFormat *formatToAdopt) {
2086 // Null out the fast formatter, it references fNumberFormat which we're
2087 // about to invalidate
2088 delete fSimpleNumberFormatter;
2089 fSimpleNumberFormatter = nullptr;
2090
2091 fixNumberFormatForDates(*formatToAdopt);
2092 delete fNumberFormat;
2093 fNumberFormat = formatToAdopt;
2094
2095 // We successfully set the default number format. Now delete the overrides
2096 // (can't fail).
2097 if (fSharedNumberFormatters) {
2098 freeSharedNumberFormatters(fSharedNumberFormatters);
2099 fSharedNumberFormatters = nullptr;
2100 }
2101
2102 // Recompute fSimpleNumberFormatter if necessary
2103 UErrorCode localStatus = U_ZERO_ERROR;
2104 initSimpleNumberFormatter(localStatus);
2105 }
2106
2107 void SimpleDateFormat::adoptNumberFormat(const UnicodeString& fields, NumberFormat *formatToAdopt, UErrorCode &status){
2108 fixNumberFormatForDates(*formatToAdopt);
2109 LocalPointer<NumberFormat> fmt(formatToAdopt);
2110 if (U_FAILURE(status)) {
2111 return;
2112 }
2113
2114 // We must ensure fSharedNumberFormatters is allocated.
2115 if (fSharedNumberFormatters == nullptr) {
2116 fSharedNumberFormatters = allocSharedNumberFormatters();
2117 if (fSharedNumberFormatters == nullptr) {
2118 status = U_MEMORY_ALLOCATION_ERROR;
2119 return;
2120 }
2121 }
2122 const SharedNumberFormat *newFormat = createSharedNumberFormat(fmt.orphan());
2123 if (newFormat == nullptr) {
2124 status = U_MEMORY_ALLOCATION_ERROR;
2125 return;
2126 }
2127 for (int i=0; i<fields.length(); i++) {
2128 char16_t field = fields.charAt(i);
2129 // if the pattern character is unrecognized, signal an error and bail out
2130 UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(field);
2131 if (patternCharIndex == UDAT_FIELD_COUNT) {
2132 status = U_INVALID_FORMAT_ERROR;
2133 newFormat->deleteIfZeroRefCount();
2134 return;
2135 }
2136
2137 // Set the number formatter in the table
2138 SharedObject::copyPtr(
2139 newFormat, fSharedNumberFormatters[patternCharIndex]);
2140 }
2141 newFormat->deleteIfZeroRefCount();
2142 }
2143
2144 const NumberFormat *
2145 SimpleDateFormat::getNumberFormatForField(char16_t field) const {
2146 UDateFormatField index = DateFormatSymbols::getPatternCharIndex(field);
2147 if (index == UDAT_FIELD_COUNT) {
2148 return nullptr;
2149 }
2150 return getNumberFormatByIndex(index);
2151 }
2152
2153 //----------------------------------------------------------------------
2154 void
2155 SimpleDateFormat::zeroPaddingNumber(
2156 const NumberFormat *currentNumberFormat,
2157 UnicodeString &appendTo,
2158 int32_t value, int32_t minDigits, int32_t maxDigits) const
2159 {
2160
2161 if (currentNumberFormat == fNumberFormat && fSimpleNumberFormatter) {
2162 // Can use fast path
2163 // We create UFormattedNumberData ourselves to avoid a heap allocation
2164 // and corresponding free. Set the pointer to null afterwards to prevent
2165 // the implementation from attempting to free it.
2166 UErrorCode localStatus = U_ZERO_ERROR;
2167 number::impl::UFormattedNumberData data;
2168 data.quantity.setToLong(value);
2169 number::SimpleNumber number(&data, localStatus);
2170 number.setMinimumIntegerDigits(minDigits, localStatus);
2171 number.setMaximumIntegerDigits(maxDigits, localStatus);
2172
2173 number::FormattedNumber result = fSimpleNumberFormatter->format(std::move(number), localStatus);
2174 if (U_FAILURE(localStatus)) {
2175 result.fData = nullptr;
2176 return;
2177 }
2178 UnicodeStringAppendable appendable(appendTo);
2179 result.appendTo(appendable, localStatus);
2180 result.fData = nullptr;
2181 return;
2182 }
2183
2184 // Check for RBNF (no clone necessary)
2185 const auto* rbnf = dynamic_cast<const RuleBasedNumberFormat*>(currentNumberFormat);
2186 if (rbnf != nullptr) {
2187 FieldPosition pos(FieldPosition::DONT_CARE);
2188 rbnf->format(value, appendTo, pos); // 3rd arg is there to speed up processing
2189 return;
2190 }
2191
2192 // Fall back to slow path (clone and mutate the NumberFormat)
2193 if (currentNumberFormat != nullptr) {
2194 FieldPosition pos(FieldPosition::DONT_CARE);
2195 LocalPointer<NumberFormat> nf(currentNumberFormat->clone());
2196 nf->setMinimumIntegerDigits(minDigits);
2197 nf->setMaximumIntegerDigits(maxDigits);
2198 nf->format(value, appendTo, pos); // 3rd arg is there to speed up processing
2199 }
2200 }
2201
2202 //----------------------------------------------------------------------
2203
2204 /**
2205 * Return true if the given format character, occurring count
2206 * times, represents a numeric field.
2207 */
2208 UBool SimpleDateFormat::isNumeric(char16_t formatChar, int32_t count) {
2209 return DateFormatSymbols::isNumericPatternChar(formatChar, count);
2210 }
2211
2212 UBool
2213 SimpleDateFormat::isAtNumericField(const UnicodeString &pattern, int32_t patternOffset) {
2214 if (patternOffset >= pattern.length()) {
2215 // not at any field
2216 return false;
2217 }
2218 char16_t ch = pattern.charAt(patternOffset);
2219 UDateFormatField f = DateFormatSymbols::getPatternCharIndex(ch);
2220 if (f == UDAT_FIELD_COUNT) {
2221 // not at any field
2222 return false;
2223 }
2224 int32_t i = patternOffset;
2225 while (pattern.charAt(++i) == ch) {}
2226 return DateFormatSymbols::isNumericField(f, i - patternOffset);
2227 }
2228
2229 UBool
2230 SimpleDateFormat::isAfterNonNumericField(const UnicodeString &pattern, int32_t patternOffset) {
2231 if (patternOffset <= 0) {
2232 // not after any field
2233 return false;
2234 }
2235 char16_t ch = pattern.charAt(--patternOffset);
2236 UDateFormatField f = DateFormatSymbols::getPatternCharIndex(ch);
2237 if (f == UDAT_FIELD_COUNT) {
2238 // not after any field
2239 return false;
2240 }
2241 int32_t i = patternOffset;
2242 while (pattern.charAt(--i) == ch) {}
2243 return !DateFormatSymbols::isNumericField(f, patternOffset - i);
2244 }
2245
2246 void
2247 SimpleDateFormat::parse(const UnicodeString& text, Calendar& cal, ParsePosition& parsePos) const
2248 {
2249 UErrorCode status = U_ZERO_ERROR;
2250 int32_t pos = parsePos.getIndex();
2251 if(parsePos.getIndex() < 0) {
2252 parsePos.setErrorIndex(0);
2253 return;
2254 }
2255 int32_t start = pos;
2256
2257 // Hold the day period until everything else is parsed, because we need
2258 // the hour to interpret time correctly.
2259 int32_t dayPeriodInt = -1;
2260
2261 UBool ambiguousYear[] = { false };
2262 int32_t saveHebrewMonth = -1;
2263 int32_t count = 0;
2264 UTimeZoneFormatTimeType tzTimeType = UTZFMT_TIME_TYPE_UNKNOWN;
2265
2266 // For parsing abutting numeric fields. 'abutPat' is the
2267 // offset into 'pattern' of the first of 2 or more abutting
2268 // numeric fields. 'abutStart' is the offset into 'text'
2269 // where parsing the fields begins. 'abutPass' starts off as 0
2270 // and increments each time we try to parse the fields.
2271 int32_t abutPat = -1; // If >=0, we are in a run of abutting numeric fields
2272 int32_t abutStart = 0;
2273 int32_t abutPass = 0;
2274 UBool inQuote = false;
2275
2276 MessageFormat * numericLeapMonthFormatter = nullptr;
2277
2278 Calendar* calClone = nullptr;
2279 Calendar *workCal = &cal;
2280 if (&cal != fCalendar && typeid(cal) != typeid(*fCalendar)) {
2281 // Different calendar type
2282 // We use the time/zone from the input calendar, but
2283 // do not use the input calendar for field calculation.
2284 calClone = fCalendar->clone();
2285 if (calClone != nullptr) {
2286 calClone->setTime(cal.getTime(status),status);
2287 if (U_FAILURE(status)) {
2288 goto ExitParse;
2289 }
2290 calClone->setTimeZone(cal.getTimeZone());
2291 workCal = calClone;
2292 } else {
2293 status = U_MEMORY_ALLOCATION_ERROR;
2294 goto ExitParse;
2295 }
2296 }
2297
2298 if (fSymbols->fLeapMonthPatterns != nullptr && fSymbols->fLeapMonthPatternsCount >= DateFormatSymbols::kMonthPatternsCount) {
2299 numericLeapMonthFormatter = new MessageFormat(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternNumeric], fLocale, status);
2300 if (numericLeapMonthFormatter == nullptr) {
2301 status = U_MEMORY_ALLOCATION_ERROR;
2302 goto ExitParse;
2303 } else if (U_FAILURE(status)) {
2304 goto ExitParse; // this will delete numericLeapMonthFormatter
2305 }
2306 }
2307
2308 for (int32_t i=0; i<fPattern.length(); ++i) {
2309 char16_t ch = fPattern.charAt(i);
2310
2311 // Handle alphabetic field characters.
2312 if (!inQuote && isSyntaxChar(ch)) {
2313 int32_t fieldPat = i;
2314
2315 // Count the length of this field specifier
2316 count = 1;
2317 while ((i+1)<fPattern.length() &&
2318 fPattern.charAt(i+1) == ch) {
2319 ++count;
2320 ++i;
2321 }
2322
2323 if (isNumeric(ch, count)) {
2324 if (abutPat < 0) {
2325 // Determine if there is an abutting numeric field.
2326 // Record the start of a set of abutting numeric fields.
2327 if (isAtNumericField(fPattern, i + 1)) {
2328 abutPat = fieldPat;
2329 abutStart = pos;
2330 abutPass = 0;
2331 }
2332 }
2333 } else {
2334 abutPat = -1; // End of any abutting fields
2335 }
2336
2337 // Handle fields within a run of abutting numeric fields. Take
2338 // the pattern "HHmmss" as an example. We will try to parse
2339 // 2/2/2 characters of the input text, then if that fails,
2340 // 1/2/2. We only adjust the width of the leftmost field; the
2341 // others remain fixed. This allows "123456" => 12:34:56, but
2342 // "12345" => 1:23:45. Likewise, for the pattern "yyyyMMdd" we
2343 // try 4/2/2, 3/2/2, 2/2/2, and finally 1/2/2.
2344 if (abutPat >= 0) {
2345 // If we are at the start of a run of abutting fields, then
2346 // shorten this field in each pass. If we can't shorten
2347 // this field any more, then the parse of this set of
2348 // abutting numeric fields has failed.
2349 if (fieldPat == abutPat) {
2350 count -= abutPass++;
2351 if (count == 0) {
2352 status = U_PARSE_ERROR;
2353 goto ExitParse;
2354 }
2355 }
2356
2357 pos = subParse(text, pos, ch, count,
2358 true, false, ambiguousYear, saveHebrewMonth, *workCal, i, numericLeapMonthFormatter, &tzTimeType);
2359
2360 // If the parse fails anywhere in the run, back up to the
2361 // start of the run and retry.
2362 if (pos < 0) {
2363 i = abutPat - 1;
2364 pos = abutStart;
2365 continue;
2366 }
2367 }
2368
2369 // Handle non-numeric fields and non-abutting numeric
2370 // fields.
2371 else if (ch != 0x6C) { // pattern char 'l' (SMALL LETTER L) just gets ignored
2372 int32_t s = subParse(text, pos, ch, count,
2373 false, true, ambiguousYear, saveHebrewMonth, *workCal, i, numericLeapMonthFormatter, &tzTimeType, &dayPeriodInt);
2374
2375 if (s == -pos-1) {
2376 // era not present, in special cases allow this to continue
2377 // from the position where the era was expected
2378 s = pos;
2379
2380 if (i+1 < fPattern.length()) {
2381 // move to next pattern character
2382 char16_t c = fPattern.charAt(i+1);
2383
2384 // check for whitespace
2385 if (PatternProps::isWhiteSpace(c)) {
2386 i++;
2387 // Advance over run in pattern
2388 while ((i+1)<fPattern.length() &&
2389 PatternProps::isWhiteSpace(fPattern.charAt(i+1))) {
2390 ++i;
2391 }
2392 }
2393 }
2394 }
2395 else if (s <= 0) {
2396 status = U_PARSE_ERROR;
2397 goto ExitParse;
2398 }
2399 pos = s;
2400 }
2401 }
2402
2403 // Handle literal pattern characters. These are any
2404 // quoted characters and non-alphabetic unquoted
2405 // characters.
2406 else {
2407
2408 abutPat = -1; // End of any abutting fields
2409
2410 if (! matchLiterals(fPattern, i, text, pos, getBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, status), getBooleanAttribute(UDAT_PARSE_PARTIAL_LITERAL_MATCH, status), isLenient())) {
2411 status = U_PARSE_ERROR;
2412 goto ExitParse;
2413 }
2414 }
2415 }
2416
2417 // Special hack for trailing "." after non-numeric field.
2418 if (text.charAt(pos) == 0x2e && getBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, status)) {
2419 // only do if the last field is not numeric
2420 if (isAfterNonNumericField(fPattern, fPattern.length())) {
2421 pos++; // skip the extra "."
2422 }
2423 }
2424
2425 // If dayPeriod is set, use it in conjunction with hour-of-day to determine am/pm.
2426 if (dayPeriodInt >= 0) {
2427 DayPeriodRules::DayPeriod dayPeriod = static_cast<DayPeriodRules::DayPeriod>(dayPeriodInt);
2428 const DayPeriodRules *ruleSet = DayPeriodRules::getInstance(this->getSmpFmtLocale(), status);
2429
2430 if (!cal.isSet(UCAL_HOUR) && !cal.isSet(UCAL_HOUR_OF_DAY)) {
2431 // If hour is not set, set time to the midpoint of current day period, overwriting
2432 // minutes if it's set.
2433 double midPoint = ruleSet->getMidPointForDayPeriod(dayPeriod, status);
2434
2435 // If we can't get midPoint we do nothing.
2436 if (U_SUCCESS(status)) {
2437 // Truncate midPoint toward zero to get the hour.
2438 // Any leftover means it was a half-hour.
2439 int32_t midPointHour = static_cast<int32_t>(midPoint);
2440 int32_t midPointMinute = (midPoint - midPointHour) > 0 ? 30 : 0;
2441
2442 // No need to set am/pm because hour-of-day is set last therefore takes precedence.
2443 cal.set(UCAL_HOUR_OF_DAY, midPointHour);
2444 cal.set(UCAL_MINUTE, midPointMinute);
2445 }
2446 } else {
2447 int hourOfDay;
2448
2449 if (cal.isSet(UCAL_HOUR_OF_DAY)) { // Hour is parsed in 24-hour format.
2450 hourOfDay = cal.get(UCAL_HOUR_OF_DAY, status);
2451 } else { // Hour is parsed in 12-hour format.
2452 hourOfDay = cal.get(UCAL_HOUR, status);
2453 // cal.get() turns 12 to 0 for 12-hour time; change 0 to 12
2454 // so 0 unambiguously means a 24-hour time from above.
2455 if (hourOfDay == 0) { hourOfDay = 12; }
2456 }
2457 U_ASSERT(0 <= hourOfDay && hourOfDay <= 23);
2458
2459
2460 // If hour-of-day is 0 or 13 thru 23 then input time in unambiguously in 24-hour format.
2461 if (hourOfDay == 0 || (13 <= hourOfDay && hourOfDay <= 23)) {
2462 // Make hour-of-day take precedence over (hour + am/pm) by setting it again.
2463 cal.set(UCAL_HOUR_OF_DAY, hourOfDay);
2464 } else {
2465 // We have a 12-hour time and need to choose between am and pm.
2466 // Behave as if dayPeriod spanned 6 hours each way from its center point.
2467 // This will parse correctly for consistent time + period (e.g. 10 at night) as
2468 // well as provide a reasonable recovery for inconsistent time + period (e.g.
2469 // 9 in the afternoon).
2470
2471 // Assume current time is in the AM.
2472 // - Change 12 back to 0 for easier handling of 12am.
2473 // - Append minutes as fractional hours because e.g. 8:15 and 8:45 could be parsed
2474 // into different half-days if center of dayPeriod is at 14:30.
2475 // - cal.get(MINUTE) will return 0 if MINUTE is unset, which works.
2476 if (hourOfDay == 12) { hourOfDay = 0; }
2477 double currentHour = hourOfDay + (cal.get(UCAL_MINUTE, status)) / 60.0;
2478 double midPointHour = ruleSet->getMidPointForDayPeriod(dayPeriod, status);
2479
2480 if (U_SUCCESS(status)) {
2481 double hoursAheadMidPoint = currentHour - midPointHour;
2482
2483 // Assume current time is in the AM.
2484 if (-6 <= hoursAheadMidPoint && hoursAheadMidPoint < 6) {
2485 // Assumption holds; set time as such.
2486 cal.set(UCAL_AM_PM, 0);
2487 } else {
2488 cal.set(UCAL_AM_PM, 1);
2489 }
2490 }
2491 }
2492 }
2493 }
2494
2495 // At this point the fields of Calendar have been set. Calendar
2496 // will fill in default values for missing fields when the time
2497 // is computed.
2498
2499 parsePos.setIndex(pos);
2500
2501 // This part is a problem: When we call parsedDate.after, we compute the time.
2502 // Take the date April 3 2004 at 2:30 am. When this is first set up, the year
2503 // will be wrong if we're parsing a 2-digit year pattern. It will be 1904.
2504 // April 3 1904 is a Sunday (unlike 2004) so it is the DST onset day. 2:30 am
2505 // is therefore an "impossible" time, since the time goes from 1:59 to 3:00 am
2506 // on that day. It is therefore parsed out to fields as 3:30 am. Then we
2507 // add 100 years, and get April 3 2004 at 3:30 am. Note that April 3 2004 is
2508 // a Saturday, so it can have a 2:30 am -- and it should. [LIU]
2509 /*
2510 UDate parsedDate = calendar.getTime();
2511 if( ambiguousYear[0] && !parsedDate.after(fDefaultCenturyStart) ) {
2512 calendar.add(Calendar.YEAR, 100);
2513 parsedDate = calendar.getTime();
2514 }
2515 */
2516 // Because of the above condition, save off the fields in case we need to readjust.
2517 // The procedure we use here is not particularly efficient, but there is no other
2518 // way to do this given the API restrictions present in Calendar. We minimize
2519 // inefficiency by only performing this computation when it might apply, that is,
2520 // when the two-digit year is equal to the start year, and thus might fall at the
2521 // front or the back of the default century. This only works because we adjust
2522 // the year correctly to start with in other cases -- see subParse().
2523 if (ambiguousYear[0] || tzTimeType != UTZFMT_TIME_TYPE_UNKNOWN) // If this is true then the two-digit year == the default start year
2524 {
2525 // We need a copy of the fields, and we need to avoid triggering a call to
2526 // complete(), which will recalculate the fields. Since we can't access
2527 // the fields[] array in Calendar, we clone the entire object. This will
2528 // stop working if Calendar.clone() is ever rewritten to call complete().
2529 Calendar *copy;
2530 if (ambiguousYear[0]) {
2531 copy = cal.clone();
2532 // Check for failed cloning.
2533 if (copy == nullptr) {
2534 status = U_MEMORY_ALLOCATION_ERROR;
2535 goto ExitParse;
2536 }
2537 UDate parsedDate = copy->getTime(status);
2538 // {sfb} check internalGetDefaultCenturyStart
2539 if (fHaveDefaultCentury && (parsedDate < fDefaultCenturyStart)) {
2540 // We can't use add here because that does a complete() first.
2541 cal.set(UCAL_YEAR, fDefaultCenturyStartYear + 100);
2542 }
2543 delete copy;
2544 }
2545
2546 if (tzTimeType != UTZFMT_TIME_TYPE_UNKNOWN) {
2547 copy = cal.clone();
2548 // Check for failed cloning.
2549 if (copy == nullptr) {
2550 status = U_MEMORY_ALLOCATION_ERROR;
2551 goto ExitParse;
2552 }
2553 const TimeZone & tz = cal.getTimeZone();
2554 BasicTimeZone *btz = nullptr;
2555
2556 if (dynamic_cast<const OlsonTimeZone *>(&tz) != nullptr
2557 || dynamic_cast<const SimpleTimeZone *>(&tz) != nullptr
2558 || dynamic_cast<const RuleBasedTimeZone *>(&tz) != nullptr
2559 || dynamic_cast<const VTimeZone *>(&tz) != nullptr) {
2560 btz = (BasicTimeZone*)&tz;
2561 }
2562
2563 // Get local millis
2564 copy->set(UCAL_ZONE_OFFSET, 0);
2565 copy->set(UCAL_DST_OFFSET, 0);
2566 UDate localMillis = copy->getTime(status);
2567
2568 // Make sure parsed time zone type (Standard or Daylight)
2569 // matches the rule used by the parsed time zone.
2570 int32_t raw, dst;
2571 if (btz != nullptr) {
2572 if (tzTimeType == UTZFMT_TIME_TYPE_STANDARD) {
2573 btz->getOffsetFromLocal(localMillis,
2574 UCAL_TZ_LOCAL_STANDARD_FORMER, UCAL_TZ_LOCAL_STANDARD_LATTER, raw, dst, status);
2575 } else {
2576 btz->getOffsetFromLocal(localMillis,
2577 UCAL_TZ_LOCAL_DAYLIGHT_FORMER, UCAL_TZ_LOCAL_DAYLIGHT_LATTER, raw, dst, status);
2578 }
2579 } else {
2580 // No good way to resolve ambiguous time at transition,
2581 // but following code work in most case.
2582 tz.getOffset(localMillis, true, raw, dst, status);
2583 }
2584
2585 // Now, compare the results with parsed type, either standard or daylight saving time
2586 int32_t resolvedSavings = dst;
2587 if (tzTimeType == UTZFMT_TIME_TYPE_STANDARD) {
2588 if (dst != 0) {
2589 // Override DST_OFFSET = 0 in the result calendar
2590 resolvedSavings = 0;
2591 }
2592 } else { // tztype == TZTYPE_DST
2593 if (dst == 0) {
2594 if (btz != nullptr) {
2595 // This implementation resolves daylight saving time offset
2596 // closest rule after the given time.
2597 UDate baseTime = localMillis + raw;
2598 UDate time = baseTime;
2599 UDate limit = baseTime + MAX_DAYLIGHT_DETECTION_RANGE;
2600 TimeZoneTransition trs;
2601 UBool trsAvail;
2602
2603 // Search for DST rule after the given time
2604 while (time < limit) {
2605 trsAvail = btz->getNextTransition(time, false, trs);
2606 if (!trsAvail) {
2607 break;
2608 }
2609 resolvedSavings = trs.getTo()->getDSTSavings();
2610 if (resolvedSavings != 0) {
2611 break;
2612 }
2613 time = trs.getTime();
2614 }
2615
2616 if (resolvedSavings == 0) {
2617 // If no DST rule after the given time was found, search for
2618 // DST rule before.
2619 time = baseTime;
2620 limit = baseTime - MAX_DAYLIGHT_DETECTION_RANGE;
2621 while (time > limit) {
2622 trsAvail = btz->getPreviousTransition(time, true, trs);
2623 if (!trsAvail) {
2624 break;
2625 }
2626 resolvedSavings = trs.getFrom()->getDSTSavings();
2627 if (resolvedSavings != 0) {
2628 break;
2629 }
2630 time = trs.getTime() - 1;
2631 }
2632
2633 if (resolvedSavings == 0) {
2634 resolvedSavings = btz->getDSTSavings();
2635 }
2636 }
2637 } else {
2638 resolvedSavings = tz.getDSTSavings();
2639 }
2640 if (resolvedSavings == 0) {
2641 // final fallback
2642 resolvedSavings = U_MILLIS_PER_HOUR;
2643 }
2644 }
2645 }
2646 cal.set(UCAL_ZONE_OFFSET, raw);
2647 cal.set(UCAL_DST_OFFSET, resolvedSavings);
2648 delete copy;
2649 }
2650 }
2651 ExitParse:
2652 // Set the parsed result if local calendar is used
2653 // instead of the input calendar
2654 if (U_SUCCESS(status) && workCal != &cal) {
2655 cal.setTimeZone(workCal->getTimeZone());
2656 cal.setTime(workCal->getTime(status), status);
2657 }
2658
2659 delete numericLeapMonthFormatter;
2660 delete calClone;
2661
2662 // If any Calendar calls failed, we pretend that we
2663 // couldn't parse the string, when in reality this isn't quite accurate--
2664 // we did parse it; the Calendar calls just failed.
2665 if (U_FAILURE(status)) {
2666 parsePos.setErrorIndex(pos);
2667 parsePos.setIndex(start);
2668 }
2669 }
2670
2671 //----------------------------------------------------------------------
2672
2673 static int32_t
2674 matchStringWithOptionalDot(const UnicodeString &text,
2675 int32_t index,
2676 const UnicodeString &data);
2677
2678 int32_t SimpleDateFormat::matchQuarterString(const UnicodeString& text,
2679 int32_t start,
2680 UCalendarDateFields field,
2681 const UnicodeString* data,
2682 int32_t dataCount,
2683 Calendar& cal) const
2684 {
2685 int32_t i = 0;
2686 int32_t count = dataCount;
2687
2688 // There may be multiple strings in the data[] array which begin with
2689 // the same prefix (e.g., Cerven and Cervenec (June and July) in Czech).
2690 // We keep track of the longest match, and return that. Note that this
2691 // unfortunately requires us to test all array elements.
2692 int32_t bestMatchLength = 0, bestMatch = -1;
2693 UnicodeString bestMatchName;
2694
2695 for (; i < count; ++i) {
2696 int32_t matchLength = 0;
2697 if ((matchLength = matchStringWithOptionalDot(text, start, data[i])) > bestMatchLength) {
2698 bestMatchLength = matchLength;
2699 bestMatch = i;
2700 }
2701 }
2702
2703 if (bestMatch >= 0) {
2704 cal.set(field, bestMatch * 3);
2705 return start + bestMatchLength;
2706 }
2707
2708 return -start;
2709 }
2710
2711 int32_t SimpleDateFormat::matchDayPeriodStrings(const UnicodeString& text, int32_t start,
2712 const UnicodeString* data, int32_t dataCount,
2713 int32_t &dayPeriod) const
2714 {
2715
2716 int32_t bestMatchLength = 0, bestMatch = -1;
2717
2718 for (int32_t i = 0; i < dataCount; ++i) {
2719 int32_t matchLength = 0;
2720 if ((matchLength = matchStringWithOptionalDot(text, start, data[i])) > bestMatchLength) {
2721 bestMatchLength = matchLength;
2722 bestMatch = i;
2723 }
2724 }
2725
2726 if (bestMatch >= 0) {
2727 dayPeriod = bestMatch;
2728 return start + bestMatchLength;
2729 }
2730
2731 return -start;
2732 }
2733
2734 //----------------------------------------------------------------------
2735 UBool SimpleDateFormat::matchLiterals(const UnicodeString &pattern,
2736 int32_t &patternOffset,
2737 const UnicodeString &text,
2738 int32_t &textOffset,
2739 UBool whitespaceLenient,
2740 UBool partialMatchLenient,
2741 UBool oldLeniency)
2742 {
2743 UBool inQuote = false;
2744 UnicodeString literal;
2745 int32_t i = patternOffset;
2746
2747 // scan pattern looking for contiguous literal characters
2748 for ( ; i < pattern.length(); i += 1) {
2749 char16_t ch = pattern.charAt(i);
2750
2751 if (!inQuote && isSyntaxChar(ch)) {
2752 break;
2753 }
2754
2755 if (ch == QUOTE) {
2756 // Match a quote literal ('') inside OR outside of quotes
2757 if ((i + 1) < pattern.length() && pattern.charAt(i + 1) == QUOTE) {
2758 i += 1;
2759 } else {
2760 inQuote = !inQuote;
2761 continue;
2762 }
2763 }
2764
2765 literal += ch;
2766 }
2767
2768 // at this point, literal contains the literal text
2769 // and i is the index of the next non-literal pattern character.
2770 int32_t p;
2771 int32_t t = textOffset;
2772
2773 if (whitespaceLenient) {
2774 // trim leading, trailing whitespace from
2775 // the literal text
2776 literal.trim();
2777
2778 // ignore any leading whitespace in the text
2779 while (t < text.length() && u_isWhitespace(text.charAt(t))) {
2780 t += 1;
2781 }
2782 }
2783
2784 for (p = 0; p < literal.length() && t < text.length();) {
2785 UBool needWhitespace = false;
2786
2787 while (p < literal.length() && PatternProps::isWhiteSpace(literal.charAt(p))) {
2788 needWhitespace = true;
2789 p += 1;
2790 }
2791
2792 if (needWhitespace) {
2793 int32_t tStart = t;
2794
2795 while (t < text.length()) {
2796 char16_t tch = text.charAt(t);
2797
2798 if (!u_isUWhiteSpace(tch) && !PatternProps::isWhiteSpace(tch)) {
2799 break;
2800 }
2801
2802 t += 1;
2803 }
2804
2805 // TODO: should we require internal spaces
2806 // in lenient mode? (There won't be any
2807 // leading or trailing spaces)
2808 if (!whitespaceLenient && t == tStart) {
2809 // didn't find matching whitespace:
2810 // an error in strict mode
2811 return false;
2812 }
2813
2814 // In strict mode, this run of whitespace
2815 // may have been at the end.
2816 if (p >= literal.length()) {
2817 break;
2818 }
2819 }
2820 if (t >= text.length() || literal.charAt(p) != text.charAt(t)) {
2821 // Ran out of text, or found a non-matching character:
2822 // OK in lenient mode, an error in strict mode.
2823 if (whitespaceLenient) {
2824 if (t == textOffset && text.charAt(t) == 0x2e &&
2825 isAfterNonNumericField(pattern, patternOffset)) {
2826 // Lenient mode and the literal input text begins with a "." and
2827 // we are after a non-numeric field: We skip the "."
2828 ++t;
2829 continue; // Do not update p.
2830 }
2831 // if it is actual whitespace and we're whitespace lenient it's OK
2832
2833 char16_t wsc = text.charAt(t);
2834 if(PatternProps::isWhiteSpace(wsc)) {
2835 // Lenient mode and it's just whitespace we skip it
2836 ++t;
2837 continue; // Do not update p.
2838 }
2839 }
2840 // hack around oldleniency being a bit of a catch-all bucket and we're just adding support specifically for partial matches
2841 if(partialMatchLenient && oldLeniency) {
2842 break;
2843 }
2844
2845 return false;
2846 }
2847 ++p;
2848 ++t;
2849 }
2850
2851 // At this point if we're in strict mode we have a complete match.
2852 // If we're in lenient mode we may have a partial match, or no
2853 // match at all.
2854 if (p <= 0) {
2855 // no match. Pretend it matched a run of whitespace
2856 // and ignorables in the text.
2857 const UnicodeSet *ignorables = nullptr;
2858 UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(pattern.charAt(i));
2859 if (patternCharIndex != UDAT_FIELD_COUNT) {
2860 ignorables = SimpleDateFormatStaticSets::getIgnorables(patternCharIndex);
2861 }
2862
2863 for (t = textOffset; t < text.length(); t += 1) {
2864 char16_t ch = text.charAt(t);
2865
2866 if (ignorables == nullptr || !ignorables->contains(ch)) {
2867 break;
2868 }
2869 }
2870 }
2871
2872 // if we get here, we've got a complete match.
2873 patternOffset = i - 1;
2874 textOffset = t;
2875
2876 return true;
2877 }
2878
2879 //----------------------------------------------------------------------
2880 // check both wide and abbrev months.
2881 // Does not currently handle monthPattern.
2882 // UCalendarDateFields field = UCAL_MONTH
2883
2884 int32_t SimpleDateFormat::matchAlphaMonthStrings(const UnicodeString& text,
2885 int32_t start,
2886 const UnicodeString* wideData,
2887 const UnicodeString* shortData,
2888 int32_t dataCount,
2889 Calendar& cal) const
2890 {
2891 int32_t i;
2892 int32_t bestMatchLength = 0, bestMatch = -1;
2893
2894 for (i = 0; i < dataCount; ++i) {
2895 int32_t matchLen = 0;
2896 if ((matchLen = matchStringWithOptionalDot(text, start, wideData[i])) > bestMatchLength) {
2897 bestMatch = i;
2898 bestMatchLength = matchLen;
2899 }
2900 }
2901 for (i = 0; i < dataCount; ++i) {
2902 int32_t matchLen = 0;
2903 if ((matchLen = matchStringWithOptionalDot(text, start, shortData[i])) > bestMatchLength) {
2904 bestMatch = i;
2905 bestMatchLength = matchLen;
2906 }
2907 }
2908
2909 if (bestMatch >= 0) {
2910 // Adjustment for Hebrew Calendar month Adar II
2911 if (typeid(cal) == typeid(HebrewCalendar) && bestMatch==13) {
2912 cal.set(UCAL_MONTH,6);
2913 } else {
2914 cal.set(UCAL_MONTH, bestMatch);
2915 }
2916 return start + bestMatchLength;
2917 }
2918
2919 return -start;
2920 }
2921
2922 //----------------------------------------------------------------------
2923
2924 int32_t SimpleDateFormat::matchString(const UnicodeString& text,
2925 int32_t start,
2926 UCalendarDateFields field,
2927 const UnicodeString* data,
2928 int32_t dataCount,
2929 const UnicodeString* monthPattern,
2930 Calendar& cal) const
2931 {
2932 int32_t i = 0;
2933 int32_t count = dataCount;
2934
2935 if (field == UCAL_DAY_OF_WEEK) i = 1;
2936
2937 // There may be multiple strings in the data[] array which begin with
2938 // the same prefix (e.g., Cerven and Cervenec (June and July) in Czech).
2939 // We keep track of the longest match, and return that. Note that this
2940 // unfortunately requires us to test all array elements.
2941 // But this does not really work for cases such as Chuvash in which
2942 // May is "ҫу" and August is "ҫурла"/"ҫур.", hence matchAlphaMonthStrings.
2943 int32_t bestMatchLength = 0, bestMatch = -1;
2944 UnicodeString bestMatchName;
2945 int32_t isLeapMonth = 0;
2946
2947 for (; i < count; ++i) {
2948 int32_t matchLen = 0;
2949 if ((matchLen = matchStringWithOptionalDot(text, start, data[i])) > bestMatchLength) {
2950 bestMatch = i;
2951 bestMatchLength = matchLen;
2952 }
2953
2954 if (monthPattern != nullptr) {
2955 UErrorCode status = U_ZERO_ERROR;
2956 UnicodeString leapMonthName;
2957 SimpleFormatter(*monthPattern, 1, 1, status).format(data[i], leapMonthName, status);
2958 if (U_SUCCESS(status)) {
2959 if ((matchLen = matchStringWithOptionalDot(text, start, leapMonthName)) > bestMatchLength) {
2960 bestMatch = i;
2961 bestMatchLength = matchLen;
2962 isLeapMonth = 1;
2963 }
2964 }
2965 }
2966 }
2967
2968 if (bestMatch >= 0) {
2969 if (field < UCAL_FIELD_COUNT) {
2970 // Adjustment for Hebrew Calendar month Adar II
2971 if (typeid(cal) == typeid(HebrewCalendar) && field==UCAL_MONTH && bestMatch==13) {
2972 cal.set(field,6);
2973 } else {
2974 if (field == UCAL_YEAR) {
2975 bestMatch++; // only get here for cyclic year names, which match 1-based years 1-60
2976 }
2977 cal.set(field, bestMatch);
2978 }
2979 if (monthPattern != nullptr) {
2980 cal.set(UCAL_IS_LEAP_MONTH, isLeapMonth);
2981 }
2982 }
2983
2984 return start + bestMatchLength;
2985 }
2986
2987 return -start;
2988 }
2989
2990 static int32_t
2991 matchStringWithOptionalDot(const UnicodeString &text,
2992 int32_t index,
2993 const UnicodeString &data) {
2994 UErrorCode sts = U_ZERO_ERROR;
2995 int32_t matchLenText = 0;
2996 int32_t matchLenData = 0;
2997
2998 u_caseInsensitivePrefixMatch(text.getBuffer() + index, text.length() - index,
2999 data.getBuffer(), data.length(),
3000 0 /* default case option */,
3001 &matchLenText, &matchLenData,
3002 &sts);
3003 U_ASSERT (U_SUCCESS(sts));
3004
3005 if (matchLenData == data.length() /* normal match */
3006 || (data.charAt(data.length() - 1) == 0x2e
3007 && matchLenData == data.length() - 1 /* match without trailing dot */)) {
3008 return matchLenText;
3009 }
3010
3011 return 0;
3012 }
3013
3014 //----------------------------------------------------------------------
3015
3016 void
3017 SimpleDateFormat::set2DigitYearStart(UDate d, UErrorCode& status)
3018 {
3019 parseAmbiguousDatesAsAfter(d, status);
3020 }
3021
3022 /**
3023 * Private member function that converts the parsed date strings into
3024 * timeFields. Returns -start (for ParsePosition) if failed.
3025 */
3026 int32_t SimpleDateFormat::subParse(const UnicodeString& text, int32_t& start, char16_t ch, int32_t count,
3027 UBool obeyCount, UBool allowNegative, UBool ambiguousYear[], int32_t& saveHebrewMonth, Calendar& cal,
3028 int32_t patLoc, MessageFormat * numericLeapMonthFormatter, UTimeZoneFormatTimeType *tzTimeType,
3029 int32_t *dayPeriod) const
3030 {
3031 Formattable number;
3032 int32_t value = 0;
3033 int32_t i;
3034 int32_t ps = 0;
3035 UErrorCode status = U_ZERO_ERROR;
3036 ParsePosition pos(0);
3037 UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(ch);
3038 const NumberFormat *currentNumberFormat;
3039 UnicodeString temp;
3040 UBool gotNumber = false;
3041
3042 #if defined (U_DEBUG_CAL)
3043 //fprintf(stderr, "%s:%d - [%c] st=%d \n", __FILE__, __LINE__, (char) ch, start);
3044 #endif
3045
3046 if (patternCharIndex == UDAT_FIELD_COUNT) {
3047 return -start;
3048 }
3049
3050 currentNumberFormat = getNumberFormatByIndex(patternCharIndex);
3051 if (currentNumberFormat == nullptr) {
3052 return -start;
3053 }
3054 UCalendarDateFields field = fgPatternIndexToCalendarField[patternCharIndex]; // UCAL_FIELD_COUNT if irrelevant
3055 UnicodeString hebr("hebr", 4, US_INV);
3056
3057 if (numericLeapMonthFormatter != nullptr) {
3058 numericLeapMonthFormatter->setFormats(reinterpret_cast<const Format**>(&currentNumberFormat), 1);
3059 }
3060
3061 // If there are any spaces here, skip over them. If we hit the end
3062 // of the string, then fail.
3063 for (;;) {
3064 if (start >= text.length()) {
3065 return -start;
3066 }
3067 UChar32 c = text.char32At(start);
3068 if (!u_isUWhiteSpace(c) /*||*/ && !PatternProps::isWhiteSpace(c)) {
3069 break;
3070 }
3071 start += U16_LENGTH(c);
3072 }
3073 pos.setIndex(start);
3074
3075 UBool isChineseCalendar = typeid(cal) == typeid(ChineseCalendar) ||
3076 typeid(cal) == typeid(DangiCalendar);
3077 // We handle a few special cases here where we need to parse
3078 // a number value. We handle further, more generic cases below. We need
3079 // to handle some of them here because some fields require extra processing on
3080 // the parsed value.
3081 if (patternCharIndex == UDAT_HOUR_OF_DAY1_FIELD || // k
3082 patternCharIndex == UDAT_HOUR_OF_DAY0_FIELD || // H
3083 patternCharIndex == UDAT_HOUR1_FIELD || // h
3084 patternCharIndex == UDAT_HOUR0_FIELD || // K
3085 (patternCharIndex == UDAT_DOW_LOCAL_FIELD && count <= 2) || // e
3086 (patternCharIndex == UDAT_STANDALONE_DAY_FIELD && count <= 2) || // c
3087 (patternCharIndex == UDAT_MONTH_FIELD && count <= 2) || // M
3088 (patternCharIndex == UDAT_STANDALONE_MONTH_FIELD && count <= 2) || // L
3089 (patternCharIndex == UDAT_QUARTER_FIELD && count <= 2) || // Q
3090 (patternCharIndex == UDAT_STANDALONE_QUARTER_FIELD && count <= 2) || // q
3091 patternCharIndex == UDAT_YEAR_FIELD || // y
3092 patternCharIndex == UDAT_YEAR_WOY_FIELD || // Y
3093 patternCharIndex == UDAT_YEAR_NAME_FIELD || // U (falls back to numeric)
3094 (patternCharIndex == UDAT_ERA_FIELD && isChineseCalendar) || // G
3095 patternCharIndex == UDAT_FRACTIONAL_SECOND_FIELD) // S
3096 {
3097 int32_t parseStart = pos.getIndex();
3098 // It would be good to unify this with the obeyCount logic below,
3099 // but that's going to be difficult.
3100 const UnicodeString* src;
3101
3102 UBool parsedNumericLeapMonth = false;
3103 if (numericLeapMonthFormatter != nullptr && (patternCharIndex == UDAT_MONTH_FIELD || patternCharIndex == UDAT_STANDALONE_MONTH_FIELD)) {
3104 int32_t argCount;
3105 Formattable * args = numericLeapMonthFormatter->parse(text, pos, argCount);
3106 if (args != nullptr && argCount == 1 && pos.getIndex() > parseStart && args[0].isNumeric()) {
3107 parsedNumericLeapMonth = true;
3108 number.setLong(args[0].getLong());
3109 cal.set(UCAL_IS_LEAP_MONTH, 1);
3110 delete[] args;
3111 } else {
3112 pos.setIndex(parseStart);
3113 cal.set(UCAL_IS_LEAP_MONTH, 0);
3114 }
3115 }
3116
3117 if (!parsedNumericLeapMonth) {
3118 if (obeyCount) {
3119 if ((start+count) > text.length()) {
3120 return -start;
3121 }
3122
3123 text.extractBetween(0, start + count, temp);
3124 src = &temp;
3125 } else {
3126 src = &text;
3127 }
3128
3129 parseInt(*src, number, pos, allowNegative,currentNumberFormat);
3130 }
3131
3132 int32_t txtLoc = pos.getIndex();
3133
3134 if (txtLoc > parseStart) {
3135 value = number.getLong();
3136 gotNumber = true;
3137
3138 // suffix processing
3139 if (value < 0 ) {
3140 txtLoc = checkIntSuffix(text, txtLoc, patLoc+1, true);
3141 if (txtLoc != pos.getIndex()) {
3142 value *= -1;
3143 }
3144 }
3145 else {
3146 txtLoc = checkIntSuffix(text, txtLoc, patLoc+1, false);
3147 }
3148
3149 if (!getBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, status)) {
3150 // Check the range of the value
3151 int32_t bias = gFieldRangeBias[patternCharIndex];
3152 if (bias >= 0 && (value > cal.getMaximum(field) + bias || value < cal.getMinimum(field) + bias)) {
3153 return -start;
3154 }
3155 }
3156
3157 pos.setIndex(txtLoc);
3158 }
3159 }
3160
3161 // Make sure that we got a number if
3162 // we want one, and didn't get one
3163 // if we don't want one.
3164 switch (patternCharIndex) {
3165 case UDAT_HOUR_OF_DAY1_FIELD:
3166 case UDAT_HOUR_OF_DAY0_FIELD:
3167 case UDAT_HOUR1_FIELD:
3168 case UDAT_HOUR0_FIELD:
3169 // special range check for hours:
3170 if (value < 0 || value > 24) {
3171 return -start;
3172 }
3173
3174 // fall through to gotNumber check
3175 U_FALLTHROUGH;
3176 case UDAT_YEAR_FIELD:
3177 case UDAT_YEAR_WOY_FIELD:
3178 case UDAT_FRACTIONAL_SECOND_FIELD:
3179 // these must be a number
3180 if (! gotNumber) {
3181 return -start;
3182 }
3183
3184 break;
3185
3186 default:
3187 // we check the rest of the fields below.
3188 break;
3189 }
3190
3191 switch (patternCharIndex) {
3192 case UDAT_ERA_FIELD:
3193 if (isChineseCalendar) {
3194 if (!gotNumber) {
3195 return -start;
3196 }
3197 cal.set(UCAL_ERA, value);
3198 return pos.getIndex();
3199 }
3200 if (count == 5) {
3201 ps = matchString(text, start, UCAL_ERA, fSymbols->fNarrowEras, fSymbols->fNarrowErasCount, nullptr, cal);
3202 } else if (count == 4) {
3203 ps = matchString(text, start, UCAL_ERA, fSymbols->fEraNames, fSymbols->fEraNamesCount, nullptr, cal);
3204 } else {
3205 ps = matchString(text, start, UCAL_ERA, fSymbols->fEras, fSymbols->fErasCount, nullptr, cal);
3206 }
3207
3208 // check return position, if it equals -start, then matchString error
3209 // special case the return code so we don't necessarily fail out until we
3210 // verify no year information also
3211 if (ps == -start)
3212 ps--;
3213
3214 return ps;
3215
3216 case UDAT_YEAR_FIELD:
3217 // If there are 3 or more YEAR pattern characters, this indicates
3218 // that the year value is to be treated literally, without any
3219 // two-digit year adjustments (e.g., from "01" to 2001). Otherwise
3220 // we made adjustments to place the 2-digit year in the proper
3221 // century, for parsed strings from "00" to "99". Any other string
3222 // is treated literally: "2250", "-1", "1", "002".
3223 if (fDateOverride.compare(hebr)==0 && value < 1000) {
3224 value += HEBREW_CAL_CUR_MILLENIUM_START_YEAR;
3225 } else if (text.moveIndex32(start, 2) == pos.getIndex() && !isChineseCalendar
3226 && u_isdigit(text.char32At(start))
3227 && u_isdigit(text.char32At(text.moveIndex32(start, 1))))
3228 {
3229 // only adjust year for patterns less than 3.
3230 if(count < 3) {
3231 // Assume for example that the defaultCenturyStart is 6/18/1903.
3232 // This means that two-digit years will be forced into the range
3233 // 6/18/1903 to 6/17/2003. As a result, years 00, 01, and 02
3234 // correspond to 2000, 2001, and 2002. Years 04, 05, etc. correspond
3235 // to 1904, 1905, etc. If the year is 03, then it is 2003 if the
3236 // other fields specify a date before 6/18, or 1903 if they specify a
3237 // date afterwards. As a result, 03 is an ambiguous year. All other
3238 // two-digit years are unambiguous.
3239 if(fHaveDefaultCentury) { // check if this formatter even has a pivot year
3240 int32_t ambiguousTwoDigitYear = fDefaultCenturyStartYear % 100;
3241 ambiguousYear[0] = (value == ambiguousTwoDigitYear);
3242 value += (fDefaultCenturyStartYear/100)*100 +
3243 (value < ambiguousTwoDigitYear ? 100 : 0);
3244 }
3245 }
3246 }
3247 cal.set(UCAL_YEAR, value);
3248
3249 // Delayed checking for adjustment of Hebrew month numbers in non-leap years.
3250 if (saveHebrewMonth >= 0) {
3251 HebrewCalendar *hc = (HebrewCalendar*)&cal;
3252 if (!hc->isLeapYear(value) && saveHebrewMonth >= 6) {
3253 cal.set(UCAL_MONTH,saveHebrewMonth);
3254 } else {
3255 cal.set(UCAL_MONTH,saveHebrewMonth-1);
3256 }
3257 saveHebrewMonth = -1;
3258 }
3259 return pos.getIndex();
3260
3261 case UDAT_YEAR_WOY_FIELD:
3262 // Comment is the same as for UDAT_Year_FIELDs - look above
3263 if (fDateOverride.compare(hebr)==0 && value < 1000) {
3264 value += HEBREW_CAL_CUR_MILLENIUM_START_YEAR;
3265 } else if (text.moveIndex32(start, 2) == pos.getIndex()
3266 && u_isdigit(text.char32At(start))
3267 && u_isdigit(text.char32At(text.moveIndex32(start, 1)))
3268 && fHaveDefaultCentury )
3269 {
3270 int32_t ambiguousTwoDigitYear = fDefaultCenturyStartYear % 100;
3271 ambiguousYear[0] = (value == ambiguousTwoDigitYear);
3272 value += (fDefaultCenturyStartYear/100)*100 +
3273 (value < ambiguousTwoDigitYear ? 100 : 0);
3274 }
3275 cal.set(UCAL_YEAR_WOY, value);
3276 return pos.getIndex();
3277
3278 case UDAT_YEAR_NAME_FIELD:
3279 if (fSymbols->fShortYearNames != nullptr) {
3280 int32_t newStart = matchString(text, start, UCAL_YEAR, fSymbols->fShortYearNames, fSymbols->fShortYearNamesCount, nullptr, cal);
3281 if (newStart > 0) {
3282 return newStart;
3283 }
3284 }
3285 if (gotNumber && (getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC,status) || value > fSymbols->fShortYearNamesCount)) {
3286 cal.set(UCAL_YEAR, value);
3287 return pos.getIndex();
3288 }
3289 return -start;
3290
3291 case UDAT_MONTH_FIELD:
3292 case UDAT_STANDALONE_MONTH_FIELD:
3293 if (gotNumber) // i.e., M or MM.
3294 {
3295 // When parsing month numbers from the Hebrew Calendar, we might need to adjust the month depending on whether
3296 // or not it was a leap year. We may or may not yet know what year it is, so might have to delay checking until
3297 // the year is parsed.
3298 if (typeid(cal) == typeid(HebrewCalendar)) {
3299 HebrewCalendar *hc = (HebrewCalendar*)&cal;
3300 if (cal.isSet(UCAL_YEAR)) {
3301 UErrorCode monthStatus = U_ZERO_ERROR;
3302 if (!hc->isLeapYear(hc->get(UCAL_YEAR, monthStatus)) && value >= 6) {
3303 cal.set(UCAL_MONTH, value);
3304 } else {
3305 cal.set(UCAL_MONTH, value - 1);
3306 }
3307 } else {
3308 saveHebrewMonth = value;
3309 }
3310 } else {
3311 // Don't want to parse the month if it is a string
3312 // while pattern uses numeric style: M/MM, L/LL
3313 // [We computed 'value' above.]
3314 cal.set(UCAL_MONTH, value - 1);
3315 }
3316 return pos.getIndex();
3317 } else {
3318 // count >= 3 // i.e., MMM/MMMM, LLL/LLLL
3319 // Want to be able to parse both short and long forms.
3320 // Try count == 4 first:
3321 UnicodeString * wideMonthPat = nullptr;
3322 UnicodeString * shortMonthPat = nullptr;
3323 if (fSymbols->fLeapMonthPatterns != nullptr && fSymbols->fLeapMonthPatternsCount >= DateFormatSymbols::kMonthPatternsCount) {
3324 if (patternCharIndex==UDAT_MONTH_FIELD) {
3325 wideMonthPat = &fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatWide];
3326 shortMonthPat = &fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatAbbrev];
3327 } else {
3328 wideMonthPat = &fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneWide];
3329 shortMonthPat = &fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneAbbrev];
3330 }
3331 }
3332 int32_t newStart = 0;
3333 if (patternCharIndex==UDAT_MONTH_FIELD) {
3334 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) && count>=3 && count <=4 &&
3335 fSymbols->fLeapMonthPatterns==nullptr && fSymbols->fMonthsCount==fSymbols->fShortMonthsCount) {
3336 // single function to check both wide and short, an experiment
3337 newStart = matchAlphaMonthStrings(text, start, fSymbols->fMonths, fSymbols->fShortMonths, fSymbols->fMonthsCount, cal); // try MMMM,MMM
3338 if (newStart > 0) {
3339 return newStart;
3340 }
3341 }
3342 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3343 newStart = matchString(text, start, UCAL_MONTH, fSymbols->fMonths, fSymbols->fMonthsCount, wideMonthPat, cal); // try MMMM
3344 if (newStart > 0) {
3345 return newStart;
3346 }
3347 }
3348 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3349 newStart = matchString(text, start, UCAL_MONTH, fSymbols->fShortMonths, fSymbols->fShortMonthsCount, shortMonthPat, cal); // try MMM
3350 }
3351 } else {
3352 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) && count>=3 && count <=4 &&
3353 fSymbols->fLeapMonthPatterns==nullptr && fSymbols->fStandaloneMonthsCount==fSymbols->fStandaloneShortMonthsCount) {
3354 // single function to check both wide and short, an experiment
3355 newStart = matchAlphaMonthStrings(text, start, fSymbols->fStandaloneMonths, fSymbols->fStandaloneShortMonths, fSymbols->fStandaloneMonthsCount, cal); // try MMMM,MMM
3356 if (newStart > 0) {
3357 return newStart;
3358 }
3359 }
3360 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3361 newStart = matchString(text, start, UCAL_MONTH, fSymbols->fStandaloneMonths, fSymbols->fStandaloneMonthsCount, wideMonthPat, cal); // try LLLL
3362 if (newStart > 0) {
3363 return newStart;
3364 }
3365 }
3366 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3367 newStart = matchString(text, start, UCAL_MONTH, fSymbols->fStandaloneShortMonths, fSymbols->fStandaloneShortMonthsCount, shortMonthPat, cal); // try LLL
3368 }
3369 }
3370 if (newStart > 0 || !getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status)) // currently we do not try to parse MMMMM/LLLLL: #8860
3371 return newStart;
3372 // else we allowing parsing as number, below
3373 }
3374 break;
3375
3376 case UDAT_HOUR_OF_DAY1_FIELD:
3377 // [We computed 'value' above.]
3378 if (value == cal.getMaximum(UCAL_HOUR_OF_DAY) + 1)
3379 value = 0;
3380
3381 // fall through to set field
3382 U_FALLTHROUGH;
3383 case UDAT_HOUR_OF_DAY0_FIELD:
3384 cal.set(UCAL_HOUR_OF_DAY, value);
3385 return pos.getIndex();
3386
3387 case UDAT_FRACTIONAL_SECOND_FIELD:
3388 // Fractional seconds left-justify
3389 i = countDigits(text, start, pos.getIndex());
3390 if (i < 3) {
3391 while (i < 3) {
3392 value *= 10;
3393 i++;
3394 }
3395 } else {
3396 int32_t a = 1;
3397 while (i > 3) {
3398 a *= 10;
3399 i--;
3400 }
3401 value /= a;
3402 }
3403 cal.set(UCAL_MILLISECOND, value);
3404 return pos.getIndex();
3405
3406 case UDAT_DOW_LOCAL_FIELD:
3407 if (gotNumber) // i.e., e or ee
3408 {
3409 // [We computed 'value' above.]
3410 cal.set(UCAL_DOW_LOCAL, value);
3411 return pos.getIndex();
3412 }
3413 // else for eee-eeeee fall through to handling of EEE-EEEEE
3414 // fall through, do not break here
3415 U_FALLTHROUGH;
3416 case UDAT_DAY_OF_WEEK_FIELD:
3417 {
3418 // Want to be able to parse both short and long forms.
3419 // Try count == 4 (EEEE) wide first:
3420 int32_t newStart = 0;
3421 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3422 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3423 fSymbols->fWeekdays, fSymbols->fWeekdaysCount, nullptr, cal)) > 0)
3424 return newStart;
3425 }
3426 // EEEE wide failed, now try EEE abbreviated
3427 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3428 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3429 fSymbols->fShortWeekdays, fSymbols->fShortWeekdaysCount, nullptr, cal)) > 0)
3430 return newStart;
3431 }
3432 // EEE abbreviated failed, now try EEEEEE short
3433 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 6) {
3434 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3435 fSymbols->fShorterWeekdays, fSymbols->fShorterWeekdaysCount, nullptr, cal)) > 0)
3436 return newStart;
3437 }
3438 // EEEEEE short failed, now try EEEEE narrow
3439 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
3440 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3441 fSymbols->fNarrowWeekdays, fSymbols->fNarrowWeekdaysCount, nullptr, cal)) > 0)
3442 return newStart;
3443 }
3444 if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status) || patternCharIndex == UDAT_DAY_OF_WEEK_FIELD)
3445 return newStart;
3446 // else we allowing parsing as number, below
3447 }
3448 break;
3449
3450 case UDAT_STANDALONE_DAY_FIELD:
3451 {
3452 if (gotNumber) // c or cc
3453 {
3454 // [We computed 'value' above.]
3455 cal.set(UCAL_DOW_LOCAL, value);
3456 return pos.getIndex();
3457 }
3458 // Want to be able to parse both short and long forms.
3459 // Try count == 4 (cccc) first:
3460 int32_t newStart = 0;
3461 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3462 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3463 fSymbols->fStandaloneWeekdays, fSymbols->fStandaloneWeekdaysCount, nullptr, cal)) > 0)
3464 return newStart;
3465 }
3466 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3467 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3468 fSymbols->fStandaloneShortWeekdays, fSymbols->fStandaloneShortWeekdaysCount, nullptr, cal)) > 0)
3469 return newStart;
3470 }
3471 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 6) {
3472 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3473 fSymbols->fStandaloneShorterWeekdays, fSymbols->fStandaloneShorterWeekdaysCount, nullptr, cal)) > 0)
3474 return newStart;
3475 }
3476 if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status))
3477 return newStart;
3478 // else we allowing parsing as number, below
3479 }
3480 break;
3481
3482 case UDAT_AM_PM_FIELD:
3483 {
3484 // optionally try both wide/abbrev and narrow forms
3485 int32_t newStart = 0;
3486 // try wide/abbrev
3487 if( getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count < 5 ) {
3488 if ((newStart = matchString(text, start, UCAL_AM_PM, fSymbols->fAmPms, fSymbols->fAmPmsCount, nullptr, cal)) > 0) {
3489 return newStart;
3490 }
3491 }
3492 // try narrow
3493 if( getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count >= 5 ) {
3494 if ((newStart = matchString(text, start, UCAL_AM_PM, fSymbols->fNarrowAmPms, fSymbols->fNarrowAmPmsCount, nullptr, cal)) > 0) {
3495 return newStart;
3496 }
3497 }
3498 // no matches for given options
3499 return -start;
3500 }
3501
3502 case UDAT_HOUR1_FIELD:
3503 // [We computed 'value' above.]
3504 if (value == cal.getLeastMaximum(UCAL_HOUR)+1)
3505 value = 0;
3506
3507 // fall through to set field
3508 U_FALLTHROUGH;
3509 case UDAT_HOUR0_FIELD:
3510 cal.set(UCAL_HOUR, value);
3511 return pos.getIndex();
3512
3513 case UDAT_QUARTER_FIELD:
3514 if (gotNumber) // i.e., Q or QQ.
3515 {
3516 // Don't want to parse the month if it is a string
3517 // while pattern uses numeric style: Q or QQ.
3518 // [We computed 'value' above.]
3519 cal.set(UCAL_MONTH, (value - 1) * 3);
3520 return pos.getIndex();
3521 } else {
3522 // count >= 3 // i.e., QQQ or QQQQ
3523 // Want to be able to parse short, long, and narrow forms.
3524 // Try count == 4 first:
3525 int32_t newStart = 0;
3526
3527 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3528 if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
3529 fSymbols->fQuarters, fSymbols->fQuartersCount, cal)) > 0)
3530 return newStart;
3531 }
3532 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3533 if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
3534 fSymbols->fShortQuarters, fSymbols->fShortQuartersCount, cal)) > 0)
3535 return newStart;
3536 }
3537 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
3538 if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
3539 fSymbols->fNarrowQuarters, fSymbols->fNarrowQuartersCount, cal)) > 0)
3540 return newStart;
3541 }
3542 if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status))
3543 return newStart;
3544 // else we allowing parsing as number, below
3545 if(!getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status))
3546 return -start;
3547 }
3548 break;
3549
3550 case UDAT_STANDALONE_QUARTER_FIELD:
3551 if (gotNumber) // i.e., q or qq.
3552 {
3553 // Don't want to parse the month if it is a string
3554 // while pattern uses numeric style: q or q.
3555 // [We computed 'value' above.]
3556 cal.set(UCAL_MONTH, (value - 1) * 3);
3557 return pos.getIndex();
3558 } else {
3559 // count >= 3 // i.e., qqq or qqqq
3560 // Want to be able to parse both short and long forms.
3561 // Try count == 4 first:
3562 int32_t newStart = 0;
3563
3564 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3565 if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
3566 fSymbols->fStandaloneQuarters, fSymbols->fStandaloneQuartersCount, cal)) > 0)
3567 return newStart;
3568 }
3569 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3570 if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
3571 fSymbols->fStandaloneShortQuarters, fSymbols->fStandaloneShortQuartersCount, cal)) > 0)
3572 return newStart;
3573 }
3574 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
3575 if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
3576 fSymbols->fStandaloneNarrowQuarters, fSymbols->fStandaloneNarrowQuartersCount, cal)) > 0)
3577 return newStart;
3578 }
3579 if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status))
3580 return newStart;
3581 // else we allowing parsing as number, below
3582 if(!getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status))
3583 return -start;
3584 }
3585 break;
3586
3587 case UDAT_TIMEZONE_FIELD: // 'z'
3588 {
3589 UTimeZoneFormatStyle style = (count < 4) ? UTZFMT_STYLE_SPECIFIC_SHORT : UTZFMT_STYLE_SPECIFIC_LONG;
3590 const TimeZoneFormat *tzfmt = tzFormat(status);
3591 if (U_SUCCESS(status)) {
3592 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3593 if (tz != nullptr) {
3594 cal.adoptTimeZone(tz);
3595 return pos.getIndex();
3596 }
3597 }
3598 return -start;
3599 }
3600 break;
3601 case UDAT_TIMEZONE_RFC_FIELD: // 'Z'
3602 {
3603 UTimeZoneFormatStyle style = (count < 4) ?
3604 UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL : ((count == 5) ? UTZFMT_STYLE_ISO_EXTENDED_FULL: UTZFMT_STYLE_LOCALIZED_GMT);
3605 const TimeZoneFormat *tzfmt = tzFormat(status);
3606 if (U_SUCCESS(status)) {
3607 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3608 if (tz != nullptr) {
3609 cal.adoptTimeZone(tz);
3610 return pos.getIndex();
3611 }
3612 }
3613 return -start;
3614 }
3615 case UDAT_TIMEZONE_GENERIC_FIELD: // 'v'
3616 {
3617 UTimeZoneFormatStyle style = (count < 4) ? UTZFMT_STYLE_GENERIC_SHORT : UTZFMT_STYLE_GENERIC_LONG;
3618 const TimeZoneFormat *tzfmt = tzFormat(status);
3619 if (U_SUCCESS(status)) {
3620 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3621 if (tz != nullptr) {
3622 cal.adoptTimeZone(tz);
3623 return pos.getIndex();
3624 }
3625 }
3626 return -start;
3627 }
3628 case UDAT_TIMEZONE_SPECIAL_FIELD: // 'V'
3629 {
3630 UTimeZoneFormatStyle style;
3631 switch (count) {
3632 case 1:
3633 style = UTZFMT_STYLE_ZONE_ID_SHORT;
3634 break;
3635 case 2:
3636 style = UTZFMT_STYLE_ZONE_ID;
3637 break;
3638 case 3:
3639 style = UTZFMT_STYLE_EXEMPLAR_LOCATION;
3640 break;
3641 default:
3642 style = UTZFMT_STYLE_GENERIC_LOCATION;
3643 break;
3644 }
3645 const TimeZoneFormat *tzfmt = tzFormat(status);
3646 if (U_SUCCESS(status)) {
3647 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3648 if (tz != nullptr) {
3649 cal.adoptTimeZone(tz);
3650 return pos.getIndex();
3651 }
3652 }
3653 return -start;
3654 }
3655 case UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD: // 'O'
3656 {
3657 UTimeZoneFormatStyle style = (count < 4) ? UTZFMT_STYLE_LOCALIZED_GMT_SHORT : UTZFMT_STYLE_LOCALIZED_GMT;
3658 const TimeZoneFormat *tzfmt = tzFormat(status);
3659 if (U_SUCCESS(status)) {
3660 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3661 if (tz != nullptr) {
3662 cal.adoptTimeZone(tz);
3663 return pos.getIndex();
3664 }
3665 }
3666 return -start;
3667 }
3668 case UDAT_TIMEZONE_ISO_FIELD: // 'X'
3669 {
3670 UTimeZoneFormatStyle style;
3671 switch (count) {
3672 case 1:
3673 style = UTZFMT_STYLE_ISO_BASIC_SHORT;
3674 break;
3675 case 2:
3676 style = UTZFMT_STYLE_ISO_BASIC_FIXED;
3677 break;
3678 case 3:
3679 style = UTZFMT_STYLE_ISO_EXTENDED_FIXED;
3680 break;
3681 case 4:
3682 style = UTZFMT_STYLE_ISO_BASIC_FULL;
3683 break;
3684 default:
3685 style = UTZFMT_STYLE_ISO_EXTENDED_FULL;
3686 break;
3687 }
3688 const TimeZoneFormat *tzfmt = tzFormat(status);
3689 if (U_SUCCESS(status)) {
3690 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3691 if (tz != nullptr) {
3692 cal.adoptTimeZone(tz);
3693 return pos.getIndex();
3694 }
3695 }
3696 return -start;
3697 }
3698 case UDAT_TIMEZONE_ISO_LOCAL_FIELD: // 'x'
3699 {
3700 UTimeZoneFormatStyle style;
3701 switch (count) {
3702 case 1:
3703 style = UTZFMT_STYLE_ISO_BASIC_LOCAL_SHORT;
3704 break;
3705 case 2:
3706 style = UTZFMT_STYLE_ISO_BASIC_LOCAL_FIXED;
3707 break;
3708 case 3:
3709 style = UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FIXED;
3710 break;
3711 case 4:
3712 style = UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL;
3713 break;
3714 default:
3715 style = UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FULL;
3716 break;
3717 }
3718 const TimeZoneFormat *tzfmt = tzFormat(status);
3719 if (U_SUCCESS(status)) {
3720 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3721 if (tz != nullptr) {
3722 cal.adoptTimeZone(tz);
3723 return pos.getIndex();
3724 }
3725 }
3726 return -start;
3727 }
3728 // currently no pattern character is defined for UDAT_TIME_SEPARATOR_FIELD
3729 // so we should not get here. Leave support in for future definition.
3730 case UDAT_TIME_SEPARATOR_FIELD:
3731 {
3732 static const char16_t def_sep = DateFormatSymbols::DEFAULT_TIME_SEPARATOR;
3733 static const char16_t alt_sep = DateFormatSymbols::ALTERNATE_TIME_SEPARATOR;
3734
3735 // Try matching a time separator.
3736 int32_t count_sep = 1;
3737 UnicodeString data[3];
3738 fSymbols->getTimeSeparatorString(data[0]);
3739
3740 // Add the default, if different from the locale.
3741 if (data[0].compare(&def_sep, 1) != 0) {
3742 data[count_sep++].setTo(def_sep);
3743 }
3744
3745 // If lenient, add also the alternate, if different from the locale.
3746 if (isLenient() && data[0].compare(&alt_sep, 1) != 0) {
3747 data[count_sep++].setTo(alt_sep);
3748 }
3749
3750 return matchString(text, start, UCAL_FIELD_COUNT /* => nothing to set */, data, count_sep, nullptr, cal);
3751 }
3752
3753 case UDAT_AM_PM_MIDNIGHT_NOON_FIELD:
3754 {
3755 U_ASSERT(dayPeriod != nullptr);
3756 int32_t ampmStart = subParse(text, start, 0x61, count,
3757 obeyCount, allowNegative, ambiguousYear, saveHebrewMonth, cal,
3758 patLoc, numericLeapMonthFormatter, tzTimeType);
3759
3760 if (ampmStart > 0) {
3761 return ampmStart;
3762 } else {
3763 int32_t newStart = 0;
3764
3765 // Only match the first two strings from the day period strings array.
3766 if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3767 if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fAbbreviatedDayPeriods,
3768 2, *dayPeriod)) > 0) {
3769 return newStart;
3770 }
3771 }
3772 if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
3773 if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fNarrowDayPeriods,
3774 2, *dayPeriod)) > 0) {
3775 return newStart;
3776 }
3777 }
3778 // count == 4, but allow other counts
3779 if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status)) {
3780 if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fWideDayPeriods,
3781 2, *dayPeriod)) > 0) {
3782 return newStart;
3783 }
3784 }
3785
3786 return -start;
3787 }
3788 }
3789
3790 case UDAT_FLEXIBLE_DAY_PERIOD_FIELD:
3791 {
3792 U_ASSERT(dayPeriod != nullptr);
3793 int32_t newStart = 0;
3794
3795 if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3796 if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fAbbreviatedDayPeriods,
3797 fSymbols->fAbbreviatedDayPeriodsCount, *dayPeriod)) > 0) {
3798 return newStart;
3799 }
3800 }
3801 if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
3802 if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fNarrowDayPeriods,
3803 fSymbols->fNarrowDayPeriodsCount, *dayPeriod)) > 0) {
3804 return newStart;
3805 }
3806 }
3807 if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3808 if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fWideDayPeriods,
3809 fSymbols->fWideDayPeriodsCount, *dayPeriod)) > 0) {
3810 return newStart;
3811 }
3812 }
3813
3814 return -start;
3815 }
3816
3817 default:
3818 // Handle "generic" fields
3819 // this is now handled below, outside the switch block
3820 break;
3821 }
3822 // Handle "generic" fields:
3823 // switch default case now handled here (outside switch block) to allow
3824 // parsing of some string fields as digits for lenient case
3825
3826 int32_t parseStart = pos.getIndex();
3827 const UnicodeString* src;
3828 if (obeyCount) {
3829 if ((start+count) > text.length()) {
3830 return -start;
3831 }
3832 text.extractBetween(0, start + count, temp);
3833 src = &temp;
3834 } else {
3835 src = &text;
3836 }
3837 parseInt(*src, number, pos, allowNegative,currentNumberFormat);
3838 if (obeyCount && !isLenient() && pos.getIndex() < start + count) {
3839 return -start;
3840 }
3841 if (pos.getIndex() != parseStart) {
3842 int32_t val = number.getLong();
3843
3844 // Don't need suffix processing here (as in number processing at the beginning of the function);
3845 // the new fields being handled as numeric values (month, weekdays, quarters) should not have suffixes.
3846
3847 if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status)) {
3848 // Check the range of the value
3849 int32_t bias = gFieldRangeBias[patternCharIndex];
3850 if (bias >= 0 && (val > cal.getMaximum(field) + bias || val < cal.getMinimum(field) + bias)) {
3851 return -start;
3852 }
3853 }
3854
3855 // For the following, need to repeat some of the "if (gotNumber)" code above:
3856 // UDAT_[STANDALONE_]MONTH_FIELD, UDAT_DOW_LOCAL_FIELD, UDAT_STANDALONE_DAY_FIELD,
3857 // UDAT_[STANDALONE_]QUARTER_FIELD
3858 switch (patternCharIndex) {
3859 case UDAT_MONTH_FIELD:
3860 // See notes under UDAT_MONTH_FIELD case above
3861 if (typeid(cal) == typeid(HebrewCalendar)) {
3862 HebrewCalendar *hc = (HebrewCalendar*)&cal;
3863 if (cal.isSet(UCAL_YEAR)) {
3864 UErrorCode monthStatus = U_ZERO_ERROR;
3865 if (!hc->isLeapYear(hc->get(UCAL_YEAR, monthStatus)) && val >= 6) {
3866 cal.set(UCAL_MONTH, val);
3867 } else {
3868 cal.set(UCAL_MONTH, val - 1);
3869 }
3870 } else {
3871 saveHebrewMonth = val;
3872 }
3873 } else {
3874 cal.set(UCAL_MONTH, val - 1);
3875 }
3876 break;
3877 case UDAT_STANDALONE_MONTH_FIELD:
3878 cal.set(UCAL_MONTH, val - 1);
3879 break;
3880 case UDAT_DOW_LOCAL_FIELD:
3881 case UDAT_STANDALONE_DAY_FIELD:
3882 cal.set(UCAL_DOW_LOCAL, val);
3883 break;
3884 case UDAT_QUARTER_FIELD:
3885 case UDAT_STANDALONE_QUARTER_FIELD:
3886 cal.set(UCAL_MONTH, (val - 1) * 3);
3887 break;
3888 case UDAT_RELATED_YEAR_FIELD:
3889 cal.setRelatedYear(val);
3890 break;
3891 default:
3892 cal.set(field, val);
3893 break;
3894 }
3895 return pos.getIndex();
3896 }
3897 return -start;
3898 }
3899
3900 /**
3901 * Parse an integer using fNumberFormat. This method is semantically
3902 * const, but actually may modify fNumberFormat.
3903 */
3904 void SimpleDateFormat::parseInt(const UnicodeString& text,
3905 Formattable& number,
3906 ParsePosition& pos,
3907 UBool allowNegative,
3908 const NumberFormat *fmt) const {
3909 parseInt(text, number, -1, pos, allowNegative,fmt);
3910 }
3911
3912 /**
3913 * Parse an integer using fNumberFormat up to maxDigits.
3914 */
3915 void SimpleDateFormat::parseInt(const UnicodeString& text,
3916 Formattable& number,
3917 int32_t maxDigits,
3918 ParsePosition& pos,
3919 UBool allowNegative,
3920 const NumberFormat *fmt) const {
3921 UnicodeString oldPrefix;
3922 const auto* fmtAsDF = dynamic_cast<const DecimalFormat*>(fmt);
3923 LocalPointer<DecimalFormat> df;
3924 if (!allowNegative && fmtAsDF != nullptr) {
3925 df.adoptInstead(fmtAsDF->clone());
3926 if (df.isNull()) {
3927 // Memory allocation error
3928 return;
3929 }
3930 df->setNegativePrefix(UnicodeString(true, SUPPRESS_NEGATIVE_PREFIX, -1));
3931 fmt = df.getAlias();
3932 }
3933 int32_t oldPos = pos.getIndex();
3934 fmt->parse(text, number, pos);
3935
3936 if (maxDigits > 0) {
3937 // adjust the result to fit into
3938 // the maxDigits and move the position back
3939 int32_t nDigits = pos.getIndex() - oldPos;
3940 if (nDigits > maxDigits) {
3941 int32_t val = number.getLong();
3942 nDigits -= maxDigits;
3943 while (nDigits > 0) {
3944 val /= 10;
3945 nDigits--;
3946 }
3947 pos.setIndex(oldPos + maxDigits);
3948 number.setLong(val);
3949 }
3950 }
3951 }
3952
3953 int32_t SimpleDateFormat::countDigits(const UnicodeString& text, int32_t start, int32_t end) const {
3954 int32_t numDigits = 0;
3955 int32_t idx = start;
3956 while (idx < end) {
3957 UChar32 cp = text.char32At(idx);
3958 if (u_isdigit(cp)) {
3959 numDigits++;
3960 }
3961 idx += U16_LENGTH(cp);
3962 }
3963 return numDigits;
3964 }
3965
3966 //----------------------------------------------------------------------
3967
3968 void SimpleDateFormat::translatePattern(const UnicodeString& originalPattern,
3969 UnicodeString& translatedPattern,
3970 const UnicodeString& from,
3971 const UnicodeString& to,
3972 UErrorCode& status)
3973 {
3974 // run through the pattern and convert any pattern symbols from the version
3975 // in "from" to the corresponding character in "to". This code takes
3976 // quoted strings into account (it doesn't try to translate them), and it signals
3977 // an error if a particular "pattern character" doesn't appear in "from".
3978 // Depending on the values of "from" and "to" this can convert from generic
3979 // to localized patterns or localized to generic.
3980 if (U_FAILURE(status)) {
3981 return;
3982 }
3983
3984 translatedPattern.remove();
3985 UBool inQuote = false;
3986 for (int32_t i = 0; i < originalPattern.length(); ++i) {
3987 char16_t c = originalPattern[i];
3988 if (inQuote) {
3989 if (c == QUOTE) {
3990 inQuote = false;
3991 }
3992 } else {
3993 if (c == QUOTE) {
3994 inQuote = true;
3995 } else if (isSyntaxChar(c)) {
3996 int32_t ci = from.indexOf(c);
3997 if (ci == -1) {
3998 status = U_INVALID_FORMAT_ERROR;
3999 return;
4000 }
4001 c = to[ci];
4002 }
4003 }
4004 translatedPattern += c;
4005 }
4006 if (inQuote) {
4007 status = U_INVALID_FORMAT_ERROR;
4008 return;
4009 }
4010 }
4011
4012 //----------------------------------------------------------------------
4013
4014 UnicodeString&
4015 SimpleDateFormat::toPattern(UnicodeString& result) const
4016 {
4017 result = fPattern;
4018 return result;
4019 }
4020
4021 //----------------------------------------------------------------------
4022
4023 UnicodeString&
4024 SimpleDateFormat::toLocalizedPattern(UnicodeString& result,
4025 UErrorCode& status) const
4026 {
4027 translatePattern(fPattern, result,
4028 UnicodeString(DateFormatSymbols::getPatternUChars()),
4029 fSymbols->fLocalPatternChars, status);
4030 return result;
4031 }
4032
4033 //----------------------------------------------------------------------
4034
4035 void
4036 SimpleDateFormat::applyPattern(const UnicodeString& pattern)
4037 {
4038 fPattern = pattern;
4039 parsePattern();
4040
4041 // Hack to update use of Gannen year numbering for ja@calendar=japanese -
4042 // use only if format is non-numeric (includes 年) and no other fDateOverride.
4043 if (fCalendar != nullptr && typeid(*fCalendar) == typeid(JapaneseCalendar) &&
4044 uprv_strcmp(fLocale.getLanguage(),"ja") == 0) {
4045 if (fDateOverride==UnicodeString(u"y=jpanyear") && !fHasHanYearChar) {
4046 // Gannen numbering is set but new pattern should not use it, unset;
4047 // use procedure from adoptNumberFormat to clear overrides
4048 if (fSharedNumberFormatters) {
4049 freeSharedNumberFormatters(fSharedNumberFormatters);
4050 fSharedNumberFormatters = nullptr;
4051 }
4052 fDateOverride.setToBogus(); // record status
4053 } else if (fDateOverride.isBogus() && fHasHanYearChar) {
4054 // No current override (=> no Gannen numbering) but new pattern needs it;
4055 // use procedures from initNUmberFormatters / adoptNumberFormat
4056 umtx_lock(&LOCK);
4057 if (fSharedNumberFormatters == nullptr) {
4058 fSharedNumberFormatters = allocSharedNumberFormatters();
4059 }
4060 umtx_unlock(&LOCK);
4061 if (fSharedNumberFormatters != nullptr) {
4062 Locale ovrLoc(fLocale.getLanguage(),fLocale.getCountry(),fLocale.getVariant(),"numbers=jpanyear");
4063 UErrorCode status = U_ZERO_ERROR;
4064 const SharedNumberFormat *snf = createSharedNumberFormat(ovrLoc, status);
4065 if (U_SUCCESS(status)) {
4066 // Now that we have an appropriate number formatter, fill in the
4067 // appropriate slot in the number formatters table.
4068 UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(u'y');
4069 SharedObject::copyPtr(snf, fSharedNumberFormatters[patternCharIndex]);
4070 snf->deleteIfZeroRefCount();
4071 fDateOverride.setTo(u"y=jpanyear", -1); // record status
4072 }
4073 }
4074 }
4075 }
4076 }
4077
4078 //----------------------------------------------------------------------
4079
4080 void
4081 SimpleDateFormat::applyLocalizedPattern(const UnicodeString& pattern,
4082 UErrorCode &status)
4083 {
4084 translatePattern(pattern, fPattern,
4085 fSymbols->fLocalPatternChars,
4086 UnicodeString(DateFormatSymbols::getPatternUChars()), status);
4087 }
4088
4089 //----------------------------------------------------------------------
4090
4091 const DateFormatSymbols*
4092 SimpleDateFormat::getDateFormatSymbols() const
4093 {
4094 return fSymbols;
4095 }
4096
4097 //----------------------------------------------------------------------
4098
4099 void
4100 SimpleDateFormat::adoptDateFormatSymbols(DateFormatSymbols* newFormatSymbols)
4101 {
4102 delete fSymbols;
4103 fSymbols = newFormatSymbols;
4104 }
4105
4106 //----------------------------------------------------------------------
4107 void
4108 SimpleDateFormat::setDateFormatSymbols(const DateFormatSymbols& newFormatSymbols)
4109 {
4110 delete fSymbols;
4111 fSymbols = new DateFormatSymbols(newFormatSymbols);
4112 }
4113
4114 //----------------------------------------------------------------------
4115 const TimeZoneFormat*
4116 SimpleDateFormat::getTimeZoneFormat() const {
4117 // TimeZoneFormat initialization might fail when out of memory.
4118 // If we always initialize TimeZoneFormat instance, we can return
4119 // such status there. For now, this implementation lazily instantiates
4120 // a TimeZoneFormat for performance optimization reasons, but cannot
4121 // propagate such error (probably just out of memory case) to the caller.
4122 UErrorCode status = U_ZERO_ERROR;
4123 return (const TimeZoneFormat*)tzFormat(status);
4124 }
4125
4126 //----------------------------------------------------------------------
4127 void
4128 SimpleDateFormat::adoptTimeZoneFormat(TimeZoneFormat* timeZoneFormatToAdopt)
4129 {
4130 delete fTimeZoneFormat;
4131 fTimeZoneFormat = timeZoneFormatToAdopt;
4132 }
4133
4134 //----------------------------------------------------------------------
4135 void
4136 SimpleDateFormat::setTimeZoneFormat(const TimeZoneFormat& newTimeZoneFormat)
4137 {
4138 delete fTimeZoneFormat;
4139 fTimeZoneFormat = new TimeZoneFormat(newTimeZoneFormat);
4140 }
4141
4142 //----------------------------------------------------------------------
4143
4144
4145 void SimpleDateFormat::adoptCalendar(Calendar* calendarToAdopt)
4146 {
4147 UErrorCode status = U_ZERO_ERROR;
4148 Locale calLocale(fLocale);
4149 calLocale.setKeywordValue("calendar", calendarToAdopt->getType(), status);
4150 DateFormatSymbols *newSymbols =
4151 DateFormatSymbols::createForLocale(calLocale, status);
4152 if (U_FAILURE(status)) {
4153 delete calendarToAdopt;
4154 return;
4155 }
4156 DateFormat::adoptCalendar(calendarToAdopt);
4157 delete fSymbols;
4158 fSymbols = newSymbols;
4159 initializeDefaultCentury(); // we need a new century (possibly)
4160 }
4161
4162
4163 //----------------------------------------------------------------------
4164
4165
4166 // override the DateFormat implementation in order to
4167 // lazily initialize fCapitalizationBrkIter
4168 void
4169 SimpleDateFormat::setContext(UDisplayContext value, UErrorCode& status)
4170 {
4171 DateFormat::setContext(value, status);
4172 #if !UCONFIG_NO_BREAK_ITERATION
4173 if (U_SUCCESS(status)) {
4174 if ( fCapitalizationBrkIter == nullptr && (value==UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE ||
4175 value==UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU || value==UDISPCTX_CAPITALIZATION_FOR_STANDALONE) ) {
4176 status = U_ZERO_ERROR;
4177 fCapitalizationBrkIter = BreakIterator::createSentenceInstance(fLocale, status);
4178 if (U_FAILURE(status)) {
4179 delete fCapitalizationBrkIter;
4180 fCapitalizationBrkIter = nullptr;
4181 }
4182 }
4183 }
4184 #endif
4185 }
4186
4187
4188 //----------------------------------------------------------------------
4189
4190
4191 UBool
4192 SimpleDateFormat::isFieldUnitIgnored(UCalendarDateFields field) const {
4193 return isFieldUnitIgnored(fPattern, field);
4194 }
4195
4196
4197 UBool
4198 SimpleDateFormat::isFieldUnitIgnored(const UnicodeString& pattern,
4199 UCalendarDateFields field) {
4200 int32_t fieldLevel = fgCalendarFieldToLevel[field];
4201 int32_t level;
4202 char16_t ch;
4203 UBool inQuote = false;
4204 char16_t prevCh = 0;
4205 int32_t count = 0;
4206
4207 for (int32_t i = 0; i < pattern.length(); ++i) {
4208 ch = pattern[i];
4209 if (ch != prevCh && count > 0) {
4210 level = getLevelFromChar(prevCh);
4211 // the larger the level, the smaller the field unit.
4212 if (fieldLevel <= level) {
4213 return false;
4214 }
4215 count = 0;
4216 }
4217 if (ch == QUOTE) {
4218 if ((i+1) < pattern.length() && pattern[i+1] == QUOTE) {
4219 ++i;
4220 } else {
4221 inQuote = ! inQuote;
4222 }
4223 }
4224 else if (!inQuote && isSyntaxChar(ch)) {
4225 prevCh = ch;
4226 ++count;
4227 }
4228 }
4229 if (count > 0) {
4230 // last item
4231 level = getLevelFromChar(prevCh);
4232 if (fieldLevel <= level) {
4233 return false;
4234 }
4235 }
4236 return true;
4237 }
4238
4239 //----------------------------------------------------------------------
4240
4241 const Locale&
4242 SimpleDateFormat::getSmpFmtLocale() const {
4243 return fLocale;
4244 }
4245
4246 //----------------------------------------------------------------------
4247
4248 int32_t
4249 SimpleDateFormat::checkIntSuffix(const UnicodeString& text, int32_t start,
4250 int32_t patLoc, UBool isNegative) const {
4251 // local variables
4252 UnicodeString suf;
4253 int32_t patternMatch;
4254 int32_t textPreMatch;
4255 int32_t textPostMatch;
4256
4257 // check that we are still in range
4258 if ( (start > text.length()) ||
4259 (start < 0) ||
4260 (patLoc < 0) ||
4261 (patLoc > fPattern.length())) {
4262 // out of range, don't advance location in text
4263 return start;
4264 }
4265
4266 // get the suffix
4267 DecimalFormat* decfmt = dynamic_cast<DecimalFormat*>(fNumberFormat);
4268 if (decfmt != nullptr) {
4269 if (isNegative) {
4270 suf = decfmt->getNegativeSuffix(suf);
4271 }
4272 else {
4273 suf = decfmt->getPositiveSuffix(suf);
4274 }
4275 }
4276
4277 // check for suffix
4278 if (suf.length() <= 0) {
4279 return start;
4280 }
4281
4282 // check suffix will be encountered in the pattern
4283 patternMatch = compareSimpleAffix(suf,fPattern,patLoc);
4284
4285 // check if a suffix will be encountered in the text
4286 textPreMatch = compareSimpleAffix(suf,text,start);
4287
4288 // check if a suffix was encountered in the text
4289 textPostMatch = compareSimpleAffix(suf,text,start-suf.length());
4290
4291 // check for suffix match
4292 if ((textPreMatch >= 0) && (patternMatch >= 0) && (textPreMatch == patternMatch)) {
4293 return start;
4294 }
4295 else if ((textPostMatch >= 0) && (patternMatch >= 0) && (textPostMatch == patternMatch)) {
4296 return start - suf.length();
4297 }
4298
4299 // should not get here
4300 return start;
4301 }
4302
4303 //----------------------------------------------------------------------
4304
4305 int32_t
4306 SimpleDateFormat::compareSimpleAffix(const UnicodeString& affix,
4307 const UnicodeString& input,
4308 int32_t pos) const {
4309 int32_t start = pos;
4310 for (int32_t i=0; i<affix.length(); ) {
4311 UChar32 c = affix.char32At(i);
4312 int32_t len = U16_LENGTH(c);
4313 if (PatternProps::isWhiteSpace(c)) {
4314 // We may have a pattern like: \u200F \u0020
4315 // and input text like: \u200F \u0020
4316 // Note that U+200F and U+0020 are Pattern_White_Space but only
4317 // U+0020 is UWhiteSpace. So we have to first do a direct
4318 // match of the run of Pattern_White_Space in the pattern,
4319 // then match any extra characters.
4320 UBool literalMatch = false;
4321 while (pos < input.length() &&
4322 input.char32At(pos) == c) {
4323 literalMatch = true;
4324 i += len;
4325 pos += len;
4326 if (i == affix.length()) {
4327 break;
4328 }
4329 c = affix.char32At(i);
4330 len = U16_LENGTH(c);
4331 if (!PatternProps::isWhiteSpace(c)) {
4332 break;
4333 }
4334 }
4335
4336 // Advance over run in pattern
4337 i = skipPatternWhiteSpace(affix, i);
4338
4339 // Advance over run in input text
4340 // Must see at least one white space char in input,
4341 // unless we've already matched some characters literally.
4342 int32_t s = pos;
4343 pos = skipUWhiteSpace(input, pos);
4344 if (pos == s && !literalMatch) {
4345 return -1;
4346 }
4347
4348 // If we skip UWhiteSpace in the input text, we need to skip it in the pattern.
4349 // Otherwise, the previous lines may have skipped over text (such as U+00A0) that
4350 // is also in the affix.
4351 i = skipUWhiteSpace(affix, i);
4352 } else {
4353 if (pos < input.length() &&
4354 input.char32At(pos) == c) {
4355 i += len;
4356 pos += len;
4357 } else {
4358 return -1;
4359 }
4360 }
4361 }
4362 return pos - start;
4363 }
4364
4365 //----------------------------------------------------------------------
4366
4367 int32_t
4368 SimpleDateFormat::skipPatternWhiteSpace(const UnicodeString& text, int32_t pos) const {
4369 const char16_t* s = text.getBuffer();
4370 return static_cast<int32_t>(PatternProps::skipWhiteSpace(s + pos, text.length() - pos) - s);
4371 }
4372
4373 //----------------------------------------------------------------------
4374
4375 int32_t
4376 SimpleDateFormat::skipUWhiteSpace(const UnicodeString& text, int32_t pos) const {
4377 while (pos < text.length()) {
4378 UChar32 c = text.char32At(pos);
4379 if (!u_isUWhiteSpace(c)) {
4380 break;
4381 }
4382 pos += U16_LENGTH(c);
4383 }
4384 return pos;
4385 }
4386
4387 //----------------------------------------------------------------------
4388
4389 // Lazy TimeZoneFormat instantiation, semantically const.
4390 TimeZoneFormat *
4391 SimpleDateFormat::tzFormat(UErrorCode &status) const {
4392 Mutex m(&LOCK);
4393 if (fTimeZoneFormat == nullptr && U_SUCCESS(status)) {
4394 const_cast<SimpleDateFormat *>(this)->fTimeZoneFormat =
4395 TimeZoneFormat::createInstance(fLocale, status);
4396 }
4397 return fTimeZoneFormat;
4398 }
4399
4400 void SimpleDateFormat::parsePattern() {
4401 fHasMinute = false;
4402 fHasSecond = false;
4403 fHasHanYearChar = false;
4404
4405 int len = fPattern.length();
4406 UBool inQuote = false;
4407 for (int32_t i = 0; i < len; ++i) {
4408 char16_t ch = fPattern[i];
4409 if (ch == QUOTE) {
4410 inQuote = !inQuote;
4411 }
4412 if (ch == 0x5E74) { // don't care whether this is inside quotes
4413 fHasHanYearChar = true;
4414 }
4415 if (!inQuote) {
4416 if (ch == 0x6D) { // 0x6D == 'm'
4417 fHasMinute = true;
4418 }
4419 if (ch == 0x73) { // 0x73 == 's'
4420 fHasSecond = true;
4421 }
4422 }
4423 }
4424 }
4425
4426 U_NAMESPACE_END
4427
4428 #endif /* #if !UCONFIG_NO_FORMATTING */
4429
4430 //eof