Bug Summary

File:root/firefox-clang/intl/icu/source/i18n/smpdtfmt.cpp
Warning:line 1730, column 13
Value stored to 'capContextUsageType' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -O2 -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name smpdtfmt.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -ffp-contract=off -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/config/external/icu/i18n -fcoverage-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/config/external/icu/i18n -resource-dir /usr/lib/llvm-23/lib/clang/23 -include /root/firefox-clang/config/gcc_hidden.h -include /root/firefox-clang/obj-x86_64-pc-linux-gnu/mozilla-config.h -D _GLIBCXX_ASSERTIONS=1 -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/system_wrappers -U _FORTIFY_SOURCE -D _FORTIFY_SOURCE=2 -D DEBUG=1 -D U_I18N_IMPLEMENTATION -D _LIBCPP_DISABLE_DEPRECATION_WARNINGS -D U_USING_ICU_NAMESPACE=0 -D U_NO_DEFAULT_INCLUDE_UTF_HEADERS=1 -D U_HIDE_OBSOLETE_UTF_OLD_H=1 -D UCONFIG_NO_LEGACY_CONVERSION -D UCONFIG_NO_TRANSLITERATION -D UCONFIG_NO_REGULAR_EXPRESSIONS -D UCONFIG_NO_BREAK_ITERATION -D UCONFIG_NO_IDNA -D UCONFIG_NO_MF2 -D UCONFIG_NO_NORMALIZATION -D UCONFIG_NO_COLLATION -D U_CHARSET_IS_UTF8 -D UNISTR_FROM_CHAR_EXPLICIT=explicit -D UNISTR_FROM_STRING_EXPLICIT=explicit -D U_ENABLE_DYLOAD=0 -D U_DEBUG=1 -I /root/firefox-clang/config/external/icu/i18n -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/config/external/icu/i18n -I /root/firefox-clang/intl/icu/source/common -I /root/firefox-clang/mfbt/double-conversion -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nspr -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nss -D MOZILLA_CLIENT -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/x86_64-linux-gnu/c++/16 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../include/c++/16/backward -internal-isystem /usr/lib/llvm-23/lib/clang/23/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/16/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -Wno-error=pessimizing-move -Wno-error=large-by-value-copy=128 -Wno-error=implicit-int-float-conversion -Wno-error=thread-safety-analysis -Wno-error=tautological-type-limit-compare -Wno-invalid-offsetof -Wno-range-loop-analysis -Wno-deprecated-anon-enum-enum-conversion -Wno-deprecated-enum-enum-conversion -Wno-inline-new-delete -Wno-error=deprecated-declarations -Wno-error=array-bounds -Wno-error=free-nonheap-object -Wno-error=atomic-alignment -Wno-error=deprecated-builtins -Wno-psabi -Wno-error=builtin-macro-redefined -Wno-vla-cxx-extension -Wno-unknown-warning-option -Wno-character-conversion -Wno-comma -Wno-implicit-const-int-float-conversion -Wno-macro-redefined -Wno-microsoft-include -Wno-tautological-unsigned-enum-zero-compare -Wno-unreachable-code-loop-increment -Wno-unreachable-code-return -std=gnu++20 -fdeprecated-macro -ferror-limit 19 -fstrict-flex-arrays=1 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fgnuc-version=4.2.1 -fno-implicit-modules -fskip-odr-check-in-gmf -fno-sized-deallocation -fno-aligned-allocation -fdiagnostics-absolute-paths -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -mllvm -dwarf-linkage-names=Abstract -faddrsig -fdwarf2-cfi-asm -o /tmp/scan-build-2026-09-01-224014-2642839-1 -x c++ /root/firefox-clang/intl/icu/source/i18n/smpdtfmt.cpp
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_MAX128 128
30
31#include "unicode/utypes.h"
32
33#if !UCONFIG_NO_FORMATTING0
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
93U_NAMESPACE_BEGINnamespace icu_78 {
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
113typedef 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
126typedef enum OvrStrType {
127 kOvrStrDate = 0,
128 kOvrStrTime = 1,
129 kOvrStrBoth = 2
130} OvrStrType;
131
132static 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 };
149static const int8_t kDateFieldsCount = 16;
150
151static 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 };
162static 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.
167static 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).
175static 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 */
181static 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 */
192static 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_SEPARATOR0
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
237static const int32_t HEBREW_CAL_CUR_MILLENIUM_START_YEAR = 5000;
238static 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 */
245static const double MAX_DAYLIGHT_DETECTION_RANGE = 30*365*24*60*60*1000.0;
246
247static UMutex LOCK;
248
249UOBJECT_DEFINE_RTTI_IMPLEMENTATION(SimpleDateFormat)UClassID SimpleDateFormat::getStaticClassID() { static char classID
= 0; return (UClassID)&classID; } UClassID SimpleDateFormat
::getDynamicClassID() const { return SimpleDateFormat::getStaticClassID
(); }
250
251SimpleDateFormat::NSOverride::~NSOverride() {
252 if (snf != nullptr) {
253 snf->removeRef();
254 }
255}
256
257
258void 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
270static 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
280static 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
290static 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
303static 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
315static 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
322const 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
333SimpleDateFormat::~SimpleDateFormat()
334{
335 delete fSymbols;
336 if (fSharedNumberFormatters) {
337 freeSharedNumberFormatters(fSharedNumberFormatters);
338 }
339 delete fTimeZoneFormat;
340 delete fSimpleNumberFormatter;
341
342#if !UCONFIG_NO_BREAK_ITERATION1
343 delete fCapitalizationBrkIter;
344#endif
345}
346
347//----------------------------------------------------------------------
348
349SimpleDateFormat::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
359SimpleDateFormat::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
375SimpleDateFormat::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
395SimpleDateFormat::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
414SimpleDateFormat::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
437SimpleDateFormat::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
456SimpleDateFormat::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
476SimpleDateFormat::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 */
496SimpleDateFormat::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
529SimpleDateFormat::SimpleDateFormat(const SimpleDateFormat& other)
530: DateFormat(other),
531 fLocale(other.fLocale)
532{
533 initializeBooleanAttributes();
534 *this = other;
535}
536
537//----------------------------------------------------------------------
538
539SimpleDateFormat& 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_ITERATION1
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
627SimpleDateFormat*
628SimpleDateFormat::clone() const
629{
630 return new SimpleDateFormat(*this);
631}
632
633//----------------------------------------------------------------------
634
635bool
636SimpleDateFormat::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//----------------------------------------------------------------------
654static const char16_t* timeSkeletons[4] = {
655 u"jmmsszzzz", // kFull
656 u"jmmssz", // kLong
657 u"jmmss", // kMedium
658 u"jmm", // kShort
659};
660
661void 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"):: 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"):: 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):: strncmp(baseReg, validLoc.getCountry(), 4)!=0)
744 || uprv_strncmp(baseLoc.getLanguage(),validLoc.getLanguage(),ULOC_LANG_CAPACITY):: strncmp(baseLoc.getLanguage(), validLoc.getLanguage(), 12)!=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
930Calendar*
931SimpleDateFormat::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
940void
941SimpleDateFormat::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"):: 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 */
979void 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_MIN2.2250738585072014e-308;
988 fDefaultCenturyStartYear = -1;
989 }
990 }
991}
992
993/*
994 * Initialize the boolean attributes. Separate so we can call it from all constructors.
995 */
996void 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 */
1009void 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
1029UnicodeString&
1030SimpleDateFormat::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
1039UnicodeString&
1040SimpleDateFormat::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
1049UnicodeString&
1050SimpleDateFormat::_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 // Set or reset Gannen year numbering.
1075 if (typeid(*fCalendar) == typeid(JapaneseCalendar) && fHasHanYearChar &&
1076 uprv_strcmp(fLocale.getLanguage(), "ja"):: strcmp(fLocale.getLanguage(), "ja") == 0) {
1077
1078 int32_t era = workCal->get(UCAL_ERA, status);
1079 if (U_FAILURE(status)) {
1080 return appendTo;
1081 }
1082
1083 // Cast away constness.
1084 auto* self = const_cast<SimpleDateFormat *>(this);
1085
1086 // Does the current calendar era uses Gannen year numbering?
1087 bool useGannen = era != GregorianCalendar::AD && era != GregorianCalendar::BC;
1088
1089 // Code to set/reset numbering copied from `SimpleDateFormat::applyPattern`.
1090 if (!useGannen && fDateOverride == UnicodeString(u"y=jpanyear")) {
1091 // Gannen numbering is set but current era should not use it, unset;
1092 // use procedure from adoptNumberFormat to clear overrides
1093 if (fSharedNumberFormatters) {
1094 freeSharedNumberFormatters(fSharedNumberFormatters);
1095 self->fSharedNumberFormatters = nullptr;
1096 }
1097 self->fDateOverride.setToBogus(); // record status
1098 } else if (useGannen && fDateOverride.isBogus()) {
1099 // No current override (=> no Gannen numbering) but current era needs it;
1100 // use procedures from initNUmberFormatters / adoptNumberFormat
1101 umtx_lock(&LOCK);
1102 if (fSharedNumberFormatters == nullptr) {
1103 self->fSharedNumberFormatters = allocSharedNumberFormatters();
1104 }
1105 umtx_unlock(&LOCK);
1106 if (fSharedNumberFormatters != nullptr) {
1107 Locale ovrLoc(fLocale.getLanguage(), fLocale.getCountry(), fLocale.getVariant(), "numbers=jpanyear");
1108 const SharedNumberFormat *snf = createSharedNumberFormat(ovrLoc, status);
1109 if (U_FAILURE(status)) {
1110 return appendTo;
1111 }
1112 // Now that we have an appropriate number formatter, fill in the
1113 // appropriate slot in the number formatters table.
1114 UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(u'y');
1115 SharedObject::copyPtr(snf, fSharedNumberFormatters[patternCharIndex]);
1116 snf->deleteIfZeroRefCount();
1117 self->fDateOverride.setTo(u"y=jpanyear", -1); // record status
1118 }
1119 }
1120 }
1121
1122 UBool inQuote = false;
1123 char16_t prevCh = 0;
1124 int32_t count = 0;
1125 int32_t fieldNum = 0;
1126 UDisplayContext capitalizationContext = getContext(UDISPCTX_TYPE_CAPITALIZATION, status);
1127
1128 // loop through the pattern string character by character
1129 int32_t patternLength = fPattern.length();
1130 for (int32_t i = 0; i < patternLength && U_SUCCESS(status); ++i) {
1131 char16_t ch = fPattern[i];
1132
1133 // Use subFormat() to format a repeated pattern character
1134 // when a different pattern or non-pattern character is seen
1135 if (ch != prevCh && count > 0) {
1136 subFormat(appendTo, prevCh, count, capitalizationContext, fieldNum++,
1137 prevCh, handler, *workCal, status);
1138 count = 0;
1139 }
1140 if (ch == QUOTE) {
1141 // Consecutive single quotes are a single quote literal,
1142 // either outside of quotes or between quotes
1143 if ((i+1) < patternLength && fPattern[i+1] == QUOTE) {
1144 appendTo += QUOTE;
1145 ++i;
1146 } else {
1147 inQuote = ! inQuote;
1148 }
1149 }
1150 else if (!inQuote && isSyntaxChar(ch)) {
1151 // ch is a date-time pattern character to be interpreted
1152 // by subFormat(); count the number of times it is repeated
1153 prevCh = ch;
1154 ++count;
1155 }
1156 else {
1157 // Append quoted characters and unquoted non-pattern characters
1158 appendTo += ch;
1159 }
1160 }
1161
1162 // Format the last item in the pattern, if any
1163 if (count > 0) {
1164 subFormat(appendTo, prevCh, count, capitalizationContext, fieldNum++,
1165 prevCh, handler, *workCal, status);
1166 }
1167
1168 delete calClone;
1169
1170 return appendTo;
1171}
1172
1173//----------------------------------------------------------------------
1174
1175/* Map calendar field into calendar field level.
1176 * the larger the level, the smaller the field unit.
1177 * For example, UCAL_ERA level is 0, UCAL_YEAR level is 10,
1178 * UCAL_MONTH level is 20.
1179 * NOTE: if new fields adds in, the table needs to update.
1180 */
1181const int32_t
1182SimpleDateFormat::fgCalendarFieldToLevel[] =
1183{
1184 /*GyM*/ 0, 10, 20,
1185 /*wW*/ 20, 30,
1186 /*dDEF*/ 30, 20, 30, 30,
1187 /*ahHm*/ 40, 50, 50, 60,
1188 /*sS*/ 70, 80,
1189 /*z?Y*/ 0, 0, 10,
1190 /*eug*/ 30, 10, 0,
1191 /*A?.*/ 40, 0, 0
1192};
1193
1194int32_t SimpleDateFormat::getLevelFromChar(char16_t ch) {
1195 // Map date field LETTER into calendar field level.
1196 // the larger the level, the smaller the field unit.
1197 // NOTE: if new fields adds in, the table needs to update.
1198 static const int32_t mapCharToLevel[] = {
1199 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1200 //
1201 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1202 // ! " # $ % & ' ( ) * + , - . /
1203 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1204#if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR0
1205 // 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
1206 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1,
1207#else
1208 // 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
1209 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
1210#endif
1211 // @ A B C D E F G H I J K L M N O
1212 -1, 40, -1, -1, 20, 30, 30, 0, 50, -1, -1, 50, 20, 20, -1, 0,
1213 // P Q R S T U V W X Y Z [ \ ] ^ _
1214 -1, 20, -1, 80, -1, 10, 0, 30, 0, 10, 0, -1, -1, -1, -1, -1,
1215 // ` a b c d e f g h i j k l m n o
1216 -1, 40, -1, 30, 30, 30, -1, 0, 50, -1, -1, 50, 0, 60, -1, -1,
1217 // p q r s t u v w x y z { | } ~
1218 -1, 20, 10, 70, -1, 10, 0, 20, 0, 10, 0, -1, -1, -1, -1, -1
1219 };
1220
1221 return ch < UPRV_LENGTHOF(mapCharToLevel)(int32_t)(sizeof(mapCharToLevel)/sizeof((mapCharToLevel)[0])) ? mapCharToLevel[ch] : -1;
1222}
1223
1224UBool SimpleDateFormat::isSyntaxChar(char16_t ch) {
1225 static const UBool mapCharToIsSyntax[] = {
1226 //
1227 false, false, false, false, false, false, false, false,
1228 //
1229 false, false, false, false, false, false, false, false,
1230 //
1231 false, false, false, false, false, false, false, false,
1232 //
1233 false, false, false, false, false, false, false, false,
1234 // ! " # $ % & '
1235 false, false, false, false, false, false, false, false,
1236 // ( ) * + , - . /
1237 false, false, false, false, false, false, false, false,
1238 // 0 1 2 3 4 5 6 7
1239 false, false, false, false, false, false, false, false,
1240#if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR0
1241 // 8 9 : ; < = > ?
1242 false, false, true, false, false, false, false, false,
1243#else
1244 // 8 9 : ; < = > ?
1245 false, false, false, false, false, false, false, false,
1246#endif
1247 // @ A B C D E F G
1248 false, true, true, true, true, true, true, true,
1249 // H I J K L M N O
1250 true, true, true, true, true, true, true, true,
1251 // P Q R S T U V W
1252 true, true, true, true, true, true, true, true,
1253 // X Y Z [ \ ] ^ _
1254 true, true, true, false, false, false, false, false,
1255 // ` a b c d e f g
1256 false, true, true, true, true, true, true, true,
1257 // h i j k l m n o
1258 true, true, true, true, true, true, true, true,
1259 // p q r s t u v w
1260 true, true, true, true, true, true, true, true,
1261 // x y z { | } ~
1262 true, true, true, false, false, false, false, false
1263 };
1264
1265 return ch < UPRV_LENGTHOF(mapCharToIsSyntax)(int32_t)(sizeof(mapCharToIsSyntax)/sizeof((mapCharToIsSyntax
)[0]))
? mapCharToIsSyntax[ch] : false;
1266}
1267
1268// Map index into pattern character string to Calendar field number.
1269const UCalendarDateFields
1270SimpleDateFormat::fgPatternIndexToCalendarField[] =
1271{
1272 /*GyM*/ UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
1273 /*dkH*/ UCAL_DATE, UCAL_HOUR_OF_DAY, UCAL_HOUR_OF_DAY,
1274 /*msS*/ UCAL_MINUTE, UCAL_SECOND, UCAL_MILLISECOND,
1275 /*EDF*/ UCAL_DAY_OF_WEEK, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK_IN_MONTH,
1276 /*wWa*/ UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_AM_PM,
1277 /*hKz*/ UCAL_HOUR, UCAL_HOUR, UCAL_ZONE_OFFSET,
1278 /*Yeu*/ UCAL_YEAR_WOY, UCAL_DOW_LOCAL, UCAL_EXTENDED_YEAR,
1279 /*gAZ*/ UCAL_JULIAN_DAY, UCAL_MILLISECONDS_IN_DAY, UCAL_ZONE_OFFSET,
1280 /*v*/ UCAL_ZONE_OFFSET,
1281 /*c*/ UCAL_DOW_LOCAL,
1282 /*L*/ UCAL_MONTH,
1283 /*Q*/ UCAL_MONTH,
1284 /*q*/ UCAL_MONTH,
1285 /*V*/ UCAL_ZONE_OFFSET,
1286 /*U*/ UCAL_YEAR,
1287 /*O*/ UCAL_ZONE_OFFSET,
1288 /*Xx*/ UCAL_ZONE_OFFSET, UCAL_ZONE_OFFSET,
1289 /*r*/ UCAL_EXTENDED_YEAR,
1290 /*bB*/ UCAL_FIELD_COUNT, UCAL_FIELD_COUNT, // no mappings to calendar fields
1291#if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR0
1292 /*:*/ UCAL_FIELD_COUNT, /* => no useful mapping to any calendar field */
1293#else
1294 /*no pattern char for UDAT_TIME_SEPARATOR_FIELD*/ UCAL_FIELD_COUNT, /* => no useful mapping to any calendar field */
1295#endif
1296};
1297
1298// Map index into pattern character string to DateFormat field number
1299const UDateFormatField
1300SimpleDateFormat::fgPatternIndexToDateFormatField[] = {
1301 /*GyM*/ UDAT_ERA_FIELD, UDAT_YEAR_FIELD, UDAT_MONTH_FIELD,
1302 /*dkH*/ UDAT_DATE_FIELD, UDAT_HOUR_OF_DAY1_FIELD, UDAT_HOUR_OF_DAY0_FIELD,
1303 /*msS*/ UDAT_MINUTE_FIELD, UDAT_SECOND_FIELD, UDAT_FRACTIONAL_SECOND_FIELD,
1304 /*EDF*/ UDAT_DAY_OF_WEEK_FIELD, UDAT_DAY_OF_YEAR_FIELD, UDAT_DAY_OF_WEEK_IN_MONTH_FIELD,
1305 /*wWa*/ UDAT_WEEK_OF_YEAR_FIELD, UDAT_WEEK_OF_MONTH_FIELD, UDAT_AM_PM_FIELD,
1306 /*hKz*/ UDAT_HOUR1_FIELD, UDAT_HOUR0_FIELD, UDAT_TIMEZONE_FIELD,
1307 /*Yeu*/ UDAT_YEAR_WOY_FIELD, UDAT_DOW_LOCAL_FIELD, UDAT_EXTENDED_YEAR_FIELD,
1308 /*gAZ*/ UDAT_JULIAN_DAY_FIELD, UDAT_MILLISECONDS_IN_DAY_FIELD, UDAT_TIMEZONE_RFC_FIELD,
1309 /*v*/ UDAT_TIMEZONE_GENERIC_FIELD,
1310 /*c*/ UDAT_STANDALONE_DAY_FIELD,
1311 /*L*/ UDAT_STANDALONE_MONTH_FIELD,
1312 /*Q*/ UDAT_QUARTER_FIELD,
1313 /*q*/ UDAT_STANDALONE_QUARTER_FIELD,
1314 /*V*/ UDAT_TIMEZONE_SPECIAL_FIELD,
1315 /*U*/ UDAT_YEAR_NAME_FIELD,
1316 /*O*/ UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD,
1317 /*Xx*/ UDAT_TIMEZONE_ISO_FIELD, UDAT_TIMEZONE_ISO_LOCAL_FIELD,
1318 /*r*/ UDAT_RELATED_YEAR_FIELD,
1319 /*bB*/ UDAT_AM_PM_MIDNIGHT_NOON_FIELD, UDAT_FLEXIBLE_DAY_PERIOD_FIELD,
1320#if UDAT_HAS_PATTERN_CHAR_FOR_TIME_SEPARATOR0
1321 /*:*/ UDAT_TIME_SEPARATOR_FIELD,
1322#else
1323 /*no pattern char for UDAT_TIME_SEPARATOR_FIELD*/ UDAT_TIME_SEPARATOR_FIELD,
1324#endif
1325};
1326
1327//----------------------------------------------------------------------
1328
1329/**
1330 * Append symbols[value] to dst. Make sure the array index is not out
1331 * of bounds.
1332 */
1333static inline void
1334_appendSymbol(UnicodeString& dst,
1335 int32_t value,
1336 const UnicodeString* symbols,
1337 int32_t symbolsCount) {
1338 U_ASSERT(0 <= value && value < symbolsCount)(static_cast <bool> (0 <= value && value <
symbolsCount) ? void (0) : __assert_fail ("0 <= value && value < symbolsCount"
, __builtin_FILE (), __builtin_LINE (), __extension__ __PRETTY_FUNCTION__
))
;
1339 if (0 <= value && value < symbolsCount) {
1340 dst += symbols[value];
1341 }
1342}
1343
1344static inline void
1345_appendSymbolWithMonthPattern(UnicodeString& dst, int32_t value, const UnicodeString* symbols, int32_t symbolsCount,
1346 const UnicodeString* monthPattern, UErrorCode& status) {
1347 U_ASSERT(0 <= value && value < symbolsCount)(static_cast <bool> (0 <= value && value <
symbolsCount) ? void (0) : __assert_fail ("0 <= value && value < symbolsCount"
, __builtin_FILE (), __builtin_LINE (), __extension__ __PRETTY_FUNCTION__
))
;
1348 if (0 <= value && value < symbolsCount) {
1349 if (monthPattern == nullptr) {
1350 dst += symbols[value];
1351 } else {
1352 SimpleFormatter(*monthPattern, 1, 1, status).format(symbols[value], dst, status);
1353 }
1354 }
1355}
1356
1357//----------------------------------------------------------------------
1358
1359void
1360SimpleDateFormat::initSimpleNumberFormatter(UErrorCode &status) {
1361 if (U_FAILURE(status)) {
1362 return;
1363 }
1364 const auto* df = dynamic_cast<const DecimalFormat*>(fNumberFormat);
1365 if (df == nullptr) {
1366 return;
1367 }
1368 const DecimalFormatSymbols* syms = df->getDecimalFormatSymbols();
1369 if (syms == nullptr) {
1370 return;
1371 }
1372 fSimpleNumberFormatter = new number::SimpleNumberFormatter(
1373 number::SimpleNumberFormatter::forLocaleAndSymbolsAndGroupingStrategy(
1374 fLocale, *syms, UNUM_GROUPING_OFF, status
1375 )
1376 );
1377 if (fSimpleNumberFormatter == nullptr) {
1378 status = U_MEMORY_ALLOCATION_ERROR;
1379 }
1380}
1381
1382void
1383SimpleDateFormat::initNumberFormatters(const Locale &locale,UErrorCode &status) {
1384 if (U_FAILURE(status)) {
1385 return;
1386 }
1387 if ( fDateOverride.isBogus() && fTimeOverride.isBogus() ) {
1388 return;
1389 }
1390 umtx_lock(&LOCK);
1391 if (fSharedNumberFormatters == nullptr) {
1392 fSharedNumberFormatters = allocSharedNumberFormatters();
1393 if (fSharedNumberFormatters == nullptr) {
1394 status = U_MEMORY_ALLOCATION_ERROR;
1395 }
1396 }
1397 umtx_unlock(&LOCK);
1398
1399 if (U_FAILURE(status)) {
1400 return;
1401 }
1402
1403 processOverrideString(locale,fDateOverride,kOvrStrDate,status);
1404 processOverrideString(locale,fTimeOverride,kOvrStrTime,status);
1405}
1406
1407void
1408SimpleDateFormat::processOverrideString(const Locale &locale, const UnicodeString &str, int8_t type, UErrorCode &status) {
1409 if (str.isBogus() || U_FAILURE(status)) {
1410 return;
1411 }
1412
1413 int32_t start = 0;
1414 int32_t len;
1415 UnicodeString nsName;
1416 UnicodeString ovrField;
1417 UBool moreToProcess = true;
1418 NSOverride *overrideList = nullptr;
1419
1420 while (moreToProcess) {
1421 int32_t delimiterPosition = str.indexOf(static_cast<char16_t>(ULOC_KEYWORD_ITEM_SEPARATOR_UNICODE0x3B), start);
1422 if (delimiterPosition == -1) {
1423 moreToProcess = false;
1424 len = str.length() - start;
1425 } else {
1426 len = delimiterPosition - start;
1427 }
1428 UnicodeString currentString(str,start,len);
1429 int32_t equalSignPosition = currentString.indexOf(static_cast<char16_t>(ULOC_KEYWORD_ASSIGN_UNICODE0x3D), 0);
1430 if (equalSignPosition == -1) { // Simple override string such as "hebrew"
1431 nsName.setTo(currentString);
1432 ovrField.setToBogus();
1433 } else { // Field specific override string such as "y=hebrew"
1434 nsName.setTo(currentString,equalSignPosition+1);
1435 ovrField.setTo(currentString,0,1); // We just need the first character.
1436 }
1437
1438 int32_t nsNameHash = nsName.hashCode();
1439 // See if the numbering system is in the override list, if not, then add it.
1440 NSOverride *curr = overrideList;
1441 const SharedNumberFormat *snf = nullptr;
1442 UBool found = false;
1443 while ( curr && !found ) {
1444 if ( curr->hash == nsNameHash ) {
1445 snf = curr->snf;
1446 found = true;
1447 }
1448 curr = curr->next;
1449 }
1450
1451 if (!found) {
1452 LocalPointer<NSOverride> cur(new NSOverride);
1453 if (!cur.isNull()) {
1454 char kw[ULOC_KEYWORD_AND_VALUES_CAPACITY100];
1455 uprv_strcpy(kw,"numbers="):: strcpy(kw, "numbers=");
1456 nsName.extract(0,len,kw+8,ULOC_KEYWORD_AND_VALUES_CAPACITY100-8,US_INVicu::UnicodeString::kInvariant);
1457
1458 Locale ovrLoc(locale.getLanguage(),locale.getCountry(),locale.getVariant(),kw);
1459 cur->hash = nsNameHash;
1460 cur->next = overrideList;
1461 SharedObject::copyPtr(
1462 createSharedNumberFormat(ovrLoc, status), cur->snf);
1463 if (U_FAILURE(status)) {
1464 if (overrideList) {
1465 overrideList->free();
1466 }
1467 return;
1468 }
1469 snf = cur->snf;
1470 overrideList = cur.orphan();
1471 } else {
1472 status = U_MEMORY_ALLOCATION_ERROR;
1473 if (overrideList) {
1474 overrideList->free();
1475 }
1476 return;
1477 }
1478 }
1479
1480 // Now that we have an appropriate number formatter, fill in the appropriate spaces in the
1481 // number formatters table.
1482 if (ovrField.isBogus()) {
1483 switch (type) {
1484 case kOvrStrDate:
1485 case kOvrStrBoth: {
1486 for ( int8_t i=0 ; i<kDateFieldsCount; i++ ) {
1487 SharedObject::copyPtr(snf, fSharedNumberFormatters[kDateFields[i]]);
1488 }
1489 if (type==kOvrStrDate) {
1490 break;
1491 }
1492 U_FALLTHROUGH[[clang::fallthrough]];
1493 }
1494 case kOvrStrTime : {
1495 for ( int8_t i=0 ; i<kTimeFieldsCount; i++ ) {
1496 SharedObject::copyPtr(snf, fSharedNumberFormatters[kTimeFields[i]]);
1497 }
1498 break;
1499 }
1500 }
1501 } else {
1502 // if the pattern character is unrecognized, signal an error and bail out
1503 UDateFormatField patternCharIndex =
1504 DateFormatSymbols::getPatternCharIndex(ovrField.charAt(0));
1505 if (patternCharIndex == UDAT_FIELD_COUNT) {
1506 status = U_INVALID_FORMAT_ERROR;
1507 if (overrideList) {
1508 overrideList->free();
1509 }
1510 return;
1511 }
1512 SharedObject::copyPtr(snf, fSharedNumberFormatters[patternCharIndex]);
1513 }
1514
1515 start = delimiterPosition + 1;
1516 }
1517 if (overrideList) {
1518 overrideList->free();
1519 }
1520}
1521
1522//---------------------------------------------------------------------
1523void
1524SimpleDateFormat::subFormat(UnicodeString &appendTo,
1525 char16_t ch,
1526 int32_t count,
1527 UDisplayContext capitalizationContext,
1528 int32_t fieldNum,
1529 char16_t fieldToOutput,
1530 FieldPositionHandler& handler,
1531 Calendar& cal,
1532 UErrorCode& status) const
1533{
1534 static const int32_t maxIntCount = 10;
1535 static const UnicodeString hebr(u"hebr");
1536
1537 if (U_FAILURE(status)) {
1538 return;
1539 }
1540
1541 // this function gets called by format() to produce the appropriate substitution
1542 // text for an individual pattern symbol (e.g., "HH" or "yyyy")
1543
1544 UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(ch);
1545 int32_t beginOffset = appendTo.length();
1546 DateFormatSymbols::ECapitalizationContextUsageType capContextUsageType = DateFormatSymbols::kCapContextUsageOther;
1547
1548 // if the pattern character is unrecognized, signal an error and dump out
1549 if (patternCharIndex == UDAT_FIELD_COUNT)
1550 {
1551 if (ch != 0x6C) { // pattern char 'l' (SMALL LETTER L) just gets ignored
1552 status = U_INVALID_FORMAT_ERROR;
1553 }
1554 return;
1555 }
1556
1557 UCalendarDateFields field = fgPatternIndexToCalendarField[patternCharIndex];
1558 int32_t value = 0;
1559 // Don't get value unless it is useful
1560 if (field < UCAL_FIELD_COUNT) {
1561 value = (patternCharIndex != UDAT_RELATED_YEAR_FIELD)? cal.get(field, status): cal.getRelatedYear(status);
1562 if (U_FAILURE(status)) {
1563 return;
1564 }
1565 }
1566
1567 const NumberFormat *currentNumberFormat = getNumberFormatByIndex(patternCharIndex);
1568 if (currentNumberFormat == nullptr) {
1569 status = U_INTERNAL_PROGRAM_ERROR;
1570 return;
1571 }
1572
1573 switch (patternCharIndex) {
1574
1575 // for any "G" symbol, write out the appropriate era string
1576 // "GGGG" is wide era name, "GGGGG" is narrow era name, anything else is abbreviated name
1577 case UDAT_ERA_FIELD:
1578 {
1579 const char* type = cal.getType();
1580 if (strcmp(type, "chinese") == 0 ||
1581 strcmp(type, "dangi") == 0) {
1582 zeroPaddingNumber(currentNumberFormat,appendTo, value, 1, 9); // as in ICU4J
1583 } else {
1584 if (count == 5) {
1585 _appendSymbol(appendTo, value, fSymbols->fNarrowEras, fSymbols->fNarrowErasCount);
1586 capContextUsageType = DateFormatSymbols::kCapContextUsageEraNarrow;
1587 } else if (count == 4) {
1588 _appendSymbol(appendTo, value, fSymbols->fEraNames, fSymbols->fEraNamesCount);
1589 capContextUsageType = DateFormatSymbols::kCapContextUsageEraWide;
1590 } else {
1591 _appendSymbol(appendTo, value, fSymbols->fEras, fSymbols->fErasCount);
1592 capContextUsageType = DateFormatSymbols::kCapContextUsageEraAbbrev;
1593 }
1594 }
1595 }
1596 break;
1597
1598 case UDAT_YEAR_NAME_FIELD:
1599 if (fSymbols->fShortYearNames != nullptr && value <= fSymbols->fShortYearNamesCount) {
1600 // the Calendar YEAR field runs 1 through 60 for cyclic years
1601 _appendSymbol(appendTo, value - 1, fSymbols->fShortYearNames, fSymbols->fShortYearNamesCount);
1602 break;
1603 }
1604 // else fall through to numeric year handling, do not break here
1605 U_FALLTHROUGH[[clang::fallthrough]];
1606
1607 // OLD: for "yyyy", write out the whole year; for "yy", write out the last 2 digits
1608 // NEW: UTS#35:
1609//Year y yy yyy yyyy yyyyy
1610//AD 1 1 01 001 0001 00001
1611//AD 12 12 12 012 0012 00012
1612//AD 123 123 23 123 0123 00123
1613//AD 1234 1234 34 1234 1234 01234
1614//AD 12345 12345 45 12345 12345 12345
1615 case UDAT_YEAR_FIELD:
1616 case UDAT_YEAR_WOY_FIELD:
1617 if (fDateOverride.compare(hebr)==0 && value>HEBREW_CAL_CUR_MILLENIUM_START_YEAR && value<HEBREW_CAL_CUR_MILLENIUM_END_YEAR) {
1618 value-=HEBREW_CAL_CUR_MILLENIUM_START_YEAR;
1619 }
1620 if(count == 2)
1621 zeroPaddingNumber(currentNumberFormat, appendTo, value, 2, 2);
1622 else
1623 zeroPaddingNumber(currentNumberFormat, appendTo, value, count, maxIntCount);
1624 break;
1625
1626 // for "MMMM"/"LLLL", write out the whole month name, for "MMM"/"LLL", write out the month
1627 // abbreviation, for "M"/"L" or "MM"/"LL", write out the month as a number with the
1628 // appropriate number of digits
1629 // for "MMMMM"/"LLLLL", use the narrow form
1630 case UDAT_MONTH_FIELD:
1631 case UDAT_STANDALONE_MONTH_FIELD:
1632 if (typeid(cal) == typeid(HebrewCalendar)) {
1633 if (HebrewCalendar::isLeapYear(cal.get(UCAL_YEAR,status)) && value == 6 && count >= 3 )
1634 value = 13; // Show alternate form for Adar II in leap years in Hebrew calendar.
1635 if (!HebrewCalendar::isLeapYear(cal.get(UCAL_YEAR,status)) && value >= 6 && count < 3 )
1636 value--; // Adjust the month number down 1 in Hebrew non-leap years, i.e. Adar is 6, not 7.
1637 }
1638 {
1639 int32_t isLeapMonth = (fSymbols->fLeapMonthPatterns != nullptr && fSymbols->fLeapMonthPatternsCount >= DateFormatSymbols::kMonthPatternsCount)?
1640 cal.get(UCAL_IS_LEAP_MONTH, status): 0;
1641 // should consolidate the next section by using arrays of pointers & counts for the right symbols...
1642 if (count == 5) {
1643 if (patternCharIndex == UDAT_MONTH_FIELD) {
1644 _appendSymbolWithMonthPattern(appendTo, value, fSymbols->fNarrowMonths, fSymbols->fNarrowMonthsCount,
1645 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatNarrow]): nullptr, status);
1646 } else {
1647 _appendSymbolWithMonthPattern(appendTo, value, fSymbols->fStandaloneNarrowMonths, fSymbols->fStandaloneNarrowMonthsCount,
1648 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneNarrow]): nullptr, status);
1649 }
1650 capContextUsageType = DateFormatSymbols::kCapContextUsageMonthNarrow;
1651 } else if (count == 4) {
1652 if (patternCharIndex == UDAT_MONTH_FIELD) {
1653 _appendSymbolWithMonthPattern(appendTo, value, fSymbols->fMonths, fSymbols->fMonthsCount,
1654 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatWide]): nullptr, status);
1655 capContextUsageType = DateFormatSymbols::kCapContextUsageMonthFormat;
1656 } else {
1657 _appendSymbolWithMonthPattern(appendTo, value, fSymbols->fStandaloneMonths, fSymbols->fStandaloneMonthsCount,
1658 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneWide]): nullptr, status);
1659 capContextUsageType = DateFormatSymbols::kCapContextUsageMonthStandalone;
1660 }
1661 } else if (count == 3) {
1662 if (patternCharIndex == UDAT_MONTH_FIELD) {
1663 _appendSymbolWithMonthPattern(appendTo, value, fSymbols->fShortMonths, fSymbols->fShortMonthsCount,
1664 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatAbbrev]): nullptr, status);
1665 capContextUsageType = DateFormatSymbols::kCapContextUsageMonthFormat;
1666 } else {
1667 _appendSymbolWithMonthPattern(appendTo, value, fSymbols->fStandaloneShortMonths, fSymbols->fStandaloneShortMonthsCount,
1668 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneAbbrev]): nullptr, status);
1669 capContextUsageType = DateFormatSymbols::kCapContextUsageMonthStandalone;
1670 }
1671 } else {
1672 UnicodeString monthNumber;
1673 zeroPaddingNumber(currentNumberFormat,monthNumber, value + 1, count, maxIntCount);
1674 _appendSymbolWithMonthPattern(appendTo, 0, &monthNumber, 1,
1675 (isLeapMonth!=0)? &(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternNumeric]): nullptr, status);
1676 }
1677 }
1678 break;
1679
1680 // for "k" and "kk", write out the hour, adjusting midnight to appear as "24"
1681 case UDAT_HOUR_OF_DAY1_FIELD:
1682 if (value == 0)
1683 zeroPaddingNumber(currentNumberFormat,appendTo, cal.getMaximum(UCAL_HOUR_OF_DAY) + 1, count, maxIntCount);
1684 else
1685 zeroPaddingNumber(currentNumberFormat,appendTo, value, count, maxIntCount);
1686 break;
1687
1688 case UDAT_FRACTIONAL_SECOND_FIELD:
1689 // Fractional seconds left-justify
1690 {
1691 int32_t minDigits = (count > 3) ? 3 : count;
1692 if (count == 1) {
1693 value /= 100;
1694 } else if (count == 2) {
1695 value /= 10;
1696 }
1697 zeroPaddingNumber(currentNumberFormat, appendTo, value, minDigits, maxIntCount);
1698 if (count > 3) {
1699 zeroPaddingNumber(currentNumberFormat, appendTo, 0, count - 3, maxIntCount);
1700 }
1701 }
1702 break;
1703
1704 // for "ee" or "e", use local numeric day-of-the-week
1705 // for "EEEEEE" or "eeeeee", write out the short day-of-the-week name
1706 // for "EEEEE" or "eeeee", write out the narrow day-of-the-week name
1707 // for "EEEE" or "eeee", write out the wide day-of-the-week name
1708 // for "EEE" or "EE" or "E" or "eee", write out the abbreviated day-of-the-week name
1709 case UDAT_DOW_LOCAL_FIELD:
1710 if ( count < 3 ) {
1711 zeroPaddingNumber(currentNumberFormat,appendTo, value, count, maxIntCount);
1712 break;
1713 }
1714 // fall through to EEEEE-EEE handling, but for that we don't want local day-of-week,
1715 // we want standard day-of-week, so first fix value to work for EEEEE-EEE.
1716 value = cal.get(UCAL_DAY_OF_WEEK, status);
1717 if (U_FAILURE(status)) {
1718 return;
1719 }
1720 // fall through, do not break here
1721 U_FALLTHROUGH[[clang::fallthrough]];
1722 case UDAT_DAY_OF_WEEK_FIELD:
1723 if (count == 5) {
1724 _appendSymbol(appendTo, value, fSymbols->fNarrowWeekdays,
1725 fSymbols->fNarrowWeekdaysCount);
1726 capContextUsageType = DateFormatSymbols::kCapContextUsageDayNarrow;
1727 } else if (count == 4) {
1728 _appendSymbol(appendTo, value, fSymbols->fWeekdays,
1729 fSymbols->fWeekdaysCount);
1730 capContextUsageType = DateFormatSymbols::kCapContextUsageDayFormat;
Value stored to 'capContextUsageType' is never read
1731 } else if (count == 6) {
1732 _appendSymbol(appendTo, value, fSymbols->fShorterWeekdays,
1733 fSymbols->fShorterWeekdaysCount);
1734 capContextUsageType = DateFormatSymbols::kCapContextUsageDayFormat;
1735 } else {
1736 _appendSymbol(appendTo, value, fSymbols->fShortWeekdays,
1737 fSymbols->fShortWeekdaysCount);
1738 capContextUsageType = DateFormatSymbols::kCapContextUsageDayFormat;
1739 }
1740 break;
1741
1742 // for "ccc", write out the abbreviated day-of-the-week name
1743 // for "cccc", write out the wide day-of-the-week name
1744 // for "ccccc", use the narrow day-of-the-week name
1745 // for "ccccc", use the short day-of-the-week name
1746 case UDAT_STANDALONE_DAY_FIELD:
1747 if ( count < 3 ) {
1748 zeroPaddingNumber(currentNumberFormat,appendTo, value, 1, maxIntCount);
1749 break;
1750 }
1751 // fall through to alpha DOW handling, but for that we don't want local day-of-week,
1752 // we want standard day-of-week, so first fix value.
1753 value = cal.get(UCAL_DAY_OF_WEEK, status);
1754 if (U_FAILURE(status)) {
1755 return;
1756 }
1757 if (count == 5) {
1758 _appendSymbol(appendTo, value, fSymbols->fStandaloneNarrowWeekdays,
1759 fSymbols->fStandaloneNarrowWeekdaysCount);
1760 capContextUsageType = DateFormatSymbols::kCapContextUsageDayNarrow;
1761 } else if (count == 4) {
1762 _appendSymbol(appendTo, value, fSymbols->fStandaloneWeekdays,
1763 fSymbols->fStandaloneWeekdaysCount);
1764 capContextUsageType = DateFormatSymbols::kCapContextUsageDayStandalone;
1765 } else if (count == 6) {
1766 _appendSymbol(appendTo, value, fSymbols->fStandaloneShorterWeekdays,
1767 fSymbols->fStandaloneShorterWeekdaysCount);
1768 capContextUsageType = DateFormatSymbols::kCapContextUsageDayStandalone;
1769 } else { // count == 3
1770 _appendSymbol(appendTo, value, fSymbols->fStandaloneShortWeekdays,
1771 fSymbols->fStandaloneShortWeekdaysCount);
1772 capContextUsageType = DateFormatSymbols::kCapContextUsageDayStandalone;
1773 }
1774 break;
1775
1776 // for "a" symbol, write out the whole AM/PM string
1777 case UDAT_AM_PM_FIELD:
1778 if (count == 4) {
1779 _appendSymbol(appendTo, value, fSymbols->fWideAmPms,
1780 fSymbols->fWideAmPmsCount);
1781 } else if (count == 5) {
1782 _appendSymbol(appendTo, value, fSymbols->fNarrowAmPms,
1783 fSymbols->fNarrowAmPmsCount);
1784 } else {
1785 _appendSymbol(appendTo, value, fSymbols->fAmPms,
1786 fSymbols->fAmPmsCount);
1787 }
1788 break;
1789
1790 // if we see pattern character for UDAT_TIME_SEPARATOR_FIELD (none currently defined),
1791 // write out the time separator string. Leave support in for future definition.
1792 case UDAT_TIME_SEPARATOR_FIELD:
1793 {
1794 UnicodeString separator;
1795 appendTo += fSymbols->getTimeSeparatorString(separator);
1796 }
1797 break;
1798
1799 // for "h" and "hh", write out the hour, adjusting noon and midnight to show up
1800 // as "12"
1801 case UDAT_HOUR1_FIELD:
1802 if (value == 0)
1803 zeroPaddingNumber(currentNumberFormat,appendTo, cal.getLeastMaximum(UCAL_HOUR) + 1, count, maxIntCount);
1804 else
1805 zeroPaddingNumber(currentNumberFormat,appendTo, value, count, maxIntCount);
1806 break;
1807
1808 case UDAT_TIMEZONE_FIELD: // 'z'
1809 case UDAT_TIMEZONE_RFC_FIELD: // 'Z'
1810 case UDAT_TIMEZONE_GENERIC_FIELD: // 'v'
1811 case UDAT_TIMEZONE_SPECIAL_FIELD: // 'V'
1812 case UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD: // 'O'
1813 case UDAT_TIMEZONE_ISO_FIELD: // 'X'
1814 case UDAT_TIMEZONE_ISO_LOCAL_FIELD: // 'x'
1815 {
1816 char16_t zsbuf[ZONE_NAME_U16_MAX128];
1817 UnicodeString zoneString(zsbuf, 0, UPRV_LENGTHOF(zsbuf)(int32_t)(sizeof(zsbuf)/sizeof((zsbuf)[0])));
1818 const TimeZone& tz = cal.getTimeZone();
1819 UDate date = cal.getTime(status);
1820 const TimeZoneFormat *tzfmt = tzFormat(status);
1821 if (U_SUCCESS(status)) {
1822 switch (patternCharIndex) {
1823 case UDAT_TIMEZONE_FIELD:
1824 if (count < 4) {
1825 // "z", "zz", "zzz"
1826 tzfmt->format(UTZFMT_STYLE_SPECIFIC_SHORT, tz, date, zoneString);
1827 capContextUsageType = DateFormatSymbols::kCapContextUsageMetazoneShort;
1828 } else {
1829 // "zzzz" or longer
1830 tzfmt->format(UTZFMT_STYLE_SPECIFIC_LONG, tz, date, zoneString);
1831 capContextUsageType = DateFormatSymbols::kCapContextUsageMetazoneLong;
1832 }
1833 break;
1834 case UDAT_TIMEZONE_RFC_FIELD:
1835 if (count < 4) {
1836 // "Z"
1837 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL, tz, date, zoneString);
1838 } else if (count == 5) {
1839 // "ZZZZZ"
1840 tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_FULL, tz, date, zoneString);
1841 } else {
1842 // "ZZ", "ZZZ", "ZZZZ"
1843 tzfmt->format(UTZFMT_STYLE_LOCALIZED_GMT, tz, date, zoneString);
1844 }
1845 break;
1846 case UDAT_TIMEZONE_GENERIC_FIELD:
1847 if (count == 1) {
1848 // "v"
1849 tzfmt->format(UTZFMT_STYLE_GENERIC_SHORT, tz, date, zoneString);
1850 capContextUsageType = DateFormatSymbols::kCapContextUsageMetazoneShort;
1851 } else if (count == 4) {
1852 // "vvvv"
1853 tzfmt->format(UTZFMT_STYLE_GENERIC_LONG, tz, date, zoneString);
1854 capContextUsageType = DateFormatSymbols::kCapContextUsageMetazoneLong;
1855 }
1856 break;
1857 case UDAT_TIMEZONE_SPECIAL_FIELD:
1858 if (count == 1) {
1859 // "V"
1860 tzfmt->format(UTZFMT_STYLE_ZONE_ID_SHORT, tz, date, zoneString);
1861 } else if (count == 2) {
1862 // "VV"
1863 tzfmt->format(UTZFMT_STYLE_ZONE_ID, tz, date, zoneString);
1864 } else if (count == 3) {
1865 // "VVV"
1866 tzfmt->format(UTZFMT_STYLE_EXEMPLAR_LOCATION, tz, date, zoneString);
1867 } else if (count == 4) {
1868 // "VVVV"
1869 tzfmt->format(UTZFMT_STYLE_GENERIC_LOCATION, tz, date, zoneString);
1870 capContextUsageType = DateFormatSymbols::kCapContextUsageZoneLong;
1871 }
1872 break;
1873 case UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD:
1874 if (count == 1) {
1875 // "O"
1876 tzfmt->format(UTZFMT_STYLE_LOCALIZED_GMT_SHORT, tz, date, zoneString);
1877 } else if (count == 4) {
1878 // "OOOO"
1879 tzfmt->format(UTZFMT_STYLE_LOCALIZED_GMT, tz, date, zoneString);
1880 }
1881 break;
1882 case UDAT_TIMEZONE_ISO_FIELD:
1883 if (count == 1) {
1884 // "X"
1885 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_SHORT, tz, date, zoneString);
1886 } else if (count == 2) {
1887 // "XX"
1888 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_FIXED, tz, date, zoneString);
1889 } else if (count == 3) {
1890 // "XXX"
1891 tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_FIXED, tz, date, zoneString);
1892 } else if (count == 4) {
1893 // "XXXX"
1894 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_FULL, tz, date, zoneString);
1895 } else if (count == 5) {
1896 // "XXXXX"
1897 tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_FULL, tz, date, zoneString);
1898 }
1899 break;
1900 case UDAT_TIMEZONE_ISO_LOCAL_FIELD:
1901 if (count == 1) {
1902 // "x"
1903 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_LOCAL_SHORT, tz, date, zoneString);
1904 } else if (count == 2) {
1905 // "xx"
1906 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_LOCAL_FIXED, tz, date, zoneString);
1907 } else if (count == 3) {
1908 // "xxx"
1909 tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FIXED, tz, date, zoneString);
1910 } else if (count == 4) {
1911 // "xxxx"
1912 tzfmt->format(UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL, tz, date, zoneString);
1913 } else if (count == 5) {
1914 // "xxxxx"
1915 tzfmt->format(UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FULL, tz, date, zoneString);
1916 }
1917 break;
1918 default:
1919 UPRV_UNREACHABLE_EXITabort();
1920 }
1921 }
1922 // CLDR analyzes abbreviations as attaching to "standard time" and "daylight-saving time".
1923 // In en-GB, however, the abbreviations for Europe/London should attach to the offset:
1924 // +0: "GMT"
1925 // +1: "BST" either for British Summer Time or, in the turn of the 1960s and 1970s, British Standard Time
1926 // +2: "BDST" for British Double Summer Time (in the 1940s only)
1927 //
1928 // Do "GMT+2" instead of "BDST" at least for now on the assumption that present-day users
1929 // might not recognize the historical abbreviation.
1930 UnicodeString id;
1931 if (zoneString == u"GMT+0" && strcmp(fLocale.getBaseName(), "en_GB") == 0 && tz.getID(id) == u"Europe/London") {
1932 // Previously in upstream, +0 was formatted as "GMT" regardless of year. However, upstream
1933 // started doing "GMT+0" for +0 before 1970 while keeping "GMT" for +0 for newer dates, and that turned up
1934 // a Web compat issue with a British bank, so restoring "GMT" even for older dates.
1935 // https://unicode-org.atlassian.net/browse/CLDR-19362
1936 appendTo += u"GMT";
1937 } else if (zoneString == u"GMT+1" && strcmp(fLocale.getBaseName(), "en_GB") == 0 && tz.getID(id) == u"Europe/London") {
1938 // Avoid formatting +2 as "BST". This is about formatting correctness, not Web compat.
1939 // The same bank form that requires +0 to be formatted as "GMT" appears not
1940 // to expect a specific formatting for cases other than +0.
1941 // https://unicode-org.atlassian.net/browse/CLDR-19382
1942 appendTo += u"BST";
1943 } else {
1944 appendTo += zoneString;
1945 }
1946 }
1947 break;
1948
1949 case UDAT_QUARTER_FIELD:
1950 if (count >= 5)
1951 _appendSymbol(appendTo, value/3, fSymbols->fNarrowQuarters,
1952 fSymbols->fNarrowQuartersCount);
1953 else if (count == 4)
1954 _appendSymbol(appendTo, value/3, fSymbols->fQuarters,
1955 fSymbols->fQuartersCount);
1956 else if (count == 3)
1957 _appendSymbol(appendTo, value/3, fSymbols->fShortQuarters,
1958 fSymbols->fShortQuartersCount);
1959 else
1960 zeroPaddingNumber(currentNumberFormat,appendTo, (value/3) + 1, count, maxIntCount);
1961 break;
1962
1963 case UDAT_STANDALONE_QUARTER_FIELD:
1964 if (count >= 5)
1965 _appendSymbol(appendTo, value/3, fSymbols->fStandaloneNarrowQuarters,
1966 fSymbols->fStandaloneNarrowQuartersCount);
1967 else if (count == 4)
1968 _appendSymbol(appendTo, value/3, fSymbols->fStandaloneQuarters,
1969 fSymbols->fStandaloneQuartersCount);
1970 else if (count == 3)
1971 _appendSymbol(appendTo, value/3, fSymbols->fStandaloneShortQuarters,
1972 fSymbols->fStandaloneShortQuartersCount);
1973 else
1974 zeroPaddingNumber(currentNumberFormat,appendTo, (value/3) + 1, count, maxIntCount);
1975 break;
1976
1977 case UDAT_AM_PM_MIDNIGHT_NOON_FIELD:
1978 {
1979 const UnicodeString *toAppend = nullptr;
1980 int32_t hour = cal.get(UCAL_HOUR_OF_DAY, status);
1981
1982 // Note: "midnight" can be ambiguous as to whether it refers to beginning of day or end of day.
1983 // For ICU 57 output of "midnight" is temporarily suppressed.
1984
1985 // For "midnight" and "noon":
1986 // Time, as displayed, must be exactly noon or midnight.
1987 // This means minutes and seconds, if present, must be zero.
1988 if ((/*hour == 0 ||*/ hour == 12) &&
1989 (!fHasMinute || cal.get(UCAL_MINUTE, status) == 0) &&
1990 (!fHasSecond || cal.get(UCAL_SECOND, status) == 0)) {
1991 // Stealing am/pm value to use as our array index.
1992 // It works out: am/midnight are both 0, pm/noon are both 1,
1993 // 12 am is 12 midnight, and 12 pm is 12 noon.
1994 int32_t val = cal.get(UCAL_AM_PM, status);
1995
1996 if (count <= 3) {
1997 toAppend = &fSymbols->fAbbreviatedDayPeriods[val];
1998 } else if (count == 4 || count > 5) {
1999 toAppend = &fSymbols->fWideDayPeriods[val];
2000 } else { // count == 5
2001 toAppend = &fSymbols->fNarrowDayPeriods[val];
2002 }
2003 }
2004
2005 // toAppend is nullptr if time isn't exactly midnight or noon (as displayed).
2006 // toAppend is bogus if time is midnight or noon, but no localized string exists.
2007 // In either case, fall back to am/pm.
2008 if (toAppend == nullptr || toAppend->isBogus()) {
2009 // Reformat with identical arguments except ch, now changed to 'a'.
2010 // We are passing a different fieldToOutput because we want to add
2011 // 'b' to field position. This makes this fallback stable when
2012 // there is a data change on locales.
2013 subFormat(appendTo, u'a', count, capitalizationContext, fieldNum, u'b', handler, cal, status);
2014 return;
2015 } else {
2016 appendTo += *toAppend;
2017 }
2018
2019 break;
2020 }
2021
2022 case UDAT_FLEXIBLE_DAY_PERIOD_FIELD:
2023 {
2024 // TODO: Maybe fetch the DayperiodRules during initialization (instead of at the first
2025 // loading of an instance) if a relevant pattern character (b or B) is used.
2026 const DayPeriodRules *ruleSet = DayPeriodRules::getInstance(this->getSmpFmtLocale(), status);
2027 if (U_FAILURE(status)) {
2028 // Data doesn't conform to spec, therefore loading failed.
2029 break;
2030 }
2031 if (ruleSet == nullptr) {
2032 // Data doesn't exist for the locale we're looking for.
2033 // Falling back to am/pm.
2034 // We are passing a different fieldToOutput because we want to add
2035 // 'B' to field position. This makes this fallback stable when
2036 // there is a data change on locales.
2037 subFormat(appendTo, u'a', count, capitalizationContext, fieldNum, u'B', handler, cal, status);
2038 return;
2039 }
2040
2041 // Get current display time.
2042 int32_t hour = cal.get(UCAL_HOUR_OF_DAY, status);
2043 int32_t minute = 0;
2044 if (fHasMinute) {
2045 minute = cal.get(UCAL_MINUTE, status);
2046 }
2047 int32_t second = 0;
2048 if (fHasSecond) {
2049 second = cal.get(UCAL_SECOND, status);
2050 }
2051
2052 // Determine day period.
2053 DayPeriodRules::DayPeriod periodType;
2054 if (hour == 0 && minute == 0 && second == 0 && ruleSet->hasMidnight()) {
2055 periodType = DayPeriodRules::DAYPERIOD_MIDNIGHT;
2056 } else if (hour == 12 && minute == 0 && second == 0 && ruleSet->hasNoon()) {
2057 periodType = DayPeriodRules::DAYPERIOD_NOON;
2058 } else {
2059 periodType = ruleSet->getDayPeriodForHour(hour);
2060 }
2061
2062 // Rule set exists, therefore periodType can't be UNKNOWN.
2063 // Get localized string.
2064 U_ASSERT(periodType != DayPeriodRules::DAYPERIOD_UNKNOWN)(static_cast <bool> (periodType != DayPeriodRules::DAYPERIOD_UNKNOWN
) ? void (0) : __assert_fail ("periodType != DayPeriodRules::DAYPERIOD_UNKNOWN"
, __builtin_FILE (), __builtin_LINE (), __extension__ __PRETTY_FUNCTION__
))
;
2065 UnicodeString *toAppend = nullptr;
2066 int32_t index;
2067
2068 // Note: "midnight" can be ambiguous as to whether it refers to beginning of day or end of day.
2069 // For ICU 57 output of "midnight" is temporarily suppressed.
2070
2071 if (periodType != DayPeriodRules::DAYPERIOD_AM &&
2072 periodType != DayPeriodRules::DAYPERIOD_PM &&
2073 periodType != DayPeriodRules::DAYPERIOD_MIDNIGHT) {
2074 index = static_cast<int32_t>(periodType);
2075 if (count <= 3) {
2076 toAppend = &fSymbols->fAbbreviatedDayPeriods[index]; // i.e. short
2077 } else if (count == 4 || count > 5) {
2078 toAppend = &fSymbols->fWideDayPeriods[index];
2079 } else { // count == 5
2080 toAppend = &fSymbols->fNarrowDayPeriods[index];
2081 }
2082 }
2083
2084 // Fallback schedule:
2085 // Midnight/Noon -> General Periods -> AM/PM.
2086
2087 // Midnight/Noon -> General Periods.
2088 if ((toAppend == nullptr || toAppend->isBogus()) &&
2089 (periodType == DayPeriodRules::DAYPERIOD_MIDNIGHT ||
2090 periodType == DayPeriodRules::DAYPERIOD_NOON)) {
2091 periodType = ruleSet->getDayPeriodForHour(hour);
2092 index = static_cast<int32_t>(periodType);
2093
2094 if (count <= 3) {
2095 toAppend = &fSymbols->fAbbreviatedDayPeriods[index]; // i.e. short
2096 } else if (count == 4 || count > 5) {
2097 toAppend = &fSymbols->fWideDayPeriods[index];
2098 } else { // count == 5
2099 toAppend = &fSymbols->fNarrowDayPeriods[index];
2100 }
2101 }
2102
2103 // General Periods -> AM/PM.
2104 if (periodType == DayPeriodRules::DAYPERIOD_AM ||
2105 periodType == DayPeriodRules::DAYPERIOD_PM ||
2106 toAppend->isBogus()) {
2107 // We are passing a different fieldToOutput because we want to add
2108 // 'B' to field position iterator. This makes this fallback stable when
2109 // there is a data change on locales.
2110 subFormat(appendTo, u'a', count, capitalizationContext, fieldNum, u'B', handler, cal, status);
2111 return;
2112 }
2113 else {
2114 appendTo += *toAppend;
2115 }
2116
2117 break;
2118 }
2119
2120 // all of the other pattern symbols can be formatted as simple numbers with
2121 // appropriate zero padding
2122 default:
2123 zeroPaddingNumber(currentNumberFormat,appendTo, value, count, maxIntCount);
2124 break;
2125 }
2126#if !UCONFIG_NO_BREAK_ITERATION1
2127 // if first field, check to see whether we need to and are able to titlecase it
2128 if (fieldNum == 0 && fCapitalizationBrkIter != nullptr && appendTo.length() > beginOffset &&
2129 u_islower(appendTo.char32At(beginOffset))) {
2130 UBool titlecase = false;
2131 switch (capitalizationContext) {
2132 case UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE:
2133 titlecase = true;
2134 break;
2135 case UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU:
2136 titlecase = fSymbols->fCapitalization[capContextUsageType][0];
2137 break;
2138 case UDISPCTX_CAPITALIZATION_FOR_STANDALONE:
2139 titlecase = fSymbols->fCapitalization[capContextUsageType][1];
2140 break;
2141 default:
2142 // titlecase = false;
2143 break;
2144 }
2145 if (titlecase) {
2146 BreakIterator* const mutableCapitalizationBrkIter = fCapitalizationBrkIter->clone();
2147 UnicodeString firstField(appendTo, beginOffset);
2148 firstField.toTitle(mutableCapitalizationBrkIter, fLocale, U_TITLECASE_NO_LOWERCASE0x100 | U_TITLECASE_NO_BREAK_ADJUSTMENT0x200);
2149 appendTo.replaceBetween(beginOffset, appendTo.length(), firstField);
2150 delete mutableCapitalizationBrkIter;
2151 }
2152 }
2153#endif
2154
2155 handler.addAttribute(DateFormatSymbols::getPatternCharIndex(fieldToOutput), beginOffset, appendTo.length());
2156}
2157
2158//----------------------------------------------------------------------
2159
2160void SimpleDateFormat::adoptNumberFormat(NumberFormat *formatToAdopt) {
2161 // Null out the fast formatter, it references fNumberFormat which we're
2162 // about to invalidate
2163 delete fSimpleNumberFormatter;
2164 fSimpleNumberFormatter = nullptr;
2165
2166 fixNumberFormatForDates(*formatToAdopt);
2167 delete fNumberFormat;
2168 fNumberFormat = formatToAdopt;
2169
2170 // We successfully set the default number format. Now delete the overrides
2171 // (can't fail).
2172 if (fSharedNumberFormatters) {
2173 freeSharedNumberFormatters(fSharedNumberFormatters);
2174 fSharedNumberFormatters = nullptr;
2175 }
2176
2177 // Recompute fSimpleNumberFormatter if necessary
2178 UErrorCode localStatus = U_ZERO_ERROR;
2179 initSimpleNumberFormatter(localStatus);
2180}
2181
2182void SimpleDateFormat::adoptNumberFormat(const UnicodeString& fields, NumberFormat *formatToAdopt, UErrorCode &status){
2183 fixNumberFormatForDates(*formatToAdopt);
2184 LocalPointer<NumberFormat> fmt(formatToAdopt);
2185 if (U_FAILURE(status)) {
2186 return;
2187 }
2188
2189 // We must ensure fSharedNumberFormatters is allocated.
2190 if (fSharedNumberFormatters == nullptr) {
2191 fSharedNumberFormatters = allocSharedNumberFormatters();
2192 if (fSharedNumberFormatters == nullptr) {
2193 status = U_MEMORY_ALLOCATION_ERROR;
2194 return;
2195 }
2196 }
2197 const SharedNumberFormat *newFormat = createSharedNumberFormat(fmt.orphan());
2198 if (newFormat == nullptr) {
2199 status = U_MEMORY_ALLOCATION_ERROR;
2200 return;
2201 }
2202 for (int i=0; i<fields.length(); i++) {
2203 char16_t field = fields.charAt(i);
2204 // if the pattern character is unrecognized, signal an error and bail out
2205 UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(field);
2206 if (patternCharIndex == UDAT_FIELD_COUNT) {
2207 status = U_INVALID_FORMAT_ERROR;
2208 newFormat->deleteIfZeroRefCount();
2209 return;
2210 }
2211
2212 // Set the number formatter in the table
2213 SharedObject::copyPtr(
2214 newFormat, fSharedNumberFormatters[patternCharIndex]);
2215 }
2216 newFormat->deleteIfZeroRefCount();
2217}
2218
2219const NumberFormat *
2220SimpleDateFormat::getNumberFormatForField(char16_t field) const {
2221 UDateFormatField index = DateFormatSymbols::getPatternCharIndex(field);
2222 if (index == UDAT_FIELD_COUNT) {
2223 return nullptr;
2224 }
2225 return getNumberFormatByIndex(index);
2226}
2227
2228//----------------------------------------------------------------------
2229void
2230SimpleDateFormat::zeroPaddingNumber(
2231 const NumberFormat *currentNumberFormat,
2232 UnicodeString &appendTo,
2233 int32_t value, int32_t minDigits, int32_t maxDigits) const
2234{
2235
2236 if (currentNumberFormat == fNumberFormat && fSimpleNumberFormatter) {
2237 // Can use fast path
2238 // We create UFormattedNumberData ourselves to avoid a heap allocation
2239 // and corresponding free. Set the pointer to null afterwards to prevent
2240 // the implementation from attempting to free it.
2241 UErrorCode localStatus = U_ZERO_ERROR;
2242 number::impl::UFormattedNumberData data;
2243 data.quantity.setToLong(value);
2244 number::SimpleNumber number(&data, localStatus);
2245 number.setMinimumIntegerDigits(minDigits, localStatus);
2246 number.setMaximumIntegerDigits(maxDigits, localStatus);
2247
2248 number::FormattedNumber result = fSimpleNumberFormatter->format(std::move(number), localStatus);
2249 if (U_FAILURE(localStatus)) {
2250 result.fData = nullptr;
2251 return;
2252 }
2253 UnicodeStringAppendable appendable(appendTo);
2254 result.appendTo(appendable, localStatus);
2255 result.fData = nullptr;
2256 return;
2257 }
2258
2259 // Check for RBNF (no clone necessary)
2260 const auto* rbnf = dynamic_cast<const RuleBasedNumberFormat*>(currentNumberFormat);
2261 if (rbnf != nullptr) {
2262 FieldPosition pos(FieldPosition::DONT_CARE);
2263 rbnf->format(value, appendTo, pos); // 3rd arg is there to speed up processing
2264 return;
2265 }
2266
2267 // Fall back to slow path (clone and mutate the NumberFormat)
2268 if (currentNumberFormat != nullptr) {
2269 FieldPosition pos(FieldPosition::DONT_CARE);
2270 LocalPointer<NumberFormat> nf(currentNumberFormat->clone());
2271 nf->setMinimumIntegerDigits(minDigits);
2272 nf->setMaximumIntegerDigits(maxDigits);
2273 nf->format(value, appendTo, pos); // 3rd arg is there to speed up processing
2274 }
2275}
2276
2277//----------------------------------------------------------------------
2278
2279/**
2280 * Return true if the given format character, occurring count
2281 * times, represents a numeric field.
2282 */
2283UBool SimpleDateFormat::isNumeric(char16_t formatChar, int32_t count) {
2284 return DateFormatSymbols::isNumericPatternChar(formatChar, count);
2285}
2286
2287UBool
2288SimpleDateFormat::isAtNumericField(const UnicodeString &pattern, int32_t patternOffset) {
2289 if (patternOffset >= pattern.length()) {
2290 // not at any field
2291 return false;
2292 }
2293 char16_t ch = pattern.charAt(patternOffset);
2294 UDateFormatField f = DateFormatSymbols::getPatternCharIndex(ch);
2295 if (f == UDAT_FIELD_COUNT) {
2296 // not at any field
2297 return false;
2298 }
2299 int32_t i = patternOffset;
2300 while (pattern.charAt(++i) == ch) {}
2301 return DateFormatSymbols::isNumericField(f, i - patternOffset);
2302}
2303
2304UBool
2305SimpleDateFormat::isAfterNonNumericField(const UnicodeString &pattern, int32_t patternOffset) {
2306 if (patternOffset <= 0) {
2307 // not after any field
2308 return false;
2309 }
2310 char16_t ch = pattern.charAt(--patternOffset);
2311 UDateFormatField f = DateFormatSymbols::getPatternCharIndex(ch);
2312 if (f == UDAT_FIELD_COUNT) {
2313 // not after any field
2314 return false;
2315 }
2316 int32_t i = patternOffset;
2317 while (pattern.charAt(--i) == ch) {}
2318 return !DateFormatSymbols::isNumericField(f, patternOffset - i);
2319}
2320
2321void
2322SimpleDateFormat::parse(const UnicodeString& text, Calendar& cal, ParsePosition& parsePos) const
2323{
2324 UErrorCode status = U_ZERO_ERROR;
2325 int32_t pos = parsePos.getIndex();
2326 if(parsePos.getIndex() < 0) {
2327 parsePos.setErrorIndex(0);
2328 return;
2329 }
2330 int32_t start = pos;
2331
2332 // Hold the day period until everything else is parsed, because we need
2333 // the hour to interpret time correctly.
2334 int32_t dayPeriodInt = -1;
2335
2336 UBool ambiguousYear[] = { false };
2337 int32_t saveHebrewMonth = -1;
2338 int32_t count = 0;
2339 UTimeZoneFormatTimeType tzTimeType = UTZFMT_TIME_TYPE_UNKNOWN;
2340
2341 // For parsing abutting numeric fields. 'abutPat' is the
2342 // offset into 'pattern' of the first of 2 or more abutting
2343 // numeric fields. 'abutStart' is the offset into 'text'
2344 // where parsing the fields begins. 'abutPass' starts off as 0
2345 // and increments each time we try to parse the fields.
2346 int32_t abutPat = -1; // If >=0, we are in a run of abutting numeric fields
2347 int32_t abutStart = 0;
2348 int32_t abutPass = 0;
2349 UBool inQuote = false;
2350
2351 MessageFormat * numericLeapMonthFormatter = nullptr;
2352
2353 Calendar* calClone = nullptr;
2354 Calendar *workCal = &cal;
2355 if (&cal != fCalendar && typeid(cal) != typeid(*fCalendar)) {
2356 // Different calendar type
2357 // We use the time/zone from the input calendar, but
2358 // do not use the input calendar for field calculation.
2359 calClone = fCalendar->clone();
2360 if (calClone != nullptr) {
2361 calClone->setTime(cal.getTime(status),status);
2362 if (U_FAILURE(status)) {
2363 goto ExitParse;
2364 }
2365 calClone->setTimeZone(cal.getTimeZone());
2366 workCal = calClone;
2367 } else {
2368 status = U_MEMORY_ALLOCATION_ERROR;
2369 goto ExitParse;
2370 }
2371 }
2372
2373 if (fSymbols->fLeapMonthPatterns != nullptr && fSymbols->fLeapMonthPatternsCount >= DateFormatSymbols::kMonthPatternsCount) {
2374 numericLeapMonthFormatter = new MessageFormat(fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternNumeric], fLocale, status);
2375 if (numericLeapMonthFormatter == nullptr) {
2376 status = U_MEMORY_ALLOCATION_ERROR;
2377 goto ExitParse;
2378 } else if (U_FAILURE(status)) {
2379 goto ExitParse; // this will delete numericLeapMonthFormatter
2380 }
2381 }
2382
2383 for (int32_t i=0; i<fPattern.length(); ++i) {
2384 char16_t ch = fPattern.charAt(i);
2385
2386 // Handle alphabetic field characters.
2387 if (!inQuote && isSyntaxChar(ch)) {
2388 int32_t fieldPat = i;
2389
2390 // Count the length of this field specifier
2391 count = 1;
2392 while ((i+1)<fPattern.length() &&
2393 fPattern.charAt(i+1) == ch) {
2394 ++count;
2395 ++i;
2396 }
2397
2398 if (isNumeric(ch, count)) {
2399 if (abutPat < 0) {
2400 // Determine if there is an abutting numeric field.
2401 // Record the start of a set of abutting numeric fields.
2402 if (isAtNumericField(fPattern, i + 1)) {
2403 abutPat = fieldPat;
2404 abutStart = pos;
2405 abutPass = 0;
2406 }
2407 }
2408 } else {
2409 abutPat = -1; // End of any abutting fields
2410 }
2411
2412 // Handle fields within a run of abutting numeric fields. Take
2413 // the pattern "HHmmss" as an example. We will try to parse
2414 // 2/2/2 characters of the input text, then if that fails,
2415 // 1/2/2. We only adjust the width of the leftmost field; the
2416 // others remain fixed. This allows "123456" => 12:34:56, but
2417 // "12345" => 1:23:45. Likewise, for the pattern "yyyyMMdd" we
2418 // try 4/2/2, 3/2/2, 2/2/2, and finally 1/2/2.
2419 if (abutPat >= 0) {
2420 // If we are at the start of a run of abutting fields, then
2421 // shorten this field in each pass. If we can't shorten
2422 // this field any more, then the parse of this set of
2423 // abutting numeric fields has failed.
2424 if (fieldPat == abutPat) {
2425 count -= abutPass++;
2426 if (count == 0) {
2427 status = U_PARSE_ERROR;
2428 goto ExitParse;
2429 }
2430 }
2431
2432 pos = subParse(text, pos, ch, count,
2433 true, false, ambiguousYear, saveHebrewMonth, *workCal, i, numericLeapMonthFormatter, &tzTimeType);
2434
2435 // If the parse fails anywhere in the run, back up to the
2436 // start of the run and retry.
2437 if (pos < 0) {
2438 i = abutPat - 1;
2439 pos = abutStart;
2440 continue;
2441 }
2442 }
2443
2444 // Handle non-numeric fields and non-abutting numeric
2445 // fields.
2446 else if (ch != 0x6C) { // pattern char 'l' (SMALL LETTER L) just gets ignored
2447 int32_t s = subParse(text, pos, ch, count,
2448 false, true, ambiguousYear, saveHebrewMonth, *workCal, i, numericLeapMonthFormatter, &tzTimeType, &dayPeriodInt);
2449
2450 if (s == -pos-1) {
2451 // era not present, in special cases allow this to continue
2452 // from the position where the era was expected
2453 s = pos;
2454
2455 if (i+1 < fPattern.length()) {
2456 // move to next pattern character
2457 char16_t c = fPattern.charAt(i+1);
2458
2459 // check for whitespace
2460 if (PatternProps::isWhiteSpace(c)) {
2461 i++;
2462 // Advance over run in pattern
2463 while ((i+1)<fPattern.length() &&
2464 PatternProps::isWhiteSpace(fPattern.charAt(i+1))) {
2465 ++i;
2466 }
2467 }
2468 }
2469 }
2470 else if (s <= 0) {
2471 status = U_PARSE_ERROR;
2472 goto ExitParse;
2473 }
2474 pos = s;
2475 }
2476 }
2477
2478 // Handle literal pattern characters. These are any
2479 // quoted characters and non-alphabetic unquoted
2480 // characters.
2481 else {
2482
2483 abutPat = -1; // End of any abutting fields
2484
2485 if (! matchLiterals(fPattern, i, text, pos, getBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, status), getBooleanAttribute(UDAT_PARSE_PARTIAL_LITERAL_MATCH, status), isLenient())) {
2486 status = U_PARSE_ERROR;
2487 goto ExitParse;
2488 }
2489 }
2490 }
2491
2492 // Special hack for trailing "." after non-numeric field.
2493 if (text.charAt(pos) == 0x2e && getBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, status)) {
2494 // only do if the last field is not numeric
2495 if (isAfterNonNumericField(fPattern, fPattern.length())) {
2496 pos++; // skip the extra "."
2497 }
2498 }
2499
2500 // If dayPeriod is set, use it in conjunction with hour-of-day to determine am/pm.
2501 if (dayPeriodInt >= 0) {
2502 DayPeriodRules::DayPeriod dayPeriod = static_cast<DayPeriodRules::DayPeriod>(dayPeriodInt);
2503 const DayPeriodRules *ruleSet = DayPeriodRules::getInstance(this->getSmpFmtLocale(), status);
2504
2505 if (!cal.isSet(UCAL_HOUR) && !cal.isSet(UCAL_HOUR_OF_DAY)) {
2506 // If hour is not set, set time to the midpoint of current day period, overwriting
2507 // minutes if it's set.
2508 double midPoint = ruleSet->getMidPointForDayPeriod(dayPeriod, status);
2509
2510 // If we can't get midPoint we do nothing.
2511 if (U_SUCCESS(status)) {
2512 // Truncate midPoint toward zero to get the hour.
2513 // Any leftover means it was a half-hour.
2514 int32_t midPointHour = static_cast<int32_t>(midPoint);
2515 int32_t midPointMinute = (midPoint - midPointHour) > 0 ? 30 : 0;
2516
2517 // No need to set am/pm because hour-of-day is set last therefore takes precedence.
2518 cal.set(UCAL_HOUR_OF_DAY, midPointHour);
2519 cal.set(UCAL_MINUTE, midPointMinute);
2520 }
2521 } else {
2522 int hourOfDay;
2523
2524 if (cal.isSet(UCAL_HOUR_OF_DAY)) { // Hour is parsed in 24-hour format.
2525 hourOfDay = cal.get(UCAL_HOUR_OF_DAY, status);
2526 } else { // Hour is parsed in 12-hour format.
2527 hourOfDay = cal.get(UCAL_HOUR, status);
2528 // cal.get() turns 12 to 0 for 12-hour time; change 0 to 12
2529 // so 0 unambiguously means a 24-hour time from above.
2530 if (hourOfDay == 0) { hourOfDay = 12; }
2531 }
2532 U_ASSERT(0 <= hourOfDay && hourOfDay <= 23)(static_cast <bool> (0 <= hourOfDay && hourOfDay
<= 23) ? void (0) : __assert_fail ("0 <= hourOfDay && hourOfDay <= 23"
, __builtin_FILE (), __builtin_LINE (), __extension__ __PRETTY_FUNCTION__
))
;
2533
2534
2535 // If hour-of-day is 0 or 13 thru 23 then input time in unambiguously in 24-hour format.
2536 if (hourOfDay == 0 || (13 <= hourOfDay && hourOfDay <= 23)) {
2537 // Make hour-of-day take precedence over (hour + am/pm) by setting it again.
2538 cal.set(UCAL_HOUR_OF_DAY, hourOfDay);
2539 } else {
2540 // We have a 12-hour time and need to choose between am and pm.
2541 // Behave as if dayPeriod spanned 6 hours each way from its center point.
2542 // This will parse correctly for consistent time + period (e.g. 10 at night) as
2543 // well as provide a reasonable recovery for inconsistent time + period (e.g.
2544 // 9 in the afternoon).
2545
2546 // Assume current time is in the AM.
2547 // - Change 12 back to 0 for easier handling of 12am.
2548 // - Append minutes as fractional hours because e.g. 8:15 and 8:45 could be parsed
2549 // into different half-days if center of dayPeriod is at 14:30.
2550 // - cal.get(MINUTE) will return 0 if MINUTE is unset, which works.
2551 if (hourOfDay == 12) { hourOfDay = 0; }
2552 double currentHour = hourOfDay + (cal.get(UCAL_MINUTE, status)) / 60.0;
2553 double midPointHour = ruleSet->getMidPointForDayPeriod(dayPeriod, status);
2554
2555 if (U_SUCCESS(status)) {
2556 double hoursAheadMidPoint = currentHour - midPointHour;
2557
2558 // Assume current time is in the AM.
2559 if (-6 <= hoursAheadMidPoint && hoursAheadMidPoint < 6) {
2560 // Assumption holds; set time as such.
2561 cal.set(UCAL_AM_PM, 0);
2562 } else {
2563 cal.set(UCAL_AM_PM, 1);
2564 }
2565 }
2566 }
2567 }
2568 }
2569
2570 // At this point the fields of Calendar have been set. Calendar
2571 // will fill in default values for missing fields when the time
2572 // is computed.
2573
2574 parsePos.setIndex(pos);
2575
2576 // This part is a problem: When we call parsedDate.after, we compute the time.
2577 // Take the date April 3 2004 at 2:30 am. When this is first set up, the year
2578 // will be wrong if we're parsing a 2-digit year pattern. It will be 1904.
2579 // April 3 1904 is a Sunday (unlike 2004) so it is the DST onset day. 2:30 am
2580 // is therefore an "impossible" time, since the time goes from 1:59 to 3:00 am
2581 // on that day. It is therefore parsed out to fields as 3:30 am. Then we
2582 // add 100 years, and get April 3 2004 at 3:30 am. Note that April 3 2004 is
2583 // a Saturday, so it can have a 2:30 am -- and it should. [LIU]
2584 /*
2585 UDate parsedDate = calendar.getTime();
2586 if( ambiguousYear[0] && !parsedDate.after(fDefaultCenturyStart) ) {
2587 calendar.add(Calendar.YEAR, 100);
2588 parsedDate = calendar.getTime();
2589 }
2590 */
2591 // Because of the above condition, save off the fields in case we need to readjust.
2592 // The procedure we use here is not particularly efficient, but there is no other
2593 // way to do this given the API restrictions present in Calendar. We minimize
2594 // inefficiency by only performing this computation when it might apply, that is,
2595 // when the two-digit year is equal to the start year, and thus might fall at the
2596 // front or the back of the default century. This only works because we adjust
2597 // the year correctly to start with in other cases -- see subParse().
2598 if (ambiguousYear[0] || tzTimeType != UTZFMT_TIME_TYPE_UNKNOWN) // If this is true then the two-digit year == the default start year
2599 {
2600 // We need a copy of the fields, and we need to avoid triggering a call to
2601 // complete(), which will recalculate the fields. Since we can't access
2602 // the fields[] array in Calendar, we clone the entire object. This will
2603 // stop working if Calendar.clone() is ever rewritten to call complete().
2604 Calendar *copy;
2605 if (ambiguousYear[0]) {
2606 copy = cal.clone();
2607 // Check for failed cloning.
2608 if (copy == nullptr) {
2609 status = U_MEMORY_ALLOCATION_ERROR;
2610 goto ExitParse;
2611 }
2612 UDate parsedDate = copy->getTime(status);
2613 // {sfb} check internalGetDefaultCenturyStart
2614 if (fHaveDefaultCentury && (parsedDate < fDefaultCenturyStart)) {
2615 // We can't use add here because that does a complete() first.
2616 cal.set(UCAL_YEAR, fDefaultCenturyStartYear + 100);
2617 }
2618 delete copy;
2619 }
2620
2621 if (tzTimeType != UTZFMT_TIME_TYPE_UNKNOWN) {
2622 copy = cal.clone();
2623 // Check for failed cloning.
2624 if (copy == nullptr) {
2625 status = U_MEMORY_ALLOCATION_ERROR;
2626 goto ExitParse;
2627 }
2628 const TimeZone & tz = cal.getTimeZone();
2629 BasicTimeZone *btz = nullptr;
2630
2631 if (dynamic_cast<const OlsonTimeZone *>(&tz) != nullptr
2632 || dynamic_cast<const SimpleTimeZone *>(&tz) != nullptr
2633 || dynamic_cast<const RuleBasedTimeZone *>(&tz) != nullptr
2634 || dynamic_cast<const VTimeZone *>(&tz) != nullptr) {
2635 btz = (BasicTimeZone*)&tz;
2636 }
2637
2638 // Get local millis
2639 copy->set(UCAL_ZONE_OFFSET, 0);
2640 copy->set(UCAL_DST_OFFSET, 0);
2641 UDate localMillis = copy->getTime(status);
2642
2643 // Make sure parsed time zone type (Standard or Daylight)
2644 // matches the rule used by the parsed time zone.
2645 int32_t raw, dst;
2646 if (btz != nullptr) {
2647 if (tzTimeType == UTZFMT_TIME_TYPE_STANDARD) {
2648 btz->getOffsetFromLocal(localMillis,
2649 UCAL_TZ_LOCAL_STANDARD_FORMER, UCAL_TZ_LOCAL_STANDARD_LATTER, raw, dst, status);
2650 } else {
2651 btz->getOffsetFromLocal(localMillis,
2652 UCAL_TZ_LOCAL_DAYLIGHT_FORMER, UCAL_TZ_LOCAL_DAYLIGHT_LATTER, raw, dst, status);
2653 }
2654 } else {
2655 // No good way to resolve ambiguous time at transition,
2656 // but following code work in most case.
2657 tz.getOffset(localMillis, true, raw, dst, status);
2658 }
2659
2660 // Now, compare the results with parsed type, either standard or daylight saving time
2661 int32_t resolvedSavings = dst;
2662 if (tzTimeType == UTZFMT_TIME_TYPE_STANDARD) {
2663 if (dst != 0) {
2664 // Override DST_OFFSET = 0 in the result calendar
2665 resolvedSavings = 0;
2666 }
2667 } else { // tztype == TZTYPE_DST
2668 if (dst == 0) {
2669 if (btz != nullptr) {
2670 // This implementation resolves daylight saving time offset
2671 // closest rule after the given time.
2672 UDate baseTime = localMillis + raw;
2673 UDate time = baseTime;
2674 UDate limit = baseTime + MAX_DAYLIGHT_DETECTION_RANGE;
2675 TimeZoneTransition trs;
2676 UBool trsAvail;
2677
2678 // Search for DST rule after the given time
2679 while (time < limit) {
2680 trsAvail = btz->getNextTransition(time, false, trs);
2681 if (!trsAvail) {
2682 break;
2683 }
2684 resolvedSavings = trs.getTo()->getDSTSavings();
2685 if (resolvedSavings != 0) {
2686 break;
2687 }
2688 time = trs.getTime();
2689 }
2690
2691 if (resolvedSavings == 0) {
2692 // If no DST rule after the given time was found, search for
2693 // DST rule before.
2694 time = baseTime;
2695 limit = baseTime - MAX_DAYLIGHT_DETECTION_RANGE;
2696 while (time > limit) {
2697 trsAvail = btz->getPreviousTransition(time, true, trs);
2698 if (!trsAvail) {
2699 break;
2700 }
2701 resolvedSavings = trs.getFrom()->getDSTSavings();
2702 if (resolvedSavings != 0) {
2703 break;
2704 }
2705 time = trs.getTime() - 1;
2706 }
2707
2708 if (resolvedSavings == 0) {
2709 resolvedSavings = btz->getDSTSavings();
2710 }
2711 }
2712 } else {
2713 resolvedSavings = tz.getDSTSavings();
2714 }
2715 if (resolvedSavings == 0) {
2716 // final fallback
2717 resolvedSavings = U_MILLIS_PER_HOUR(3600000);
2718 }
2719 }
2720 }
2721 cal.set(UCAL_ZONE_OFFSET, raw);
2722 cal.set(UCAL_DST_OFFSET, resolvedSavings);
2723 delete copy;
2724 }
2725 }
2726ExitParse:
2727 // Set the parsed result if local calendar is used
2728 // instead of the input calendar
2729 if (U_SUCCESS(status) && workCal != &cal) {
2730 cal.setTimeZone(workCal->getTimeZone());
2731 cal.setTime(workCal->getTime(status), status);
2732 }
2733
2734 delete numericLeapMonthFormatter;
2735 delete calClone;
2736
2737 // If any Calendar calls failed, we pretend that we
2738 // couldn't parse the string, when in reality this isn't quite accurate--
2739 // we did parse it; the Calendar calls just failed.
2740 if (U_FAILURE(status)) {
2741 parsePos.setErrorIndex(pos);
2742 parsePos.setIndex(start);
2743 }
2744}
2745
2746//----------------------------------------------------------------------
2747
2748static int32_t
2749matchStringWithOptionalDot(const UnicodeString &text,
2750 int32_t index,
2751 const UnicodeString &data);
2752
2753int32_t SimpleDateFormat::matchQuarterString(const UnicodeString& text,
2754 int32_t start,
2755 UCalendarDateFields field,
2756 const UnicodeString* data,
2757 int32_t dataCount,
2758 Calendar& cal) const
2759{
2760 int32_t i = 0;
2761 int32_t count = dataCount;
2762
2763 // There may be multiple strings in the data[] array which begin with
2764 // the same prefix (e.g., Cerven and Cervenec (June and July) in Czech).
2765 // We keep track of the longest match, and return that. Note that this
2766 // unfortunately requires us to test all array elements.
2767 int32_t bestMatchLength = 0, bestMatch = -1;
2768 UnicodeString bestMatchName;
2769
2770 for (; i < count; ++i) {
2771 int32_t matchLength = 0;
2772 if ((matchLength = matchStringWithOptionalDot(text, start, data[i])) > bestMatchLength) {
2773 bestMatchLength = matchLength;
2774 bestMatch = i;
2775 }
2776 }
2777
2778 if (bestMatch >= 0) {
2779 cal.set(field, bestMatch * 3);
2780 return start + bestMatchLength;
2781 }
2782
2783 return -start;
2784}
2785
2786int32_t SimpleDateFormat::matchDayPeriodStrings(const UnicodeString& text, int32_t start,
2787 const UnicodeString* data, int32_t dataCount,
2788 int32_t &dayPeriod) const
2789{
2790
2791 int32_t bestMatchLength = 0, bestMatch = -1;
2792
2793 for (int32_t i = 0; i < dataCount; ++i) {
2794 int32_t matchLength = 0;
2795 if ((matchLength = matchStringWithOptionalDot(text, start, data[i])) > bestMatchLength) {
2796 bestMatchLength = matchLength;
2797 bestMatch = i;
2798 }
2799 }
2800
2801 if (bestMatch >= 0) {
2802 dayPeriod = bestMatch;
2803 return start + bestMatchLength;
2804 }
2805
2806 return -start;
2807}
2808
2809//----------------------------------------------------------------------
2810UBool SimpleDateFormat::matchLiterals(const UnicodeString &pattern,
2811 int32_t &patternOffset,
2812 const UnicodeString &text,
2813 int32_t &textOffset,
2814 UBool whitespaceLenient,
2815 UBool partialMatchLenient,
2816 UBool oldLeniency)
2817{
2818 UBool inQuote = false;
2819 UnicodeString literal;
2820 int32_t i = patternOffset;
2821
2822 // scan pattern looking for contiguous literal characters
2823 for ( ; i < pattern.length(); i += 1) {
2824 char16_t ch = pattern.charAt(i);
2825
2826 if (!inQuote && isSyntaxChar(ch)) {
2827 break;
2828 }
2829
2830 if (ch == QUOTE) {
2831 // Match a quote literal ('') inside OR outside of quotes
2832 if ((i + 1) < pattern.length() && pattern.charAt(i + 1) == QUOTE) {
2833 i += 1;
2834 } else {
2835 inQuote = !inQuote;
2836 continue;
2837 }
2838 }
2839
2840 literal += ch;
2841 }
2842
2843 // at this point, literal contains the literal text
2844 // and i is the index of the next non-literal pattern character.
2845 int32_t p;
2846 int32_t t = textOffset;
2847
2848 if (whitespaceLenient) {
2849 // trim leading, trailing whitespace from
2850 // the literal text
2851 literal.trim();
2852
2853 // ignore any leading whitespace in the text
2854 while (t < text.length() && u_isWhitespace(text.charAt(t))) {
2855 t += 1;
2856 }
2857 }
2858
2859 for (p = 0; p < literal.length() && t < text.length();) {
2860 UBool needWhitespace = false;
2861
2862 while (p < literal.length() && PatternProps::isWhiteSpace(literal.charAt(p))) {
2863 needWhitespace = true;
2864 p += 1;
2865 }
2866
2867 if (needWhitespace) {
2868 int32_t tStart = t;
2869
2870 while (t < text.length()) {
2871 char16_t tch = text.charAt(t);
2872
2873 if (!u_isUWhiteSpace(tch) && !PatternProps::isWhiteSpace(tch)) {
2874 break;
2875 }
2876
2877 t += 1;
2878 }
2879
2880 // TODO: should we require internal spaces
2881 // in lenient mode? (There won't be any
2882 // leading or trailing spaces)
2883 if (!whitespaceLenient && t == tStart) {
2884 // didn't find matching whitespace:
2885 // an error in strict mode
2886 return false;
2887 }
2888
2889 // In strict mode, this run of whitespace
2890 // may have been at the end.
2891 if (p >= literal.length()) {
2892 break;
2893 }
2894 }
2895 if (t >= text.length() || literal.charAt(p) != text.charAt(t)) {
2896 // Ran out of text, or found a non-matching character:
2897 // OK in lenient mode, an error in strict mode.
2898 if (whitespaceLenient) {
2899 if (t == textOffset && text.charAt(t) == 0x2e &&
2900 isAfterNonNumericField(pattern, patternOffset)) {
2901 // Lenient mode and the literal input text begins with a "." and
2902 // we are after a non-numeric field: We skip the "."
2903 ++t;
2904 continue; // Do not update p.
2905 }
2906 // if it is actual whitespace and we're whitespace lenient it's OK
2907
2908 char16_t wsc = text.charAt(t);
2909 if(PatternProps::isWhiteSpace(wsc)) {
2910 // Lenient mode and it's just whitespace we skip it
2911 ++t;
2912 continue; // Do not update p.
2913 }
2914 }
2915 // hack around oldleniency being a bit of a catch-all bucket and we're just adding support specifically for partial matches
2916 if(partialMatchLenient && oldLeniency) {
2917 break;
2918 }
2919
2920 return false;
2921 }
2922 ++p;
2923 ++t;
2924 }
2925
2926 // At this point if we're in strict mode we have a complete match.
2927 // If we're in lenient mode we may have a partial match, or no
2928 // match at all.
2929 if (p <= 0) {
2930 // no match. Pretend it matched a run of whitespace
2931 // and ignorables in the text.
2932 const UnicodeSet *ignorables = nullptr;
2933 UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(pattern.charAt(i));
2934 if (patternCharIndex != UDAT_FIELD_COUNT) {
2935 ignorables = SimpleDateFormatStaticSets::getIgnorables(patternCharIndex);
2936 }
2937
2938 for (t = textOffset; t < text.length(); t += 1) {
2939 char16_t ch = text.charAt(t);
2940
2941 if (ignorables == nullptr || !ignorables->contains(ch)) {
2942 break;
2943 }
2944 }
2945 }
2946
2947 // if we get here, we've got a complete match.
2948 patternOffset = i - 1;
2949 textOffset = t;
2950
2951 return true;
2952}
2953
2954//----------------------------------------------------------------------
2955// check both wide and abbrev months.
2956// Does not currently handle monthPattern.
2957// UCalendarDateFields field = UCAL_MONTH
2958
2959int32_t SimpleDateFormat::matchAlphaMonthStrings(const UnicodeString& text,
2960 int32_t start,
2961 const UnicodeString* wideData,
2962 const UnicodeString* shortData,
2963 int32_t dataCount,
2964 Calendar& cal) const
2965{
2966 int32_t i;
2967 int32_t bestMatchLength = 0, bestMatch = -1;
2968
2969 for (i = 0; i < dataCount; ++i) {
2970 int32_t matchLen = 0;
2971 if ((matchLen = matchStringWithOptionalDot(text, start, wideData[i])) > bestMatchLength) {
2972 bestMatch = i;
2973 bestMatchLength = matchLen;
2974 }
2975 }
2976 for (i = 0; i < dataCount; ++i) {
2977 int32_t matchLen = 0;
2978 if ((matchLen = matchStringWithOptionalDot(text, start, shortData[i])) > bestMatchLength) {
2979 bestMatch = i;
2980 bestMatchLength = matchLen;
2981 }
2982 }
2983
2984 if (bestMatch >= 0) {
2985 // Adjustment for Hebrew Calendar month Adar II
2986 if (typeid(cal) == typeid(HebrewCalendar) && bestMatch==13) {
2987 cal.set(UCAL_MONTH,6);
2988 } else {
2989 cal.set(UCAL_MONTH, bestMatch);
2990 }
2991 return start + bestMatchLength;
2992 }
2993
2994 return -start;
2995}
2996
2997//----------------------------------------------------------------------
2998
2999int32_t SimpleDateFormat::matchString(const UnicodeString& text,
3000 int32_t start,
3001 UCalendarDateFields field,
3002 const UnicodeString* data,
3003 int32_t dataCount,
3004 const UnicodeString* monthPattern,
3005 Calendar& cal) const
3006{
3007 int32_t i = 0;
3008 int32_t count = dataCount;
3009
3010 if (field == UCAL_DAY_OF_WEEK) i = 1;
3011
3012 // There may be multiple strings in the data[] array which begin with
3013 // the same prefix (e.g., Cerven and Cervenec (June and July) in Czech).
3014 // We keep track of the longest match, and return that. Note that this
3015 // unfortunately requires us to test all array elements.
3016 // But this does not really work for cases such as Chuvash in which
3017 // May is "ҫу" and August is "ҫурла"/"ҫур.", hence matchAlphaMonthStrings.
3018 int32_t bestMatchLength = 0, bestMatch = -1;
3019 UnicodeString bestMatchName;
3020 int32_t isLeapMonth = 0;
3021
3022 for (; i < count; ++i) {
3023 int32_t matchLen = 0;
3024 if ((matchLen = matchStringWithOptionalDot(text, start, data[i])) > bestMatchLength) {
3025 bestMatch = i;
3026 bestMatchLength = matchLen;
3027 }
3028
3029 if (monthPattern != nullptr) {
3030 UErrorCode status = U_ZERO_ERROR;
3031 UnicodeString leapMonthName;
3032 SimpleFormatter(*monthPattern, 1, 1, status).format(data[i], leapMonthName, status);
3033 if (U_SUCCESS(status)) {
3034 if ((matchLen = matchStringWithOptionalDot(text, start, leapMonthName)) > bestMatchLength) {
3035 bestMatch = i;
3036 bestMatchLength = matchLen;
3037 isLeapMonth = 1;
3038 }
3039 }
3040 }
3041 }
3042
3043 if (bestMatch >= 0) {
3044 if (field < UCAL_FIELD_COUNT) {
3045 // Adjustment for Hebrew Calendar month Adar II
3046 if (typeid(cal) == typeid(HebrewCalendar) && field==UCAL_MONTH && bestMatch==13) {
3047 cal.set(field,6);
3048 } else {
3049 if (field == UCAL_YEAR) {
3050 bestMatch++; // only get here for cyclic year names, which match 1-based years 1-60
3051 }
3052 cal.set(field, bestMatch);
3053 }
3054 if (monthPattern != nullptr) {
3055 cal.set(UCAL_IS_LEAP_MONTH, isLeapMonth);
3056 }
3057 }
3058
3059 return start + bestMatchLength;
3060 }
3061
3062 return -start;
3063}
3064
3065static int32_t
3066matchStringWithOptionalDot(const UnicodeString &text,
3067 int32_t index,
3068 const UnicodeString &data) {
3069 UErrorCode sts = U_ZERO_ERROR;
3070 int32_t matchLenText = 0;
3071 int32_t matchLenData = 0;
3072
3073 u_caseInsensitivePrefixMatch(text.getBuffer() + index, text.length() - index,
3074 data.getBuffer(), data.length(),
3075 0 /* default case option */,
3076 &matchLenText, &matchLenData,
3077 &sts);
3078 U_ASSERT (U_SUCCESS(sts))(static_cast <bool> (U_SUCCESS(sts)) ? void (0) : __assert_fail
("U_SUCCESS(sts)", __builtin_FILE (), __builtin_LINE (), __extension__
__PRETTY_FUNCTION__))
;
3079
3080 if (matchLenData == data.length() /* normal match */
3081 || (data.charAt(data.length() - 1) == 0x2e
3082 && matchLenData == data.length() - 1 /* match without trailing dot */)) {
3083 return matchLenText;
3084 }
3085
3086 return 0;
3087}
3088
3089//----------------------------------------------------------------------
3090
3091void
3092SimpleDateFormat::set2DigitYearStart(UDate d, UErrorCode& status)
3093{
3094 parseAmbiguousDatesAsAfter(d, status);
3095}
3096
3097/**
3098 * Private member function that converts the parsed date strings into
3099 * timeFields. Returns -start (for ParsePosition) if failed.
3100 */
3101int32_t SimpleDateFormat::subParse(const UnicodeString& text, int32_t& start, char16_t ch, int32_t count,
3102 UBool obeyCount, UBool allowNegative, UBool ambiguousYear[], int32_t& saveHebrewMonth, Calendar& cal,
3103 int32_t patLoc, MessageFormat * numericLeapMonthFormatter, UTimeZoneFormatTimeType *tzTimeType,
3104 int32_t *dayPeriod) const
3105{
3106 Formattable number;
3107 int32_t value = 0;
3108 int32_t i;
3109 int32_t ps = 0;
3110 UErrorCode status = U_ZERO_ERROR;
3111 ParsePosition pos(0);
3112 UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(ch);
3113 const NumberFormat *currentNumberFormat;
3114 UnicodeString temp;
3115 UBool gotNumber = false;
3116
3117#if defined (U_DEBUG_CAL)
3118 //fprintf(stderr, "%s:%d - [%c] st=%d \n", __FILE__, __LINE__, (char) ch, start);
3119#endif
3120
3121 if (patternCharIndex == UDAT_FIELD_COUNT) {
3122 return -start;
3123 }
3124
3125 currentNumberFormat = getNumberFormatByIndex(patternCharIndex);
3126 if (currentNumberFormat == nullptr) {
3127 return -start;
3128 }
3129 UCalendarDateFields field = fgPatternIndexToCalendarField[patternCharIndex]; // UCAL_FIELD_COUNT if irrelevant
3130 UnicodeString hebr("hebr", 4, US_INVicu::UnicodeString::kInvariant);
3131
3132 if (numericLeapMonthFormatter != nullptr) {
3133 numericLeapMonthFormatter->setFormats(reinterpret_cast<const Format**>(&currentNumberFormat), 1);
3134 }
3135
3136 // If there are any spaces here, skip over them. If we hit the end
3137 // of the string, then fail.
3138 for (;;) {
3139 if (start >= text.length()) {
3140 return -start;
3141 }
3142 UChar32 c = text.char32At(start);
3143 if (!u_isUWhiteSpace(c) /*||*/ && !PatternProps::isWhiteSpace(c)) {
3144 break;
3145 }
3146 start += U16_LENGTH(c)((uint32_t)(c)<=0xffff ? 1 : 2);
3147 }
3148 pos.setIndex(start);
3149
3150 UBool isChineseCalendar = typeid(cal) == typeid(ChineseCalendar) ||
3151 typeid(cal) == typeid(DangiCalendar);
3152 // We handle a few special cases here where we need to parse
3153 // a number value. We handle further, more generic cases below. We need
3154 // to handle some of them here because some fields require extra processing on
3155 // the parsed value.
3156 if (patternCharIndex == UDAT_HOUR_OF_DAY1_FIELD || // k
3157 patternCharIndex == UDAT_HOUR_OF_DAY0_FIELD || // H
3158 patternCharIndex == UDAT_HOUR1_FIELD || // h
3159 patternCharIndex == UDAT_HOUR0_FIELD || // K
3160 (patternCharIndex == UDAT_DOW_LOCAL_FIELD && count <= 2) || // e
3161 (patternCharIndex == UDAT_STANDALONE_DAY_FIELD && count <= 2) || // c
3162 (patternCharIndex == UDAT_MONTH_FIELD && count <= 2) || // M
3163 (patternCharIndex == UDAT_STANDALONE_MONTH_FIELD && count <= 2) || // L
3164 (patternCharIndex == UDAT_QUARTER_FIELD && count <= 2) || // Q
3165 (patternCharIndex == UDAT_STANDALONE_QUARTER_FIELD && count <= 2) || // q
3166 patternCharIndex == UDAT_YEAR_FIELD || // y
3167 patternCharIndex == UDAT_YEAR_WOY_FIELD || // Y
3168 patternCharIndex == UDAT_YEAR_NAME_FIELD || // U (falls back to numeric)
3169 (patternCharIndex == UDAT_ERA_FIELD && isChineseCalendar) || // G
3170 patternCharIndex == UDAT_FRACTIONAL_SECOND_FIELD) // S
3171 {
3172 int32_t parseStart = pos.getIndex();
3173 // It would be good to unify this with the obeyCount logic below,
3174 // but that's going to be difficult.
3175 const UnicodeString* src;
3176
3177 UBool parsedNumericLeapMonth = false;
3178 if (numericLeapMonthFormatter != nullptr && (patternCharIndex == UDAT_MONTH_FIELD || patternCharIndex == UDAT_STANDALONE_MONTH_FIELD)) {
3179 int32_t argCount;
3180 Formattable * args = numericLeapMonthFormatter->parse(text, pos, argCount);
3181 if (args != nullptr && argCount == 1 && pos.getIndex() > parseStart && args[0].isNumeric()) {
3182 parsedNumericLeapMonth = true;
3183 number.setLong(args[0].getLong());
3184 cal.set(UCAL_IS_LEAP_MONTH, 1);
3185 delete[] args;
3186 } else {
3187 pos.setIndex(parseStart);
3188 cal.set(UCAL_IS_LEAP_MONTH, 0);
3189 }
3190 }
3191
3192 if (!parsedNumericLeapMonth) {
3193 if (obeyCount) {
3194 if ((start+count) > text.length()) {
3195 return -start;
3196 }
3197
3198 text.extractBetween(0, start + count, temp);
3199 src = &temp;
3200 } else {
3201 src = &text;
3202 }
3203
3204 parseInt(*src, number, pos, allowNegative,currentNumberFormat);
3205 }
3206
3207 int32_t txtLoc = pos.getIndex();
3208
3209 if (txtLoc > parseStart) {
3210 value = number.getLong();
3211 gotNumber = true;
3212
3213 // suffix processing
3214 if (value < 0 ) {
3215 txtLoc = checkIntSuffix(text, txtLoc, patLoc+1, true);
3216 if (txtLoc != pos.getIndex()) {
3217 value *= -1;
3218 }
3219 }
3220 else {
3221 txtLoc = checkIntSuffix(text, txtLoc, patLoc+1, false);
3222 }
3223
3224 if (!getBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, status)) {
3225 // Check the range of the value
3226 int32_t bias = gFieldRangeBias[patternCharIndex];
3227 if (bias >= 0 && (value > cal.getMaximum(field) + bias || value < cal.getMinimum(field) + bias)) {
3228 return -start;
3229 }
3230 }
3231
3232 pos.setIndex(txtLoc);
3233 }
3234 }
3235
3236 // Make sure that we got a number if
3237 // we want one, and didn't get one
3238 // if we don't want one.
3239 switch (patternCharIndex) {
3240 case UDAT_HOUR_OF_DAY1_FIELD:
3241 case UDAT_HOUR_OF_DAY0_FIELD:
3242 case UDAT_HOUR1_FIELD:
3243 case UDAT_HOUR0_FIELD:
3244 // special range check for hours:
3245 if (value < 0 || value > 24) {
3246 return -start;
3247 }
3248
3249 // fall through to gotNumber check
3250 U_FALLTHROUGH[[clang::fallthrough]];
3251 case UDAT_YEAR_FIELD:
3252 case UDAT_YEAR_WOY_FIELD:
3253 case UDAT_FRACTIONAL_SECOND_FIELD:
3254 // these must be a number
3255 if (! gotNumber) {
3256 return -start;
3257 }
3258
3259 break;
3260
3261 default:
3262 // we check the rest of the fields below.
3263 break;
3264 }
3265
3266 switch (patternCharIndex) {
3267 case UDAT_ERA_FIELD:
3268 if (isChineseCalendar) {
3269 if (!gotNumber) {
3270 return -start;
3271 }
3272 cal.set(UCAL_ERA, value);
3273 return pos.getIndex();
3274 }
3275 if (count == 5) {
3276 ps = matchString(text, start, UCAL_ERA, fSymbols->fNarrowEras, fSymbols->fNarrowErasCount, nullptr, cal);
3277 } else if (count == 4) {
3278 ps = matchString(text, start, UCAL_ERA, fSymbols->fEraNames, fSymbols->fEraNamesCount, nullptr, cal);
3279 } else {
3280 ps = matchString(text, start, UCAL_ERA, fSymbols->fEras, fSymbols->fErasCount, nullptr, cal);
3281 }
3282
3283 // check return position, if it equals -start, then matchString error
3284 // special case the return code so we don't necessarily fail out until we
3285 // verify no year information also
3286 if (ps == -start)
3287 ps--;
3288
3289 return ps;
3290
3291 case UDAT_YEAR_FIELD:
3292 // If there are 3 or more YEAR pattern characters, this indicates
3293 // that the year value is to be treated literally, without any
3294 // two-digit year adjustments (e.g., from "01" to 2001). Otherwise
3295 // we made adjustments to place the 2-digit year in the proper
3296 // century, for parsed strings from "00" to "99". Any other string
3297 // is treated literally: "2250", "-1", "1", "002".
3298 if (fDateOverride.compare(hebr)==0 && value < 1000) {
3299 value += HEBREW_CAL_CUR_MILLENIUM_START_YEAR;
3300 } else if (text.moveIndex32(start, 2) == pos.getIndex() && !isChineseCalendar
3301 && u_isdigit(text.char32At(start))
3302 && u_isdigit(text.char32At(text.moveIndex32(start, 1))))
3303 {
3304 // only adjust year for patterns less than 3.
3305 if(count < 3) {
3306 // Assume for example that the defaultCenturyStart is 6/18/1903.
3307 // This means that two-digit years will be forced into the range
3308 // 6/18/1903 to 6/17/2003. As a result, years 00, 01, and 02
3309 // correspond to 2000, 2001, and 2002. Years 04, 05, etc. correspond
3310 // to 1904, 1905, etc. If the year is 03, then it is 2003 if the
3311 // other fields specify a date before 6/18, or 1903 if they specify a
3312 // date afterwards. As a result, 03 is an ambiguous year. All other
3313 // two-digit years are unambiguous.
3314 if(fHaveDefaultCentury) { // check if this formatter even has a pivot year
3315 int32_t ambiguousTwoDigitYear = fDefaultCenturyStartYear % 100;
3316 ambiguousYear[0] = (value == ambiguousTwoDigitYear);
3317 value += (fDefaultCenturyStartYear/100)*100 +
3318 (value < ambiguousTwoDigitYear ? 100 : 0);
3319 }
3320 }
3321 }
3322 cal.set(UCAL_YEAR, value);
3323
3324 // Delayed checking for adjustment of Hebrew month numbers in non-leap years.
3325 if (saveHebrewMonth >= 0) {
3326 HebrewCalendar *hc = (HebrewCalendar*)&cal;
3327 if (!hc->isLeapYear(value) && saveHebrewMonth >= 6) {
3328 cal.set(UCAL_MONTH,saveHebrewMonth);
3329 } else {
3330 cal.set(UCAL_MONTH,saveHebrewMonth-1);
3331 }
3332 saveHebrewMonth = -1;
3333 }
3334 return pos.getIndex();
3335
3336 case UDAT_YEAR_WOY_FIELD:
3337 // Comment is the same as for UDAT_Year_FIELDs - look above
3338 if (fDateOverride.compare(hebr)==0 && value < 1000) {
3339 value += HEBREW_CAL_CUR_MILLENIUM_START_YEAR;
3340 } else if (text.moveIndex32(start, 2) == pos.getIndex()
3341 && u_isdigit(text.char32At(start))
3342 && u_isdigit(text.char32At(text.moveIndex32(start, 1)))
3343 && fHaveDefaultCentury )
3344 {
3345 int32_t ambiguousTwoDigitYear = fDefaultCenturyStartYear % 100;
3346 ambiguousYear[0] = (value == ambiguousTwoDigitYear);
3347 value += (fDefaultCenturyStartYear/100)*100 +
3348 (value < ambiguousTwoDigitYear ? 100 : 0);
3349 }
3350 cal.set(UCAL_YEAR_WOY, value);
3351 return pos.getIndex();
3352
3353 case UDAT_YEAR_NAME_FIELD:
3354 if (fSymbols->fShortYearNames != nullptr) {
3355 int32_t newStart = matchString(text, start, UCAL_YEAR, fSymbols->fShortYearNames, fSymbols->fShortYearNamesCount, nullptr, cal);
3356 if (newStart > 0) {
3357 return newStart;
3358 }
3359 }
3360 if (gotNumber && (getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC,status) || value > fSymbols->fShortYearNamesCount)) {
3361 cal.set(UCAL_YEAR, value);
3362 return pos.getIndex();
3363 }
3364 return -start;
3365
3366 case UDAT_MONTH_FIELD:
3367 case UDAT_STANDALONE_MONTH_FIELD:
3368 if (gotNumber) // i.e., M or MM.
3369 {
3370 // When parsing month numbers from the Hebrew Calendar, we might need to adjust the month depending on whether
3371 // 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
3372 // the year is parsed.
3373 if (typeid(cal) == typeid(HebrewCalendar)) {
3374 HebrewCalendar *hc = (HebrewCalendar*)&cal;
3375 if (cal.isSet(UCAL_YEAR)) {
3376 UErrorCode monthStatus = U_ZERO_ERROR;
3377 if (!hc->isLeapYear(hc->get(UCAL_YEAR, monthStatus)) && value >= 6) {
3378 cal.set(UCAL_MONTH, value);
3379 } else {
3380 cal.set(UCAL_MONTH, value - 1);
3381 }
3382 } else {
3383 saveHebrewMonth = value;
3384 }
3385 } else {
3386 // Don't want to parse the month if it is a string
3387 // while pattern uses numeric style: M/MM, L/LL
3388 // [We computed 'value' above.]
3389 cal.set(UCAL_MONTH, value - 1);
3390 }
3391 return pos.getIndex();
3392 } else {
3393 // count >= 3 // i.e., MMM/MMMM, LLL/LLLL
3394 // Want to be able to parse both short and long forms.
3395 // Try count == 4 first:
3396 UnicodeString * wideMonthPat = nullptr;
3397 UnicodeString * shortMonthPat = nullptr;
3398 if (fSymbols->fLeapMonthPatterns != nullptr && fSymbols->fLeapMonthPatternsCount >= DateFormatSymbols::kMonthPatternsCount) {
3399 if (patternCharIndex==UDAT_MONTH_FIELD) {
3400 wideMonthPat = &fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatWide];
3401 shortMonthPat = &fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternFormatAbbrev];
3402 } else {
3403 wideMonthPat = &fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneWide];
3404 shortMonthPat = &fSymbols->fLeapMonthPatterns[DateFormatSymbols::kLeapMonthPatternStandaloneAbbrev];
3405 }
3406 }
3407 int32_t newStart = 0;
3408 if (patternCharIndex==UDAT_MONTH_FIELD) {
3409 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) && count>=3 && count <=4 &&
3410 fSymbols->fLeapMonthPatterns==nullptr && fSymbols->fMonthsCount==fSymbols->fShortMonthsCount) {
3411 // single function to check both wide and short, an experiment
3412 newStart = matchAlphaMonthStrings(text, start, fSymbols->fMonths, fSymbols->fShortMonths, fSymbols->fMonthsCount, cal); // try MMMM,MMM
3413 if (newStart > 0) {
3414 return newStart;
3415 }
3416 }
3417 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3418 newStart = matchString(text, start, UCAL_MONTH, fSymbols->fMonths, fSymbols->fMonthsCount, wideMonthPat, cal); // try MMMM
3419 if (newStart > 0) {
3420 return newStart;
3421 }
3422 }
3423 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3424 newStart = matchString(text, start, UCAL_MONTH, fSymbols->fShortMonths, fSymbols->fShortMonthsCount, shortMonthPat, cal); // try MMM
3425 }
3426 } else {
3427 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) && count>=3 && count <=4 &&
3428 fSymbols->fLeapMonthPatterns==nullptr && fSymbols->fStandaloneMonthsCount==fSymbols->fStandaloneShortMonthsCount) {
3429 // single function to check both wide and short, an experiment
3430 newStart = matchAlphaMonthStrings(text, start, fSymbols->fStandaloneMonths, fSymbols->fStandaloneShortMonths, fSymbols->fStandaloneMonthsCount, cal); // try MMMM,MMM
3431 if (newStart > 0) {
3432 return newStart;
3433 }
3434 }
3435 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3436 newStart = matchString(text, start, UCAL_MONTH, fSymbols->fStandaloneMonths, fSymbols->fStandaloneMonthsCount, wideMonthPat, cal); // try LLLL
3437 if (newStart > 0) {
3438 return newStart;
3439 }
3440 }
3441 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3442 newStart = matchString(text, start, UCAL_MONTH, fSymbols->fStandaloneShortMonths, fSymbols->fStandaloneShortMonthsCount, shortMonthPat, cal); // try LLL
3443 }
3444 }
3445 if (newStart > 0 || !getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status)) // currently we do not try to parse MMMMM/LLLLL: #8860
3446 return newStart;
3447 // else we allowing parsing as number, below
3448 }
3449 break;
3450
3451 case UDAT_HOUR_OF_DAY1_FIELD:
3452 // [We computed 'value' above.]
3453 if (value == cal.getMaximum(UCAL_HOUR_OF_DAY) + 1)
3454 value = 0;
3455
3456 // fall through to set field
3457 U_FALLTHROUGH[[clang::fallthrough]];
3458 case UDAT_HOUR_OF_DAY0_FIELD:
3459 cal.set(UCAL_HOUR_OF_DAY, value);
3460 return pos.getIndex();
3461
3462 case UDAT_FRACTIONAL_SECOND_FIELD:
3463 // Fractional seconds left-justify
3464 i = countDigits(text, start, pos.getIndex());
3465 if (i < 3) {
3466 while (i < 3) {
3467 value *= 10;
3468 i++;
3469 }
3470 } else {
3471 int32_t a = 1;
3472 while (i > 3) {
3473 a *= 10;
3474 i--;
3475 }
3476 value /= a;
3477 }
3478 cal.set(UCAL_MILLISECOND, value);
3479 return pos.getIndex();
3480
3481 case UDAT_DOW_LOCAL_FIELD:
3482 if (gotNumber) // i.e., e or ee
3483 {
3484 // [We computed 'value' above.]
3485 cal.set(UCAL_DOW_LOCAL, value);
3486 return pos.getIndex();
3487 }
3488 // else for eee-eeeee fall through to handling of EEE-EEEEE
3489 // fall through, do not break here
3490 U_FALLTHROUGH[[clang::fallthrough]];
3491 case UDAT_DAY_OF_WEEK_FIELD:
3492 {
3493 // Want to be able to parse both short and long forms.
3494 // Try count == 4 (EEEE) wide first:
3495 int32_t newStart = 0;
3496 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3497 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3498 fSymbols->fWeekdays, fSymbols->fWeekdaysCount, nullptr, cal)) > 0)
3499 return newStart;
3500 }
3501 // EEEE wide failed, now try EEE abbreviated
3502 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3503 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3504 fSymbols->fShortWeekdays, fSymbols->fShortWeekdaysCount, nullptr, cal)) > 0)
3505 return newStart;
3506 }
3507 // EEE abbreviated failed, now try EEEEEE short
3508 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 6) {
3509 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3510 fSymbols->fShorterWeekdays, fSymbols->fShorterWeekdaysCount, nullptr, cal)) > 0)
3511 return newStart;
3512 }
3513 // EEEEEE short failed, now try EEEEE narrow
3514 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
3515 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3516 fSymbols->fNarrowWeekdays, fSymbols->fNarrowWeekdaysCount, nullptr, cal)) > 0)
3517 return newStart;
3518 }
3519 if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status) || patternCharIndex == UDAT_DAY_OF_WEEK_FIELD)
3520 return newStart;
3521 // else we allowing parsing as number, below
3522 }
3523 break;
3524
3525 case UDAT_STANDALONE_DAY_FIELD:
3526 {
3527 if (gotNumber) // c or cc
3528 {
3529 // [We computed 'value' above.]
3530 cal.set(UCAL_DOW_LOCAL, value);
3531 return pos.getIndex();
3532 }
3533 // Want to be able to parse both short and long forms.
3534 // Try count == 4 (cccc) first:
3535 int32_t newStart = 0;
3536 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3537 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3538 fSymbols->fStandaloneWeekdays, fSymbols->fStandaloneWeekdaysCount, nullptr, cal)) > 0)
3539 return newStart;
3540 }
3541 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3542 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3543 fSymbols->fStandaloneShortWeekdays, fSymbols->fStandaloneShortWeekdaysCount, nullptr, cal)) > 0)
3544 return newStart;
3545 }
3546 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 6) {
3547 if ((newStart = matchString(text, start, UCAL_DAY_OF_WEEK,
3548 fSymbols->fStandaloneShorterWeekdays, fSymbols->fStandaloneShorterWeekdaysCount, nullptr, cal)) > 0)
3549 return newStart;
3550 }
3551 if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status))
3552 return newStart;
3553 // else we allowing parsing as number, below
3554 }
3555 break;
3556
3557 case UDAT_AM_PM_FIELD:
3558 {
3559 // optionally try both wide/abbrev and narrow forms
3560 int32_t newStart = 0;
3561 // try wide
3562 if( getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4 ) {
3563 if ((newStart = matchString(text, start, UCAL_AM_PM, fSymbols->fWideAmPms, fSymbols->fWideAmPmsCount, nullptr, cal)) > 0) {
3564 return newStart;
3565 }
3566 }
3567 // try abbreviated
3568 if( getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count <= 3 ) {
3569 if ((newStart = matchString(text, start, UCAL_AM_PM, fSymbols->fAmPms, fSymbols->fAmPmsCount, nullptr, cal)) > 0) {
3570 return newStart;
3571 }
3572 }
3573 // try narrow
3574 if( getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count >= 5 ) {
3575 if ((newStart = matchString(text, start, UCAL_AM_PM, fSymbols->fNarrowAmPms, fSymbols->fNarrowAmPmsCount, nullptr, cal)) > 0) {
3576 return newStart;
3577 }
3578 }
3579 // no matches for given options
3580 return -start;
3581 }
3582
3583 case UDAT_HOUR1_FIELD:
3584 // [We computed 'value' above.]
3585 if (value == cal.getLeastMaximum(UCAL_HOUR)+1)
3586 value = 0;
3587
3588 // fall through to set field
3589 U_FALLTHROUGH[[clang::fallthrough]];
3590 case UDAT_HOUR0_FIELD:
3591 cal.set(UCAL_HOUR, value);
3592 return pos.getIndex();
3593
3594 case UDAT_QUARTER_FIELD:
3595 if (gotNumber) // i.e., Q or QQ.
3596 {
3597 // Don't want to parse the month if it is a string
3598 // while pattern uses numeric style: Q or QQ.
3599 // [We computed 'value' above.]
3600 cal.set(UCAL_MONTH, (value - 1) * 3);
3601 return pos.getIndex();
3602 } else {
3603 // count >= 3 // i.e., QQQ or QQQQ
3604 // Want to be able to parse short, long, and narrow forms.
3605 // Try count == 4 first:
3606 int32_t newStart = 0;
3607
3608 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3609 if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
3610 fSymbols->fQuarters, fSymbols->fQuartersCount, cal)) > 0)
3611 return newStart;
3612 }
3613 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3614 if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
3615 fSymbols->fShortQuarters, fSymbols->fShortQuartersCount, cal)) > 0)
3616 return newStart;
3617 }
3618 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
3619 if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
3620 fSymbols->fNarrowQuarters, fSymbols->fNarrowQuartersCount, cal)) > 0)
3621 return newStart;
3622 }
3623 if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status))
3624 return newStart;
3625 // else we allowing parsing as number, below
3626 if(!getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status))
3627 return -start;
3628 }
3629 break;
3630
3631 case UDAT_STANDALONE_QUARTER_FIELD:
3632 if (gotNumber) // i.e., q or qq.
3633 {
3634 // Don't want to parse the month if it is a string
3635 // while pattern uses numeric style: q or q.
3636 // [We computed 'value' above.]
3637 cal.set(UCAL_MONTH, (value - 1) * 3);
3638 return pos.getIndex();
3639 } else {
3640 // count >= 3 // i.e., qqq or qqqq
3641 // Want to be able to parse both short and long forms.
3642 // Try count == 4 first:
3643 int32_t newStart = 0;
3644
3645 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3646 if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
3647 fSymbols->fStandaloneQuarters, fSymbols->fStandaloneQuartersCount, cal)) > 0)
3648 return newStart;
3649 }
3650 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3651 if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
3652 fSymbols->fStandaloneShortQuarters, fSymbols->fStandaloneShortQuartersCount, cal)) > 0)
3653 return newStart;
3654 }
3655 if(getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
3656 if ((newStart = matchQuarterString(text, start, UCAL_MONTH,
3657 fSymbols->fStandaloneNarrowQuarters, fSymbols->fStandaloneNarrowQuartersCount, cal)) > 0)
3658 return newStart;
3659 }
3660 if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status))
3661 return newStart;
3662 // else we allowing parsing as number, below
3663 if(!getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status))
3664 return -start;
3665 }
3666 break;
3667
3668 case UDAT_TIMEZONE_FIELD: // 'z'
3669 {
3670 UTimeZoneFormatStyle style = (count < 4) ? UTZFMT_STYLE_SPECIFIC_SHORT : UTZFMT_STYLE_SPECIFIC_LONG;
3671 const TimeZoneFormat *tzfmt = tzFormat(status);
3672 if (U_SUCCESS(status)) {
3673 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3674 if (tz != nullptr) {
3675 cal.adoptTimeZone(tz);
3676 return pos.getIndex();
3677 }
3678 }
3679 return -start;
3680 }
3681 break;
3682 case UDAT_TIMEZONE_RFC_FIELD: // 'Z'
3683 {
3684 UTimeZoneFormatStyle style = (count < 4) ?
3685 UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL : ((count == 5) ? UTZFMT_STYLE_ISO_EXTENDED_FULL: UTZFMT_STYLE_LOCALIZED_GMT);
3686 const TimeZoneFormat *tzfmt = tzFormat(status);
3687 if (U_SUCCESS(status)) {
3688 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3689 if (tz != nullptr) {
3690 cal.adoptTimeZone(tz);
3691 return pos.getIndex();
3692 }
3693 }
3694 return -start;
3695 }
3696 case UDAT_TIMEZONE_GENERIC_FIELD: // 'v'
3697 {
3698 UTimeZoneFormatStyle style = (count < 4) ? UTZFMT_STYLE_GENERIC_SHORT : UTZFMT_STYLE_GENERIC_LONG;
3699 const TimeZoneFormat *tzfmt = tzFormat(status);
3700 if (U_SUCCESS(status)) {
3701 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3702 if (tz != nullptr) {
3703 cal.adoptTimeZone(tz);
3704 return pos.getIndex();
3705 }
3706 }
3707 return -start;
3708 }
3709 case UDAT_TIMEZONE_SPECIAL_FIELD: // 'V'
3710 {
3711 UTimeZoneFormatStyle style;
3712 switch (count) {
3713 case 1:
3714 style = UTZFMT_STYLE_ZONE_ID_SHORT;
3715 break;
3716 case 2:
3717 style = UTZFMT_STYLE_ZONE_ID;
3718 break;
3719 case 3:
3720 style = UTZFMT_STYLE_EXEMPLAR_LOCATION;
3721 break;
3722 default:
3723 style = UTZFMT_STYLE_GENERIC_LOCATION;
3724 break;
3725 }
3726 const TimeZoneFormat *tzfmt = tzFormat(status);
3727 if (U_SUCCESS(status)) {
3728 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3729 if (tz != nullptr) {
3730 cal.adoptTimeZone(tz);
3731 return pos.getIndex();
3732 }
3733 }
3734 return -start;
3735 }
3736 case UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD: // 'O'
3737 {
3738 UTimeZoneFormatStyle style = (count < 4) ? UTZFMT_STYLE_LOCALIZED_GMT_SHORT : UTZFMT_STYLE_LOCALIZED_GMT;
3739 const TimeZoneFormat *tzfmt = tzFormat(status);
3740 if (U_SUCCESS(status)) {
3741 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3742 if (tz != nullptr) {
3743 cal.adoptTimeZone(tz);
3744 return pos.getIndex();
3745 }
3746 }
3747 return -start;
3748 }
3749 case UDAT_TIMEZONE_ISO_FIELD: // 'X'
3750 {
3751 UTimeZoneFormatStyle style;
3752 switch (count) {
3753 case 1:
3754 style = UTZFMT_STYLE_ISO_BASIC_SHORT;
3755 break;
3756 case 2:
3757 style = UTZFMT_STYLE_ISO_BASIC_FIXED;
3758 break;
3759 case 3:
3760 style = UTZFMT_STYLE_ISO_EXTENDED_FIXED;
3761 break;
3762 case 4:
3763 style = UTZFMT_STYLE_ISO_BASIC_FULL;
3764 break;
3765 default:
3766 style = UTZFMT_STYLE_ISO_EXTENDED_FULL;
3767 break;
3768 }
3769 const TimeZoneFormat *tzfmt = tzFormat(status);
3770 if (U_SUCCESS(status)) {
3771 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3772 if (tz != nullptr) {
3773 cal.adoptTimeZone(tz);
3774 return pos.getIndex();
3775 }
3776 }
3777 return -start;
3778 }
3779 case UDAT_TIMEZONE_ISO_LOCAL_FIELD: // 'x'
3780 {
3781 UTimeZoneFormatStyle style;
3782 switch (count) {
3783 case 1:
3784 style = UTZFMT_STYLE_ISO_BASIC_LOCAL_SHORT;
3785 break;
3786 case 2:
3787 style = UTZFMT_STYLE_ISO_BASIC_LOCAL_FIXED;
3788 break;
3789 case 3:
3790 style = UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FIXED;
3791 break;
3792 case 4:
3793 style = UTZFMT_STYLE_ISO_BASIC_LOCAL_FULL;
3794 break;
3795 default:
3796 style = UTZFMT_STYLE_ISO_EXTENDED_LOCAL_FULL;
3797 break;
3798 }
3799 const TimeZoneFormat *tzfmt = tzFormat(status);
3800 if (U_SUCCESS(status)) {
3801 TimeZone *tz = tzfmt->parse(style, text, pos, tzTimeType);
3802 if (tz != nullptr) {
3803 cal.adoptTimeZone(tz);
3804 return pos.getIndex();
3805 }
3806 }
3807 return -start;
3808 }
3809 // currently no pattern character is defined for UDAT_TIME_SEPARATOR_FIELD
3810 // so we should not get here. Leave support in for future definition.
3811 case UDAT_TIME_SEPARATOR_FIELD:
3812 {
3813 static const char16_t def_sep = DateFormatSymbols::DEFAULT_TIME_SEPARATOR;
3814 static const char16_t alt_sep = DateFormatSymbols::ALTERNATE_TIME_SEPARATOR;
3815
3816 // Try matching a time separator.
3817 int32_t count_sep = 1;
3818 UnicodeString data[3];
3819 fSymbols->getTimeSeparatorString(data[0]);
3820
3821 // Add the default, if different from the locale.
3822 if (data[0].compare(&def_sep, 1) != 0) {
3823 data[count_sep++].setTo(def_sep);
3824 }
3825
3826 // If lenient, add also the alternate, if different from the locale.
3827 if (isLenient() && data[0].compare(&alt_sep, 1) != 0) {
3828 data[count_sep++].setTo(alt_sep);
3829 }
3830
3831 return matchString(text, start, UCAL_FIELD_COUNT /* => nothing to set */, data, count_sep, nullptr, cal);
3832 }
3833
3834 case UDAT_AM_PM_MIDNIGHT_NOON_FIELD:
3835 {
3836 U_ASSERT(dayPeriod != nullptr)(static_cast <bool> (dayPeriod != nullptr) ? void (0) :
__assert_fail ("dayPeriod != nullptr", __builtin_FILE (), __builtin_LINE
(), __extension__ __PRETTY_FUNCTION__))
;
3837 int32_t ampmStart = subParse(text, start, 0x61, count,
3838 obeyCount, allowNegative, ambiguousYear, saveHebrewMonth, cal,
3839 patLoc, numericLeapMonthFormatter, tzTimeType);
3840
3841 if (ampmStart > 0) {
3842 return ampmStart;
3843 } else {
3844 int32_t newStart = 0;
3845
3846 // Only match the first two strings from the day period strings array.
3847 if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3848 if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fAbbreviatedDayPeriods,
3849 2, *dayPeriod)) > 0) {
3850 return newStart;
3851 }
3852 }
3853 if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
3854 if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fNarrowDayPeriods,
3855 2, *dayPeriod)) > 0) {
3856 return newStart;
3857 }
3858 }
3859 // count == 4, but allow other counts
3860 if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status)) {
3861 if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fWideDayPeriods,
3862 2, *dayPeriod)) > 0) {
3863 return newStart;
3864 }
3865 }
3866
3867 return -start;
3868 }
3869 }
3870
3871 case UDAT_FLEXIBLE_DAY_PERIOD_FIELD:
3872 {
3873 U_ASSERT(dayPeriod != nullptr)(static_cast <bool> (dayPeriod != nullptr) ? void (0) :
__assert_fail ("dayPeriod != nullptr", __builtin_FILE (), __builtin_LINE
(), __extension__ __PRETTY_FUNCTION__))
;
3874 int32_t newStart = 0;
3875
3876 if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 3) {
3877 if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fAbbreviatedDayPeriods,
3878 fSymbols->fAbbreviatedDayPeriodsCount, *dayPeriod)) > 0) {
3879 return newStart;
3880 }
3881 }
3882 if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 5) {
3883 if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fNarrowDayPeriods,
3884 fSymbols->fNarrowDayPeriodsCount, *dayPeriod)) > 0) {
3885 return newStart;
3886 }
3887 }
3888 if (getBooleanAttribute(UDAT_PARSE_MULTIPLE_PATTERNS_FOR_MATCH, status) || count == 4) {
3889 if ((newStart = matchDayPeriodStrings(text, start, fSymbols->fWideDayPeriods,
3890 fSymbols->fWideDayPeriodsCount, *dayPeriod)) > 0) {
3891 return newStart;
3892 }
3893 }
3894
3895 return -start;
3896 }
3897
3898 default:
3899 // Handle "generic" fields
3900 // this is now handled below, outside the switch block
3901 break;
3902 }
3903 // Handle "generic" fields:
3904 // switch default case now handled here (outside switch block) to allow
3905 // parsing of some string fields as digits for lenient case
3906
3907 int32_t parseStart = pos.getIndex();
3908 const UnicodeString* src;
3909 if (obeyCount) {
3910 if ((start+count) > text.length()) {
3911 return -start;
3912 }
3913 text.extractBetween(0, start + count, temp);
3914 src = &temp;
3915 } else {
3916 src = &text;
3917 }
3918 parseInt(*src, number, pos, allowNegative,currentNumberFormat);
3919 if (obeyCount && !isLenient() && pos.getIndex() < start + count) {
3920 return -start;
3921 }
3922 if (pos.getIndex() != parseStart) {
3923 int32_t val = number.getLong();
3924
3925 // Don't need suffix processing here (as in number processing at the beginning of the function);
3926 // the new fields being handled as numeric values (month, weekdays, quarters) should not have suffixes.
3927
3928 if (!getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status)) {
3929 // Check the range of the value
3930 int32_t bias = gFieldRangeBias[patternCharIndex];
3931 if (bias >= 0 && (val > cal.getMaximum(field) + bias || val < cal.getMinimum(field) + bias)) {
3932 return -start;
3933 }
3934 }
3935
3936 // For the following, need to repeat some of the "if (gotNumber)" code above:
3937 // UDAT_[STANDALONE_]MONTH_FIELD, UDAT_DOW_LOCAL_FIELD, UDAT_STANDALONE_DAY_FIELD,
3938 // UDAT_[STANDALONE_]QUARTER_FIELD
3939 switch (patternCharIndex) {
3940 case UDAT_MONTH_FIELD:
3941 // See notes under UDAT_MONTH_FIELD case above
3942 if (typeid(cal) == typeid(HebrewCalendar)) {
3943 HebrewCalendar *hc = (HebrewCalendar*)&cal;
3944 if (cal.isSet(UCAL_YEAR)) {
3945 UErrorCode monthStatus = U_ZERO_ERROR;
3946 if (!hc->isLeapYear(hc->get(UCAL_YEAR, monthStatus)) && val >= 6) {
3947 cal.set(UCAL_MONTH, val);
3948 } else {
3949 cal.set(UCAL_MONTH, val - 1);
3950 }
3951 } else {
3952 saveHebrewMonth = val;
3953 }
3954 } else {
3955 cal.set(UCAL_MONTH, val - 1);
3956 }
3957 break;
3958 case UDAT_STANDALONE_MONTH_FIELD:
3959 cal.set(UCAL_MONTH, val - 1);
3960 break;
3961 case UDAT_DOW_LOCAL_FIELD:
3962 case UDAT_STANDALONE_DAY_FIELD:
3963 cal.set(UCAL_DOW_LOCAL, val);
3964 break;
3965 case UDAT_QUARTER_FIELD:
3966 case UDAT_STANDALONE_QUARTER_FIELD:
3967 cal.set(UCAL_MONTH, (val - 1) * 3);
3968 break;
3969 case UDAT_RELATED_YEAR_FIELD:
3970 cal.setRelatedYear(val);
3971 break;
3972 default:
3973 cal.set(field, val);
3974 break;
3975 }
3976 return pos.getIndex();
3977 }
3978 return -start;
3979}
3980
3981/**
3982 * Parse an integer using fNumberFormat. This method is semantically
3983 * const, but actually may modify fNumberFormat.
3984 */
3985void SimpleDateFormat::parseInt(const UnicodeString& text,
3986 Formattable& number,
3987 ParsePosition& pos,
3988 UBool allowNegative,
3989 const NumberFormat *fmt) const {
3990 parseInt(text, number, -1, pos, allowNegative,fmt);
3991}
3992
3993/**
3994 * Parse an integer using fNumberFormat up to maxDigits.
3995 */
3996void SimpleDateFormat::parseInt(const UnicodeString& text,
3997 Formattable& number,
3998 int32_t maxDigits,
3999 ParsePosition& pos,
4000 UBool allowNegative,
4001 const NumberFormat *fmt) const {
4002 UnicodeString oldPrefix;
4003 const auto* fmtAsDF = dynamic_cast<const DecimalFormat*>(fmt);
4004 LocalPointer<DecimalFormat> df;
4005 if (!allowNegative && fmtAsDF != nullptr) {
4006 df.adoptInstead(fmtAsDF->clone());
4007 if (df.isNull()) {
4008 // Memory allocation error
4009 return;
4010 }
4011 df->setNegativePrefix(UnicodeString(true, SUPPRESS_NEGATIVE_PREFIX, -1));
4012 fmt = df.getAlias();
4013 }
4014 int32_t oldPos = pos.getIndex();
4015 fmt->parse(text, number, pos);
4016
4017 if (maxDigits > 0) {
4018 // adjust the result to fit into
4019 // the maxDigits and move the position back
4020 int32_t nDigits = pos.getIndex() - oldPos;
4021 if (nDigits > maxDigits) {
4022 int32_t val = number.getLong();
4023 nDigits -= maxDigits;
4024 while (nDigits > 0) {
4025 val /= 10;
4026 nDigits--;
4027 }
4028 pos.setIndex(oldPos + maxDigits);
4029 number.setLong(val);
4030 }
4031 }
4032}
4033
4034int32_t SimpleDateFormat::countDigits(const UnicodeString& text, int32_t start, int32_t end) const {
4035 int32_t numDigits = 0;
4036 int32_t idx = start;
4037 while (idx < end) {
4038 UChar32 cp = text.char32At(idx);
4039 if (u_isdigit(cp)) {
4040 numDigits++;
4041 }
4042 idx += U16_LENGTH(cp)((uint32_t)(cp)<=0xffff ? 1 : 2);
4043 }
4044 return numDigits;
4045}
4046
4047//----------------------------------------------------------------------
4048
4049void SimpleDateFormat::translatePattern(const UnicodeString& originalPattern,
4050 UnicodeString& translatedPattern,
4051 const UnicodeString& from,
4052 const UnicodeString& to,
4053 UErrorCode& status)
4054{
4055 // run through the pattern and convert any pattern symbols from the version
4056 // in "from" to the corresponding character in "to". This code takes
4057 // quoted strings into account (it doesn't try to translate them), and it signals
4058 // an error if a particular "pattern character" doesn't appear in "from".
4059 // Depending on the values of "from" and "to" this can convert from generic
4060 // to localized patterns or localized to generic.
4061 if (U_FAILURE(status)) {
4062 return;
4063 }
4064
4065 translatedPattern.remove();
4066 UBool inQuote = false;
4067 for (int32_t i = 0; i < originalPattern.length(); ++i) {
4068 char16_t c = originalPattern[i];
4069 if (inQuote) {
4070 if (c == QUOTE) {
4071 inQuote = false;
4072 }
4073 } else {
4074 if (c == QUOTE) {
4075 inQuote = true;
4076 } else if (isSyntaxChar(c)) {
4077 int32_t ci = from.indexOf(c);
4078 if (ci == -1) {
4079 status = U_INVALID_FORMAT_ERROR;
4080 return;
4081 }
4082 c = to[ci];
4083 }
4084 }
4085 translatedPattern += c;
4086 }
4087 if (inQuote) {
4088 status = U_INVALID_FORMAT_ERROR;
4089 return;
4090 }
4091}
4092
4093//----------------------------------------------------------------------
4094
4095UnicodeString&
4096SimpleDateFormat::toPattern(UnicodeString& result) const
4097{
4098 result = fPattern;
4099 return result;
4100}
4101
4102//----------------------------------------------------------------------
4103
4104UnicodeString&
4105SimpleDateFormat::toLocalizedPattern(UnicodeString& result,
4106 UErrorCode& status) const
4107{
4108 translatePattern(fPattern, result,
4109 UnicodeString(DateFormatSymbols::getPatternUChars()),
4110 fSymbols->fLocalPatternChars, status);
4111 return result;
4112}
4113
4114//----------------------------------------------------------------------
4115
4116void
4117SimpleDateFormat::applyPattern(const UnicodeString& pattern)
4118{
4119 fPattern = pattern;
4120 parsePattern();
4121
4122 // Hack to update use of Gannen year numbering for ja@calendar=japanese -
4123 // use only if format is non-numeric (includes 年) and no other fDateOverride.
4124 if (fCalendar != nullptr && typeid(*fCalendar) == typeid(JapaneseCalendar) &&
4125 uprv_strcmp(fLocale.getLanguage(),"ja"):: strcmp(fLocale.getLanguage(), "ja") == 0) {
4126 if (fDateOverride==UnicodeString(u"y=jpanyear") && !fHasHanYearChar) {
4127 // Gannen numbering is set but new pattern should not use it, unset;
4128 // use procedure from adoptNumberFormat to clear overrides
4129 if (fSharedNumberFormatters) {
4130 freeSharedNumberFormatters(fSharedNumberFormatters);
4131 fSharedNumberFormatters = nullptr;
4132 }
4133 fDateOverride.setToBogus(); // record status
4134 } else if (fDateOverride.isBogus() && fHasHanYearChar) {
4135 // No current override (=> no Gannen numbering) but new pattern needs it;
4136 // use procedures from initNUmberFormatters / adoptNumberFormat
4137 umtx_lock(&LOCK);
4138 if (fSharedNumberFormatters == nullptr) {
4139 fSharedNumberFormatters = allocSharedNumberFormatters();
4140 }
4141 umtx_unlock(&LOCK);
4142 if (fSharedNumberFormatters != nullptr) {
4143 Locale ovrLoc(fLocale.getLanguage(),fLocale.getCountry(),fLocale.getVariant(),"numbers=jpanyear");
4144 UErrorCode status = U_ZERO_ERROR;
4145 const SharedNumberFormat *snf = createSharedNumberFormat(ovrLoc, status);
4146 if (U_SUCCESS(status)) {
4147 // Now that we have an appropriate number formatter, fill in the
4148 // appropriate slot in the number formatters table.
4149 UDateFormatField patternCharIndex = DateFormatSymbols::getPatternCharIndex(u'y');
4150 SharedObject::copyPtr(snf, fSharedNumberFormatters[patternCharIndex]);
4151 snf->deleteIfZeroRefCount();
4152 fDateOverride.setTo(u"y=jpanyear", -1); // record status
4153 }
4154 }
4155 }
4156 }
4157}
4158
4159//----------------------------------------------------------------------
4160
4161void
4162SimpleDateFormat::applyLocalizedPattern(const UnicodeString& pattern,
4163 UErrorCode &status)
4164{
4165 translatePattern(pattern, fPattern,
4166 fSymbols->fLocalPatternChars,
4167 UnicodeString(DateFormatSymbols::getPatternUChars()), status);
4168}
4169
4170//----------------------------------------------------------------------
4171
4172const DateFormatSymbols*
4173SimpleDateFormat::getDateFormatSymbols() const
4174{
4175 return fSymbols;
4176}
4177
4178//----------------------------------------------------------------------
4179
4180void
4181SimpleDateFormat::adoptDateFormatSymbols(DateFormatSymbols* newFormatSymbols)
4182{
4183 delete fSymbols;
4184 fSymbols = newFormatSymbols;
4185}
4186
4187//----------------------------------------------------------------------
4188void
4189SimpleDateFormat::setDateFormatSymbols(const DateFormatSymbols& newFormatSymbols)
4190{
4191 delete fSymbols;
4192 fSymbols = new DateFormatSymbols(newFormatSymbols);
4193}
4194
4195//----------------------------------------------------------------------
4196const TimeZoneFormat*
4197SimpleDateFormat::getTimeZoneFormat() const {
4198 // TimeZoneFormat initialization might fail when out of memory.
4199 // If we always initialize TimeZoneFormat instance, we can return
4200 // such status there. For now, this implementation lazily instantiates
4201 // a TimeZoneFormat for performance optimization reasons, but cannot
4202 // propagate such error (probably just out of memory case) to the caller.
4203 UErrorCode status = U_ZERO_ERROR;
4204 return (const TimeZoneFormat*)tzFormat(status);
4205}
4206
4207//----------------------------------------------------------------------
4208void
4209SimpleDateFormat::adoptTimeZoneFormat(TimeZoneFormat* timeZoneFormatToAdopt)
4210{
4211 delete fTimeZoneFormat;
4212 fTimeZoneFormat = timeZoneFormatToAdopt;
4213}
4214
4215//----------------------------------------------------------------------
4216void
4217SimpleDateFormat::setTimeZoneFormat(const TimeZoneFormat& newTimeZoneFormat)
4218{
4219 delete fTimeZoneFormat;
4220 fTimeZoneFormat = new TimeZoneFormat(newTimeZoneFormat);
4221}
4222
4223//----------------------------------------------------------------------
4224
4225
4226void SimpleDateFormat::adoptCalendar(Calendar* calendarToAdopt)
4227{
4228 UErrorCode status = U_ZERO_ERROR;
4229 Locale calLocale(fLocale);
4230 calLocale.setKeywordValue("calendar", calendarToAdopt->getType(), status);
4231 DateFormatSymbols *newSymbols =
4232 DateFormatSymbols::createForLocale(calLocale, status);
4233 if (U_FAILURE(status)) {
4234 delete calendarToAdopt;
4235 return;
4236 }
4237 DateFormat::adoptCalendar(calendarToAdopt);
4238 delete fSymbols;
4239 fSymbols = newSymbols;
4240 initializeDefaultCentury(); // we need a new century (possibly)
4241}
4242
4243
4244//----------------------------------------------------------------------
4245
4246
4247// override the DateFormat implementation in order to
4248// lazily initialize fCapitalizationBrkIter
4249void
4250SimpleDateFormat::setContext(UDisplayContext value, UErrorCode& status)
4251{
4252 DateFormat::setContext(value, status);
4253#if !UCONFIG_NO_BREAK_ITERATION1
4254 if (U_SUCCESS(status)) {
4255 if ( fCapitalizationBrkIter == nullptr && (value==UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE ||
4256 value==UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU || value==UDISPCTX_CAPITALIZATION_FOR_STANDALONE) ) {
4257 status = U_ZERO_ERROR;
4258 fCapitalizationBrkIter = BreakIterator::createSentenceInstance(fLocale, status);
4259 if (U_FAILURE(status)) {
4260 delete fCapitalizationBrkIter;
4261 fCapitalizationBrkIter = nullptr;
4262 }
4263 }
4264 }
4265#endif
4266}
4267
4268
4269//----------------------------------------------------------------------
4270
4271
4272UBool
4273SimpleDateFormat::isFieldUnitIgnored(UCalendarDateFields field) const {
4274 return isFieldUnitIgnored(fPattern, field);
4275}
4276
4277
4278UBool
4279SimpleDateFormat::isFieldUnitIgnored(const UnicodeString& pattern,
4280 UCalendarDateFields field) {
4281 int32_t fieldLevel = fgCalendarFieldToLevel[field];
4282 int32_t level;
4283 char16_t ch;
4284 UBool inQuote = false;
4285 char16_t prevCh = 0;
4286 int32_t count = 0;
4287
4288 for (int32_t i = 0; i < pattern.length(); ++i) {
4289 ch = pattern[i];
4290 if (ch != prevCh && count > 0) {
4291 level = getLevelFromChar(prevCh);
4292 // the larger the level, the smaller the field unit.
4293 if (fieldLevel <= level) {
4294 return false;
4295 }
4296 count = 0;
4297 }
4298 if (ch == QUOTE) {
4299 if ((i+1) < pattern.length() && pattern[i+1] == QUOTE) {
4300 ++i;
4301 } else {
4302 inQuote = ! inQuote;
4303 }
4304 }
4305 else if (!inQuote && isSyntaxChar(ch)) {
4306 prevCh = ch;
4307 ++count;
4308 }
4309 }
4310 if (count > 0) {
4311 // last item
4312 level = getLevelFromChar(prevCh);
4313 if (fieldLevel <= level) {
4314 return false;
4315 }
4316 }
4317 return true;
4318}
4319
4320//----------------------------------------------------------------------
4321
4322const Locale&
4323SimpleDateFormat::getSmpFmtLocale() const {
4324 return fLocale;
4325}
4326
4327//----------------------------------------------------------------------
4328
4329int32_t
4330SimpleDateFormat::checkIntSuffix(const UnicodeString& text, int32_t start,
4331 int32_t patLoc, UBool isNegative) const {
4332 // local variables
4333 UnicodeString suf;
4334 int32_t patternMatch;
4335 int32_t textPreMatch;
4336 int32_t textPostMatch;
4337
4338 // check that we are still in range
4339 if ( (start > text.length()) ||
4340 (start < 0) ||
4341 (patLoc < 0) ||
4342 (patLoc > fPattern.length())) {
4343 // out of range, don't advance location in text
4344 return start;
4345 }
4346
4347 // get the suffix
4348 DecimalFormat* decfmt = dynamic_cast<DecimalFormat*>(fNumberFormat);
4349 if (decfmt != nullptr) {
4350 if (isNegative) {
4351 suf = decfmt->getNegativeSuffix(suf);
4352 }
4353 else {
4354 suf = decfmt->getPositiveSuffix(suf);
4355 }
4356 }
4357
4358 // check for suffix
4359 if (suf.length() <= 0) {
4360 return start;
4361 }
4362
4363 // check suffix will be encountered in the pattern
4364 patternMatch = compareSimpleAffix(suf,fPattern,patLoc);
4365
4366 // check if a suffix will be encountered in the text
4367 textPreMatch = compareSimpleAffix(suf,text,start);
4368
4369 // check if a suffix was encountered in the text
4370 textPostMatch = compareSimpleAffix(suf,text,start-suf.length());
4371
4372 // check for suffix match
4373 if ((textPreMatch >= 0) && (patternMatch >= 0) && (textPreMatch == patternMatch)) {
4374 return start;
4375 }
4376 else if ((textPostMatch >= 0) && (patternMatch >= 0) && (textPostMatch == patternMatch)) {
4377 return start - suf.length();
4378 }
4379
4380 // should not get here
4381 return start;
4382}
4383
4384//----------------------------------------------------------------------
4385
4386int32_t
4387SimpleDateFormat::compareSimpleAffix(const UnicodeString& affix,
4388 const UnicodeString& input,
4389 int32_t pos) const {
4390 int32_t start = pos;
4391 for (int32_t i=0; i<affix.length(); ) {
4392 UChar32 c = affix.char32At(i);
4393 int32_t len = U16_LENGTH(c)((uint32_t)(c)<=0xffff ? 1 : 2);
4394 if (PatternProps::isWhiteSpace(c)) {
4395 // We may have a pattern like: \u200F \u0020
4396 // and input text like: \u200F \u0020
4397 // Note that U+200F and U+0020 are Pattern_White_Space but only
4398 // U+0020 is UWhiteSpace. So we have to first do a direct
4399 // match of the run of Pattern_White_Space in the pattern,
4400 // then match any extra characters.
4401 UBool literalMatch = false;
4402 while (pos < input.length() &&
4403 input.char32At(pos) == c) {
4404 literalMatch = true;
4405 i += len;
4406 pos += len;
4407 if (i == affix.length()) {
4408 break;
4409 }
4410 c = affix.char32At(i);
4411 len = U16_LENGTH(c)((uint32_t)(c)<=0xffff ? 1 : 2);
4412 if (!PatternProps::isWhiteSpace(c)) {
4413 break;
4414 }
4415 }
4416
4417 // Advance over run in pattern
4418 i = skipPatternWhiteSpace(affix, i);
4419
4420 // Advance over run in input text
4421 // Must see at least one white space char in input,
4422 // unless we've already matched some characters literally.
4423 int32_t s = pos;
4424 pos = skipUWhiteSpace(input, pos);
4425 if (pos == s && !literalMatch) {
4426 return -1;
4427 }
4428
4429 // If we skip UWhiteSpace in the input text, we need to skip it in the pattern.
4430 // Otherwise, the previous lines may have skipped over text (such as U+00A0) that
4431 // is also in the affix.
4432 i = skipUWhiteSpace(affix, i);
4433 } else {
4434 if (pos < input.length() &&
4435 input.char32At(pos) == c) {
4436 i += len;
4437 pos += len;
4438 } else {
4439 return -1;
4440 }
4441 }
4442 }
4443 return pos - start;
4444}
4445
4446//----------------------------------------------------------------------
4447
4448int32_t
4449SimpleDateFormat::skipPatternWhiteSpace(const UnicodeString& text, int32_t pos) const {
4450 const char16_t* s = text.getBuffer();
4451 return static_cast<int32_t>(PatternProps::skipWhiteSpace(s + pos, text.length() - pos) - s);
4452}
4453
4454//----------------------------------------------------------------------
4455
4456int32_t
4457SimpleDateFormat::skipUWhiteSpace(const UnicodeString& text, int32_t pos) const {
4458 while (pos < text.length()) {
4459 UChar32 c = text.char32At(pos);
4460 if (!u_isUWhiteSpace(c)) {
4461 break;
4462 }
4463 pos += U16_LENGTH(c)((uint32_t)(c)<=0xffff ? 1 : 2);
4464 }
4465 return pos;
4466}
4467
4468//----------------------------------------------------------------------
4469
4470// Lazy TimeZoneFormat instantiation, semantically const.
4471TimeZoneFormat *
4472SimpleDateFormat::tzFormat(UErrorCode &status) const {
4473 Mutex m(&LOCK);
4474 if (fTimeZoneFormat == nullptr && U_SUCCESS(status)) {
4475 const_cast<SimpleDateFormat *>(this)->fTimeZoneFormat =
4476 TimeZoneFormat::createInstance(fLocale, status);
4477 }
4478 return fTimeZoneFormat;
4479}
4480
4481void SimpleDateFormat::parsePattern() {
4482 fHasMinute = false;
4483 fHasSecond = false;
4484 fHasHanYearChar = false;
4485
4486 int len = fPattern.length();
4487 UBool inQuote = false;
4488 for (int32_t i = 0; i < len; ++i) {
4489 char16_t ch = fPattern[i];
4490 if (ch == QUOTE) {
4491 inQuote = !inQuote;
4492 }
4493 if (ch == 0x5E74) { // don't care whether this is inside quotes
4494 fHasHanYearChar = true;
4495 }
4496 if (!inQuote) {
4497 if (ch == 0x6D) { // 0x6D == 'm'
4498 fHasMinute = true;
4499 }
4500 if (ch == 0x73) { // 0x73 == 's'
4501 fHasSecond = true;
4502 }
4503 }
4504 }
4505}
4506
4507U_NAMESPACE_END}
4508
4509#endif /* #if !UCONFIG_NO_FORMATTING */
4510
4511//eof