Coverage Report

Created: 2018-09-25 14:53

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