Bug Summary

File:out/../deps/icu-small/source/i18n/dtitvfmt.cpp
Warning:line 389, column 20
The left operand of '!=' is a garbage value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-unknown-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name dtitvfmt.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 2 -pic-is-pie -mframe-pointer=all -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/home/maurizio/node-v18.6.0/out -resource-dir /usr/local/lib/clang/16.0.0 -D V8_DEPRECATION_WARNINGS -D V8_IMMINENT_DEPRECATION_WARNINGS -D _GLIBCXX_USE_CXX11_ABI=1 -D NODE_OPENSSL_CONF_NAME=nodejs_conf -D NODE_OPENSSL_HAS_QUIC -D __STDC_FORMAT_MACROS -D OPENSSL_NO_PINSHARED -D OPENSSL_THREADS -D U_COMMON_IMPLEMENTATION=1 -D U_I18N_IMPLEMENTATION=1 -D U_IO_IMPLEMENTATION=1 -D U_TOOLUTIL_IMPLEMENTATION=1 -D U_ATTRIBUTE_DEPRECATED= -D _CRT_SECURE_NO_DEPRECATE= -D U_STATIC_IMPLEMENTATION=1 -D UCONFIG_NO_SERVICE=1 -D U_ENABLE_DYLOAD=0 -D U_HAVE_STD_STRING=1 -D UCONFIG_NO_BREAK_ITERATION=0 -I ../deps/icu-small/source/common -I ../deps/icu-small/source/i18n -I ../deps/icu-small/source/tools/toolutil -internal-isystem /usr/lib/gcc/x86_64-redhat-linux/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-redhat-linux/8/../../../../include/c++/8/x86_64-redhat-linux -internal-isystem /usr/lib/gcc/x86_64-redhat-linux/8/../../../../include/c++/8/backward -internal-isystem /usr/local/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-redhat-linux/8/../../../../x86_64-redhat-linux/include -internal-externc-isystem /include -internal-externc-isystem /usr/include -O3 -Wno-unused-parameter -Wno-deprecated-declarations -Wno-strict-aliasing -std=gnu++17 -fdeprecated-macro -fdebug-compilation-dir=/home/maurizio/node-v18.6.0/out -ferror-limit 19 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-08-22-142216-507842-1 -x c++ ../deps/icu-small/source/i18n/dtitvfmt.cpp
1// © 2016 and later: Unicode, Inc. and others.
2// License & terms of use: http://www.unicode.org/copyright.html
3/*******************************************************************************
4* Copyright (C) 2008-2016, International Business Machines Corporation and
5* others. All Rights Reserved.
6*******************************************************************************
7*
8* File DTITVFMT.CPP
9*
10*******************************************************************************
11*/
12
13#include "utypeinfo.h" // for 'typeid' to work
14
15#include "unicode/dtitvfmt.h"
16
17#if !UCONFIG_NO_FORMATTING0
18
19//TODO: put in compilation
20//#define DTITVFMT_DEBUG 1
21
22#include "unicode/calendar.h"
23#include "unicode/dtptngen.h"
24#include "unicode/dtitvinf.h"
25#include "unicode/simpleformatter.h"
26#include "unicode/udisplaycontext.h"
27#include "cmemory.h"
28#include "cstring.h"
29#include "dtitv_impl.h"
30#include "mutex.h"
31#include "uresimp.h"
32#include "formattedval_impl.h"
33
34#ifdef DTITVFMT_DEBUG
35#include <iostream>
36#endif
37
38U_NAMESPACE_BEGINnamespace icu_71 {
39
40
41
42#ifdef DTITVFMT_DEBUG
43#define PRINTMESG(msg) { std::cout << "(" << __FILE__"../deps/icu-small/source/i18n/dtitvfmt.cpp" << ":" << __LINE__43 << ") " << msg << "\n"; }
44#endif
45
46
47static const UChar gDateFormatSkeleton[][11] = {
48//yMMMMEEEEd
49{LOW_Y((UChar)0x0079), CAP_M((UChar)0x004D), CAP_M((UChar)0x004D), CAP_M((UChar)0x004D), CAP_M((UChar)0x004D), CAP_E((UChar)0x0045), CAP_E((UChar)0x0045), CAP_E((UChar)0x0045), CAP_E((UChar)0x0045), LOW_D((UChar)0x0064), 0},
50//yMMMMd
51{LOW_Y((UChar)0x0079), CAP_M((UChar)0x004D), CAP_M((UChar)0x004D), CAP_M((UChar)0x004D), CAP_M((UChar)0x004D), LOW_D((UChar)0x0064), 0},
52//yMMMd
53{LOW_Y((UChar)0x0079), CAP_M((UChar)0x004D), CAP_M((UChar)0x004D), CAP_M((UChar)0x004D), LOW_D((UChar)0x0064), 0},
54//yMd
55{LOW_Y((UChar)0x0079), CAP_M((UChar)0x004D), LOW_D((UChar)0x0064), 0} };
56
57
58static const char gCalendarTag[] = "calendar";
59static const char gGregorianTag[] = "gregorian";
60static const char gDateTimePatternsTag[] = "DateTimePatterns";
61
62
63// latestFirst:
64static const UChar gLaterFirstPrefix[] = {LOW_L((UChar)0x006C), LOW_A((UChar)0x0061), LOW_T((UChar)0x0074), LOW_E((UChar)0x0065), LOW_S((UChar)0x0073),LOW_T((UChar)0x0074), CAP_F((UChar)0x0046), LOW_I((UChar)0x0069), LOW_R((UChar)0x0072), LOW_S((UChar)0x0073), LOW_T((UChar)0x0074), COLON((UChar)0x003A)};
65
66// earliestFirst:
67static const UChar gEarlierFirstPrefix[] = {LOW_E((UChar)0x0065), LOW_A((UChar)0x0061), LOW_R((UChar)0x0072), LOW_L((UChar)0x006C), LOW_I((UChar)0x0069), LOW_E((UChar)0x0065), LOW_S((UChar)0x0073), LOW_T((UChar)0x0074), CAP_F((UChar)0x0046), LOW_I((UChar)0x0069), LOW_R((UChar)0x0072), LOW_S((UChar)0x0073), LOW_T((UChar)0x0074), COLON((UChar)0x003A)};
68
69
70class FormattedDateIntervalData : public FormattedValueFieldPositionIteratorImpl {
71public:
72 FormattedDateIntervalData(UErrorCode& status) : FormattedValueFieldPositionIteratorImpl(5, status) {}
73 virtual ~FormattedDateIntervalData();
74};
75
76FormattedDateIntervalData::~FormattedDateIntervalData() = default;
77
78UPRV_FORMATTED_VALUE_SUBCLASS_AUTO_IMPL(FormattedDateInterval)FormattedDateInterval::FormattedDateInterval(FormattedDateInterval
&& src) noexcept : fData(src.fData), fErrorCode(src.fErrorCode
) { src.fData = nullptr; src.fErrorCode = U_INVALID_STATE_ERROR
; } FormattedDateInterval::~FormattedDateInterval() { delete fData
; fData = nullptr; } FormattedDateInterval& FormattedDateInterval
::operator=(FormattedDateInterval&& src) noexcept { delete
fData; fData = src.fData; src.fData = nullptr; fErrorCode = src
.fErrorCode; src.fErrorCode = U_INVALID_STATE_ERROR; return *
this; } UnicodeString FormattedDateInterval::toString(UErrorCode
& status) const { if (U_FAILURE(status)) { return ICU_Utility
::makeBogusString(); } if (fData == nullptr) { status = fErrorCode
; return ICU_Utility::makeBogusString(); } return fData->toString
(status); } UnicodeString FormattedDateInterval::toTempString
(UErrorCode& status) const { if (U_FAILURE(status)) { return
ICU_Utility::makeBogusString(); } if (fData == nullptr) { status
= fErrorCode; return ICU_Utility::makeBogusString(); } return
fData->toTempString(status); } Appendable& FormattedDateInterval
::appendTo(Appendable& appendable, UErrorCode& status
) const { if (U_FAILURE(status)) { return appendable; } if (fData
== nullptr) { status = fErrorCode; return appendable; } return
fData->appendTo(appendable, status); } UBool FormattedDateInterval
::nextPosition(ConstrainedFieldPosition& cfpos, UErrorCode
& status) const { if (U_FAILURE(status)) { return false; }
if (fData == nullptr) { status = fErrorCode; return false; }
return fData->nextPosition(cfpos, status); }
79
80
81UOBJECT_DEFINE_RTTI_IMPLEMENTATION(DateIntervalFormat)UClassID DateIntervalFormat::getStaticClassID() { static char
classID = 0; return (UClassID)&classID; } UClassID DateIntervalFormat
::getDynamicClassID() const { return DateIntervalFormat::getStaticClassID
(); }
82
83// Mutex, protects access to fDateFormat, fFromCalendar and fToCalendar.
84// Needed because these data members are modified by const methods of DateIntervalFormat.
85
86static UMutex gFormatterMutex;
87
88DateIntervalFormat* U_EXPORT2
89DateIntervalFormat::createInstance(const UnicodeString& skeleton,
90 UErrorCode& status) {
91 return createInstance(skeleton, Locale::getDefault(), status);
92}
93
94
95DateIntervalFormat* U_EXPORT2
96DateIntervalFormat::createInstance(const UnicodeString& skeleton,
97 const Locale& locale,
98 UErrorCode& status) {
99#ifdef DTITVFMT_DEBUG
100 char result[1000];
101 char result_1[1000];
102 char mesg[2000];
103 skeleton.extract(0, skeleton.length(), result, "UTF-8");
104 UnicodeString pat;
105 ((SimpleDateFormat*)dtfmt)->toPattern(pat);
106 pat.extract(0, pat.length(), result_1, "UTF-8");
107 sprintf(mesg, "skeleton: %s; pattern: %s\n", result, result_1);
108 PRINTMESG(mesg)
109#endif
110
111 DateIntervalInfo* dtitvinf = new DateIntervalInfo(locale, status);
112 if (dtitvinf == nullptr) {
113 status = U_MEMORY_ALLOCATION_ERROR;
114 return nullptr;
115 }
116 return create(locale, dtitvinf, &skeleton, status);
117}
118
119
120
121DateIntervalFormat* U_EXPORT2
122DateIntervalFormat::createInstance(const UnicodeString& skeleton,
123 const DateIntervalInfo& dtitvinf,
124 UErrorCode& status) {
125 return createInstance(skeleton, Locale::getDefault(), dtitvinf, status);
126}
127
128
129DateIntervalFormat* U_EXPORT2
130DateIntervalFormat::createInstance(const UnicodeString& skeleton,
131 const Locale& locale,
132 const DateIntervalInfo& dtitvinf,
133 UErrorCode& status) {
134 DateIntervalInfo* ptn = dtitvinf.clone();
135 return create(locale, ptn, &skeleton, status);
136}
137
138
139DateIntervalFormat::DateIntervalFormat()
140: fInfo(nullptr),
141 fDateFormat(nullptr),
142 fFromCalendar(nullptr),
143 fToCalendar(nullptr),
144 fLocale(Locale::getRoot()),
145 fDatePattern(nullptr),
146 fTimePattern(nullptr),
147 fDateTimeFormat(nullptr),
148 fCapitalizationContext(UDISPCTX_CAPITALIZATION_NONE)
149{}
150
151
152DateIntervalFormat::DateIntervalFormat(const DateIntervalFormat& itvfmt)
153: Format(itvfmt),
154 fInfo(nullptr),
155 fDateFormat(nullptr),
156 fFromCalendar(nullptr),
157 fToCalendar(nullptr),
158 fLocale(itvfmt.fLocale),
159 fDatePattern(nullptr),
160 fTimePattern(nullptr),
161 fDateTimeFormat(nullptr),
162 fCapitalizationContext(UDISPCTX_CAPITALIZATION_NONE) {
163 *this = itvfmt;
164}
165
166
167DateIntervalFormat&
168DateIntervalFormat::operator=(const DateIntervalFormat& itvfmt) {
169 if ( this != &itvfmt ) {
170 delete fDateFormat;
171 delete fInfo;
172 delete fFromCalendar;
173 delete fToCalendar;
174 delete fDatePattern;
175 delete fTimePattern;
176 delete fDateTimeFormat;
177 {
178 Mutex lock(&gFormatterMutex);
179 if ( itvfmt.fDateFormat ) {
180 fDateFormat = itvfmt.fDateFormat->clone();
181 } else {
182 fDateFormat = nullptr;
183 }
184 if ( itvfmt.fFromCalendar ) {
185 fFromCalendar = itvfmt.fFromCalendar->clone();
186 } else {
187 fFromCalendar = nullptr;
188 }
189 if ( itvfmt.fToCalendar ) {
190 fToCalendar = itvfmt.fToCalendar->clone();
191 } else {
192 fToCalendar = nullptr;
193 }
194 }
195 if ( itvfmt.fInfo ) {
196 fInfo = itvfmt.fInfo->clone();
197 } else {
198 fInfo = nullptr;
199 }
200 fSkeleton = itvfmt.fSkeleton;
201 int8_t i;
202 for ( i = 0; i< DateIntervalInfo::kIPI_MAX_INDEX; ++i ) {
203 fIntervalPatterns[i] = itvfmt.fIntervalPatterns[i];
204 }
205 fLocale = itvfmt.fLocale;
206 fDatePattern = (itvfmt.fDatePattern)? itvfmt.fDatePattern->clone(): nullptr;
207 fTimePattern = (itvfmt.fTimePattern)? itvfmt.fTimePattern->clone(): nullptr;
208 fDateTimeFormat = (itvfmt.fDateTimeFormat)? itvfmt.fDateTimeFormat->clone(): nullptr;
209 fCapitalizationContext = itvfmt.fCapitalizationContext;
210 }
211 return *this;
212}
213
214
215DateIntervalFormat::~DateIntervalFormat() {
216 delete fInfo;
217 delete fDateFormat;
218 delete fFromCalendar;
219 delete fToCalendar;
220 delete fDatePattern;
221 delete fTimePattern;
222 delete fDateTimeFormat;
223}
224
225
226DateIntervalFormat*
227DateIntervalFormat::clone() const {
228 return new DateIntervalFormat(*this);
229}
230
231
232bool
233DateIntervalFormat::operator==(const Format& other) const {
234 if (typeid(*this) != typeid(other)) {return false;}
235 const DateIntervalFormat* fmt = (DateIntervalFormat*)&other;
236 if (this == fmt) {return true;}
237 if (!Format::operator==(other)) {return false;}
238 if ((fInfo != fmt->fInfo) && (fInfo == nullptr || fmt->fInfo == nullptr)) {return false;}
239 if (fInfo && fmt->fInfo && (*fInfo != *fmt->fInfo )) {return false;}
240 {
241 Mutex lock(&gFormatterMutex);
242 if (fDateFormat != fmt->fDateFormat && (fDateFormat == nullptr || fmt->fDateFormat == nullptr)) {return false;}
243 if (fDateFormat && fmt->fDateFormat && (*fDateFormat != *fmt->fDateFormat)) {return false;}
244 }
245 // note: fFromCalendar and fToCalendar hold no persistent state, and therefore do not participate in operator ==.
246 // fDateFormat has the primary calendar for the DateIntervalFormat.
247 if (fSkeleton != fmt->fSkeleton) {return false;}
248 if (fDatePattern != fmt->fDatePattern && (fDatePattern == nullptr || fmt->fDatePattern == nullptr)) {return false;}
249 if (fDatePattern && fmt->fDatePattern && (*fDatePattern != *fmt->fDatePattern)) {return false;}
250 if (fTimePattern != fmt->fTimePattern && (fTimePattern == nullptr || fmt->fTimePattern == nullptr)) {return false;}
251 if (fTimePattern && fmt->fTimePattern && (*fTimePattern != *fmt->fTimePattern)) {return false;}
252 if (fDateTimeFormat != fmt->fDateTimeFormat && (fDateTimeFormat == nullptr || fmt->fDateTimeFormat == nullptr)) {return false;}
253 if (fDateTimeFormat && fmt->fDateTimeFormat && (*fDateTimeFormat != *fmt->fDateTimeFormat)) {return false;}
254 if (fLocale != fmt->fLocale) {return false;}
255
256 for (int32_t i = 0; i< DateIntervalInfo::kIPI_MAX_INDEX; ++i ) {
257 if (fIntervalPatterns[i].firstPart != fmt->fIntervalPatterns[i].firstPart) {return false;}
258 if (fIntervalPatterns[i].secondPart != fmt->fIntervalPatterns[i].secondPart ) {return false;}
259 if (fIntervalPatterns[i].laterDateFirst != fmt->fIntervalPatterns[i].laterDateFirst) {return false;}
260 }
261 if (fCapitalizationContext != fmt->fCapitalizationContext) {return false;}
262 return true;
263}
264
265
266UnicodeString&
267DateIntervalFormat::format(const Formattable& obj,
268 UnicodeString& appendTo,
269 FieldPosition& fieldPosition,
270 UErrorCode& status) const {
271 if ( U_FAILURE(status) ) {
272 return appendTo;
273 }
274
275 if ( obj.getType() == Formattable::kObject ) {
276 const UObject* formatObj = obj.getObject();
277 const DateInterval* interval = dynamic_cast<const DateInterval*>(formatObj);
278 if (interval != nullptr) {
279 return format(interval, appendTo, fieldPosition, status);
280 }
281 }
282 status = U_ILLEGAL_ARGUMENT_ERROR;
283 return appendTo;
284}
285
286
287UnicodeString&
288DateIntervalFormat::format(const DateInterval* dtInterval,
289 UnicodeString& appendTo,
290 FieldPosition& fieldPosition,
291 UErrorCode& status) const {
292 if ( U_FAILURE(status) ) {
293 return appendTo;
294 }
295 if (fDateFormat == nullptr || fInfo == nullptr) {
296 status = U_INVALID_STATE_ERROR;
297 return appendTo;
298 }
299
300 FieldPositionOnlyHandler handler(fieldPosition);
301 handler.setAcceptFirstOnly(TRUE1);
302 int8_t ignore;
303
304 Mutex lock(&gFormatterMutex);
305 return formatIntervalImpl(*dtInterval, appendTo, ignore, handler, status);
306}
307
308
309FormattedDateInterval DateIntervalFormat::formatToValue(
310 const DateInterval& dtInterval,
311 UErrorCode& status) const {
312 if (U_FAILURE(status)) {
313 return FormattedDateInterval(status);
314 }
315 // LocalPointer only sets OOM status if U_SUCCESS is true.
316 LocalPointer<FormattedDateIntervalData> result(new FormattedDateIntervalData(status), status);
317 if (U_FAILURE(status)) {
318 return FormattedDateInterval(status);
319 }
320 UnicodeString string;
321 int8_t firstIndex;
322 auto handler = result->getHandler(status);
323 handler.setCategory(UFIELD_CATEGORY_DATE);
324 {
325 Mutex lock(&gFormatterMutex);
326 formatIntervalImpl(dtInterval, string, firstIndex, handler, status);
327 }
328 handler.getError(status);
329 result->appendString(string, status);
330 if (U_FAILURE(status)) {
331 return FormattedDateInterval(status);
332 }
333
334 // Compute the span fields and sort them into place:
335 if (firstIndex != -1) {
336 result->addOverlapSpans(UFIELD_CATEGORY_DATE_INTERVAL_SPAN, firstIndex, status);
337 if (U_FAILURE(status)) {
338 return FormattedDateInterval(status);
339 }
340 result->sort();
341 }
342
343 return FormattedDateInterval(result.orphan());
344}
345
346
347UnicodeString&
348DateIntervalFormat::format(Calendar& fromCalendar,
349 Calendar& toCalendar,
350 UnicodeString& appendTo,
351 FieldPosition& pos,
352 UErrorCode& status) const {
353 FieldPositionOnlyHandler handler(pos);
354 handler.setAcceptFirstOnly(TRUE1);
355 int8_t ignore;
356
357 Mutex lock(&gFormatterMutex);
358 return formatImpl(fromCalendar, toCalendar, appendTo, ignore, handler, status);
359}
360
361
362FormattedDateInterval DateIntervalFormat::formatToValue(
363 Calendar& fromCalendar,
364 Calendar& toCalendar,
365 UErrorCode& status) const {
366 if (U_FAILURE(status)) {
1
Taking false branch
367 return FormattedDateInterval(status);
368 }
369 // LocalPointer only sets OOM status if U_SUCCESS is true.
370 LocalPointer<FormattedDateIntervalData> result(new FormattedDateIntervalData(status), status);
371 if (U_FAILURE(status)) {
2
Taking false branch
372 return FormattedDateInterval(status);
373 }
374 UnicodeString string;
375 int8_t firstIndex;
3
'firstIndex' declared without an initial value
376 auto handler = result->getHandler(status);
377 handler.setCategory(UFIELD_CATEGORY_DATE);
378 {
379 Mutex lock(&gFormatterMutex);
380 formatImpl(fromCalendar, toCalendar, string, firstIndex, handler, status);
4
Calling 'DateIntervalFormat::formatImpl'
7
Returning from 'DateIntervalFormat::formatImpl'
381 }
382 handler.getError(status);
383 result->appendString(string, status);
384 if (U_FAILURE(status)) {
8
Taking false branch
385 return FormattedDateInterval(status);
386 }
387
388 // Compute the span fields and sort them into place:
389 if (firstIndex != -1) {
9
The left operand of '!=' is a garbage value
390 result->addOverlapSpans(UFIELD_CATEGORY_DATE_INTERVAL_SPAN, firstIndex, status);
391 result->sort();
392 }
393
394 return FormattedDateInterval(result.orphan());
395}
396
397
398UnicodeString& DateIntervalFormat::formatIntervalImpl(
399 const DateInterval& dtInterval,
400 UnicodeString& appendTo,
401 int8_t& firstIndex,
402 FieldPositionHandler& fphandler,
403 UErrorCode& status) const {
404 if (U_FAILURE(status)) {
405 return appendTo;
406 }
407 if (fFromCalendar == nullptr || fToCalendar == nullptr) {
408 status = U_INVALID_STATE_ERROR;
409 return appendTo;
410 }
411 fFromCalendar->setTime(dtInterval.getFromDate(), status);
412 fToCalendar->setTime(dtInterval.getToDate(), status);
413 return formatImpl(*fFromCalendar, *fToCalendar, appendTo, firstIndex, fphandler, status);
414}
415
416
417// The following is only called from within the gFormatterMutex lock
418UnicodeString&
419DateIntervalFormat::formatImpl(Calendar& fromCalendar,
420 Calendar& toCalendar,
421 UnicodeString& appendTo,
422 int8_t& firstIndex,
423 FieldPositionHandler& fphandler,
424 UErrorCode& status) const {
425 if ( U_FAILURE(status) ) {
5
Taking true branch
426 return appendTo;
6
Returning without writing to 'firstIndex'
427 }
428
429 // Initialize firstIndex to -1 (single date, no range)
430 firstIndex = -1;
431
432 // not support different calendar types and time zones
433 //if ( fromCalendar.getType() != toCalendar.getType() ) {
434 if ( !fromCalendar.isEquivalentTo(toCalendar) ) {
435 status = U_ILLEGAL_ARGUMENT_ERROR;
436 return appendTo;
437 }
438
439 // First, find the largest different calendar field.
440 UCalendarDateFields field = UCAL_FIELD_COUNT;
441
442 if ( fromCalendar.get(UCAL_ERA,status) != toCalendar.get(UCAL_ERA,status)) {
443 field = UCAL_ERA;
444 } else if ( fromCalendar.get(UCAL_YEAR, status) !=
445 toCalendar.get(UCAL_YEAR, status) ) {
446 field = UCAL_YEAR;
447 } else if ( fromCalendar.get(UCAL_MONTH, status) !=
448 toCalendar.get(UCAL_MONTH, status) ) {
449 field = UCAL_MONTH;
450 } else if ( fromCalendar.get(UCAL_DATE, status) !=
451 toCalendar.get(UCAL_DATE, status) ) {
452 field = UCAL_DATE;
453 } else if ( fromCalendar.get(UCAL_AM_PM, status) !=
454 toCalendar.get(UCAL_AM_PM, status) ) {
455 field = UCAL_AM_PM;
456 } else if ( fromCalendar.get(UCAL_HOUR, status) !=
457 toCalendar.get(UCAL_HOUR, status) ) {
458 field = UCAL_HOUR;
459 } else if ( fromCalendar.get(UCAL_MINUTE, status) !=
460 toCalendar.get(UCAL_MINUTE, status) ) {
461 field = UCAL_MINUTE;
462 } else if ( fromCalendar.get(UCAL_SECOND, status) !=
463 toCalendar.get(UCAL_SECOND, status) ) {
464 field = UCAL_SECOND;
465 } else if ( fromCalendar.get(UCAL_MILLISECOND, status) !=
466 toCalendar.get(UCAL_MILLISECOND, status) ) {
467 field = UCAL_MILLISECOND;
468 }
469
470 if ( U_FAILURE(status) ) {
471 return appendTo;
472 }
473 UErrorCode tempStatus = U_ZERO_ERROR; // for setContext, ignored
474 // Set up fDateFormat to handle the first or only part of the interval
475 // (override later for any second part). Inside lock, OK to modify fDateFormat.
476 fDateFormat->setContext(fCapitalizationContext, tempStatus);
477
478 if ( field == UCAL_FIELD_COUNT ) {
479 /* ignore the millisecond etc. small fields' difference.
480 * use single date when all the above are the same.
481 */
482 return fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
483 }
484 UBool fromToOnSameDay = (field==UCAL_AM_PM || field==UCAL_HOUR || field==UCAL_MINUTE || field==UCAL_SECOND || field==UCAL_MILLISECOND);
485
486 // following call should not set wrong status,
487 // all the pass-in fields are valid till here
488 int32_t itvPtnIndex = DateIntervalInfo::calendarFieldToIntervalIndex(field,
489 status);
490 const PatternInfo& intervalPattern = fIntervalPatterns[itvPtnIndex];
491
492 if ( intervalPattern.firstPart.isEmpty() &&
493 intervalPattern.secondPart.isEmpty() ) {
494 if ( fDateFormat->isFieldUnitIgnored(field) ) {
495 /* the largest different calendar field is small than
496 * the smallest calendar field in pattern,
497 * return single date format.
498 */
499 return fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
500 }
501 return fallbackFormat(fromCalendar, toCalendar, fromToOnSameDay, appendTo, firstIndex, fphandler, status);
502 }
503 // If the first part in interval pattern is empty,
504 // the 2nd part of it saves the full-pattern used in fall-back.
505 // For a 'real' interval pattern, the first part will never be empty.
506 if ( intervalPattern.firstPart.isEmpty() ) {
507 // fall back
508 UnicodeString originalPattern;
509 fDateFormat->toPattern(originalPattern);
510 fDateFormat->applyPattern(intervalPattern.secondPart);
511 appendTo = fallbackFormat(fromCalendar, toCalendar, fromToOnSameDay, appendTo, firstIndex, fphandler, status);
512 fDateFormat->applyPattern(originalPattern);
513 return appendTo;
514 }
515 Calendar* firstCal;
516 Calendar* secondCal;
517 if ( intervalPattern.laterDateFirst ) {
518 firstCal = &toCalendar;
519 secondCal = &fromCalendar;
520 firstIndex = 1;
521 } else {
522 firstCal = &fromCalendar;
523 secondCal = &toCalendar;
524 firstIndex = 0;
525 }
526 // break the interval pattern into 2 parts,
527 // first part should not be empty,
528 UnicodeString originalPattern;
529 fDateFormat->toPattern(originalPattern);
530 fDateFormat->applyPattern(intervalPattern.firstPart);
531 fDateFormat->_format(*firstCal, appendTo, fphandler, status);
532
533 if ( !intervalPattern.secondPart.isEmpty() ) {
534 fDateFormat->applyPattern(intervalPattern.secondPart);
535 // No capitalization for second part of interval
536 tempStatus = U_ZERO_ERROR;
537 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
538 fDateFormat->_format(*secondCal, appendTo, fphandler, status);
539 }
540 fDateFormat->applyPattern(originalPattern);
541 return appendTo;
542}
543
544
545
546void
547DateIntervalFormat::parseObject(const UnicodeString& /* source */,
548 Formattable& /* result */,
549 ParsePosition& /* parse_pos */) const {
550 // parseObject(const UnicodeString&, Formattable&, UErrorCode&) const
551 // will set status as U_INVALID_FORMAT_ERROR if
552 // parse_pos is still 0
553}
554
555
556
557
558const DateIntervalInfo*
559DateIntervalFormat::getDateIntervalInfo() const {
560 return fInfo;
561}
562
563
564void
565DateIntervalFormat::setDateIntervalInfo(const DateIntervalInfo& newItvPattern,
566 UErrorCode& status) {
567 delete fInfo;
568 fInfo = new DateIntervalInfo(newItvPattern);
569 if (fInfo == nullptr) {
570 status = U_MEMORY_ALLOCATION_ERROR;
571 }
572
573 // Delete patterns that get reset by initializePattern
574 delete fDatePattern;
575 fDatePattern = nullptr;
576 delete fTimePattern;
577 fTimePattern = nullptr;
578 delete fDateTimeFormat;
579 fDateTimeFormat = nullptr;
580
581 if (fDateFormat) {
582 initializePattern(status);
583 }
584}
585
586
587
588const DateFormat*
589DateIntervalFormat::getDateFormat() const {
590 return fDateFormat;
591}
592
593
594void
595DateIntervalFormat::adoptTimeZone(TimeZone* zone)
596{
597 if (fDateFormat != nullptr) {
598 fDateFormat->adoptTimeZone(zone);
599 }
600 // The fDateFormat has the primary calendar for the DateIntervalFormat and has
601 // ownership of any adopted TimeZone; fFromCalendar and fToCalendar are internal
602 // work clones of that calendar (and should not also be given ownership of the
603 // adopted TimeZone).
604 if (fFromCalendar) {
605 fFromCalendar->setTimeZone(*zone);
606 }
607 if (fToCalendar) {
608 fToCalendar->setTimeZone(*zone);
609 }
610}
611
612void
613DateIntervalFormat::setTimeZone(const TimeZone& zone)
614{
615 if (fDateFormat != nullptr) {
616 fDateFormat->setTimeZone(zone);
617 }
618 // The fDateFormat has the primary calendar for the DateIntervalFormat;
619 // fFromCalendar and fToCalendar are internal work clones of that calendar.
620 if (fFromCalendar) {
621 fFromCalendar->setTimeZone(zone);
622 }
623 if (fToCalendar) {
624 fToCalendar->setTimeZone(zone);
625 }
626}
627
628const TimeZone&
629DateIntervalFormat::getTimeZone() const
630{
631 if (fDateFormat != nullptr) {
632 Mutex lock(&gFormatterMutex);
633 return fDateFormat->getTimeZone();
634 }
635 // If fDateFormat is nullptr (unexpected), create default timezone.
636 return *(TimeZone::createDefault());
637}
638
639void
640DateIntervalFormat::setContext(UDisplayContext value, UErrorCode& status)
641{
642 if (U_FAILURE(status))
643 return;
644 if ( (UDisplayContextType)((uint32_t)value >> 8) == UDISPCTX_TYPE_CAPITALIZATION ) {
645 fCapitalizationContext = value;
646 } else {
647 status = U_ILLEGAL_ARGUMENT_ERROR;
648 }
649}
650
651UDisplayContext
652DateIntervalFormat::getContext(UDisplayContextType type, UErrorCode& status) const
653{
654 if (U_FAILURE(status))
655 return (UDisplayContext)0;
656 if (type != UDISPCTX_TYPE_CAPITALIZATION) {
657 status = U_ILLEGAL_ARGUMENT_ERROR;
658 return (UDisplayContext)0;
659 }
660 return fCapitalizationContext;
661}
662
663DateIntervalFormat::DateIntervalFormat(const Locale& locale,
664 DateIntervalInfo* dtItvInfo,
665 const UnicodeString* skeleton,
666 UErrorCode& status)
667: fInfo(nullptr),
668 fDateFormat(nullptr),
669 fFromCalendar(nullptr),
670 fToCalendar(nullptr),
671 fLocale(locale),
672 fDatePattern(nullptr),
673 fTimePattern(nullptr),
674 fDateTimeFormat(nullptr),
675 fCapitalizationContext(UDISPCTX_CAPITALIZATION_NONE)
676{
677 LocalPointer<DateIntervalInfo> info(dtItvInfo, status);
678 LocalPointer<SimpleDateFormat> dtfmt(static_cast<SimpleDateFormat *>(
679 DateFormat::createInstanceForSkeleton(*skeleton, locale, status)), status);
680 if (U_FAILURE(status)) {
681 return;
682 }
683
684 if ( skeleton ) {
685 fSkeleton = *skeleton;
686 }
687 fInfo = info.orphan();
688 fDateFormat = dtfmt.orphan();
689 if ( fDateFormat->getCalendar() ) {
690 fFromCalendar = fDateFormat->getCalendar()->clone();
691 fToCalendar = fDateFormat->getCalendar()->clone();
692 }
693 initializePattern(status);
694}
695
696DateIntervalFormat* U_EXPORT2
697DateIntervalFormat::create(const Locale& locale,
698 DateIntervalInfo* dtitvinf,
699 const UnicodeString* skeleton,
700 UErrorCode& status) {
701 DateIntervalFormat* f = new DateIntervalFormat(locale, dtitvinf,
702 skeleton, status);
703 if ( f == nullptr ) {
704 status = U_MEMORY_ALLOCATION_ERROR;
705 delete dtitvinf;
706 } else if ( U_FAILURE(status) ) {
707 // safe to delete f, although nothing actually is saved
708 delete f;
709 f = 0;
710 }
711 return f;
712}
713
714
715
716/**
717 * Initialize interval patterns locale to this formatter
718 *
719 * This code is a bit complicated since
720 * 1. the interval patterns saved in resource bundle files are interval
721 * patterns based on date or time only.
722 * It does not have interval patterns based on both date and time.
723 * Interval patterns on both date and time are algorithm generated.
724 *
725 * For example, it has interval patterns on skeleton "dMy" and "hm",
726 * but it does not have interval patterns on skeleton "dMyhm".
727 *
728 * The rule to genearte interval patterns for both date and time skeleton are
729 * 1) when the year, month, or day differs, concatenate the two original
730 * expressions with a separator between,
731 * For example, interval pattern from "Jan 10, 2007 10:10 am"
732 * to "Jan 11, 2007 10:10am" is
733 * "Jan 10, 2007 10:10 am - Jan 11, 2007 10:10am"
734 *
735 * 2) otherwise, present the date followed by the range expression
736 * for the time.
737 * For example, interval pattern from "Jan 10, 2007 10:10 am"
738 * to "Jan 10, 2007 11:10am" is
739 * "Jan 10, 2007 10:10 am - 11:10am"
740 *
741 * 2. even a pattern does not request a certion calendar field,
742 * the interval pattern needs to include such field if such fields are
743 * different between 2 dates.
744 * For example, a pattern/skeleton is "hm", but the interval pattern
745 * includes year, month, and date when year, month, and date differs.
746 *
747 * @param status output param set to success/failure code on exit
748 * @stable ICU 4.0
749 */
750void
751DateIntervalFormat::initializePattern(UErrorCode& status) {
752 if ( U_FAILURE(status) ) {
753 return;
754 }
755 const Locale& locale = fDateFormat->getSmpFmtLocale();
756 if ( fSkeleton.isEmpty() ) {
757 UnicodeString fullPattern;
758 fDateFormat->toPattern(fullPattern);
759#ifdef DTITVFMT_DEBUG
760 char result[1000];
761 char result_1[1000];
762 char mesg[2000];
763 fSkeleton.extract(0, fSkeleton.length(), result, "UTF-8");
764 sprintf(mesg, "in getBestSkeleton: fSkeleton: %s; \n", result);
765 PRINTMESG(mesg)
766#endif
767 // fSkeleton is already set by createDateIntervalInstance()
768 // or by createInstance(UnicodeString skeleton, .... )
769 fSkeleton = DateTimePatternGenerator::staticGetSkeleton(
770 fullPattern, status);
771 if ( U_FAILURE(status) ) {
772 return;
773 }
774 }
775
776 // initialize the fIntervalPattern ordering
777 int8_t i;
778 for ( i = 0; i < DateIntervalInfo::kIPI_MAX_INDEX; ++i ) {
779 fIntervalPatterns[i].laterDateFirst = fInfo->getDefaultOrder();
780 }
781
782 /* Check whether the skeleton is a combination of date and time.
783 * For the complication reason 1 explained above.
784 */
785 UnicodeString dateSkeleton;
786 UnicodeString timeSkeleton;
787 UnicodeString normalizedTimeSkeleton;
788 UnicodeString normalizedDateSkeleton;
789
790
791 /* the difference between time skeleton and normalizedTimeSkeleton are:
792 * 1. (Formerly, normalized time skeleton folded 'H' to 'h'; no longer true)
793 * 2. (Formerly, 'a' was omitted in normalized time skeleton; this is now handled elsewhere)
794 * 3. there is only one appearance for 'h' or 'H', 'm','v', 'z' in normalized
795 * time skeleton
796 *
797 * The difference between date skeleton and normalizedDateSkeleton are:
798 * 1. both 'y' and 'd' appear only once in normalizeDateSkeleton
799 * 2. 'E' and 'EE' are normalized into 'EEE'
800 * 3. 'MM' is normalized into 'M'
801 */
802 UnicodeString convertedSkeleton = normalizeHourMetacharacters(fSkeleton);
803 getDateTimeSkeleton(convertedSkeleton, dateSkeleton, normalizedDateSkeleton,
804 timeSkeleton, normalizedTimeSkeleton);
805
806#ifdef DTITVFMT_DEBUG
807 char result[1000];
808 char result_1[1000];
809 char mesg[2000];
810 fSkeleton.extract(0, fSkeleton.length(), result, "UTF-8");
811 sprintf(mesg, "in getBestSkeleton: fSkeleton: %s; \n", result);
812 PRINTMESG(mesg)
813#endif
814
815 // move this up here since we need it for fallbacks
816 if ( timeSkeleton.length() > 0 && dateSkeleton.length() > 0 ) {
817 // Need the Date/Time pattern for concatenation of the date
818 // with the time interval.
819 // The date/time pattern ( such as {0} {1} ) is saved in
820 // calendar, that is why need to get the CalendarData here.
821 LocalUResourceBundlePointer dateTimePatternsRes(ures_openures_open_71(nullptr, locale.getBaseName(), &status));
822 ures_getByKeyures_getByKey_71(dateTimePatternsRes.getAlias(), gCalendarTag,
823 dateTimePatternsRes.getAlias(), &status);
824 ures_getByKeyWithFallbackures_getByKeyWithFallback_71(dateTimePatternsRes.getAlias(), gGregorianTag,
825 dateTimePatternsRes.getAlias(), &status);
826 ures_getByKeyWithFallbackures_getByKeyWithFallback_71(dateTimePatternsRes.getAlias(), gDateTimePatternsTag,
827 dateTimePatternsRes.getAlias(), &status);
828
829 int32_t dateTimeFormatLength;
830 const UChar* dateTimeFormat = ures_getStringByIndexures_getStringByIndex_71(
831 dateTimePatternsRes.getAlias(),
832 (int32_t)DateFormat::kDateTime,
833 &dateTimeFormatLength, &status);
834 if ( U_SUCCESS(status) && dateTimeFormatLength >= 3 ) {
835 fDateTimeFormat = new UnicodeString(dateTimeFormat, dateTimeFormatLength);
836 if (fDateTimeFormat == nullptr) {
837 status = U_MEMORY_ALLOCATION_ERROR;
838 return;
839 }
840 }
841 }
842
843 UBool found = setSeparateDateTimePtn(normalizedDateSkeleton,
844 normalizedTimeSkeleton);
845
846 // for skeletons with seconds, found is false and we enter this block
847 if ( found == false ) {
848 // use fallback
849 // TODO: if user asks "m"(minute), but "d"(day) differ
850 if ( timeSkeleton.length() != 0 ) {
851 if ( dateSkeleton.length() == 0 ) {
852 // prefix with yMd
853 timeSkeleton.insert(0, gDateFormatSkeleton[DateFormat::kShort], -1);
854 UnicodeString pattern = DateFormat::getBestPattern(
855 locale, timeSkeleton, status);
856 if ( U_FAILURE(status) ) {
857 return;
858 }
859 // for fall back interval patterns,
860 // the first part of the pattern is empty,
861 // the second part of the pattern is the full-pattern
862 // should be used in fall-back.
863 setPatternInfo(UCAL_DATE, nullptr, &pattern, fInfo->getDefaultOrder());
864 setPatternInfo(UCAL_MONTH, nullptr, &pattern, fInfo->getDefaultOrder());
865 setPatternInfo(UCAL_YEAR, nullptr, &pattern, fInfo->getDefaultOrder());
866
867 timeSkeleton.insert(0, CAP_G((UChar)0x0047));
868 pattern = DateFormat::getBestPattern(
869 locale, timeSkeleton, status);
870 if ( U_FAILURE(status) ) {
871 return;
872 }
873 setPatternInfo(UCAL_ERA, nullptr, &pattern, fInfo->getDefaultOrder());
874 } else {
875 // TODO: fall back
876 }
877 } else {
878 // TODO: fall back
879 }
880 return;
881 } // end of skeleton not found
882 // interval patterns for skeleton are found in resource
883 if ( timeSkeleton.length() == 0 ) {
884 // done
885 } else if ( dateSkeleton.length() == 0 ) {
886 // prefix with yMd
887 timeSkeleton.insert(0, gDateFormatSkeleton[DateFormat::kShort], -1);
888 UnicodeString pattern = DateFormat::getBestPattern(
889 locale, timeSkeleton, status);
890 if ( U_FAILURE(status) ) {
891 return;
892 }
893 // for fall back interval patterns,
894 // the first part of the pattern is empty,
895 // the second part of the pattern is the full-pattern
896 // should be used in fall-back.
897 setPatternInfo(UCAL_DATE, nullptr, &pattern, fInfo->getDefaultOrder());
898 setPatternInfo(UCAL_MONTH, nullptr, &pattern, fInfo->getDefaultOrder());
899 setPatternInfo(UCAL_YEAR, nullptr, &pattern, fInfo->getDefaultOrder());
900
901 timeSkeleton.insert(0, CAP_G((UChar)0x0047));
902 pattern = DateFormat::getBestPattern(
903 locale, timeSkeleton, status);
904 if ( U_FAILURE(status) ) {
905 return;
906 }
907 setPatternInfo(UCAL_ERA, nullptr, &pattern, fInfo->getDefaultOrder());
908 } else {
909 /* if both present,
910 * 1) when the era, year, month, or day differs,
911 * concatenate the two original expressions with a separator between,
912 * 2) otherwise, present the date followed by the
913 * range expression for the time.
914 */
915 /*
916 * 1) when the era, year, month, or day differs,
917 * concatenate the two original expressions with a separator between,
918 */
919 // if field exists, use fall back
920 UnicodeString skeleton = fSkeleton;
921 if ( !fieldExistsInSkeleton(UCAL_DATE, dateSkeleton) ) {
922 // prefix skeleton with 'd'
923 skeleton.insert(0, LOW_D((UChar)0x0064));
924 setFallbackPattern(UCAL_DATE, skeleton, status);
925 }
926 if ( !fieldExistsInSkeleton(UCAL_MONTH, dateSkeleton) ) {
927 // then prefix skeleton with 'M'
928 skeleton.insert(0, CAP_M((UChar)0x004D));
929 setFallbackPattern(UCAL_MONTH, skeleton, status);
930 }
931 if ( !fieldExistsInSkeleton(UCAL_YEAR, dateSkeleton) ) {
932 // then prefix skeleton with 'y'
933 skeleton.insert(0, LOW_Y((UChar)0x0079));
934 setFallbackPattern(UCAL_YEAR, skeleton, status);
935 }
936 if ( !fieldExistsInSkeleton(UCAL_ERA, dateSkeleton) ) {
937 // then prefix skeleton with 'G'
938 skeleton.insert(0, CAP_G((UChar)0x0047));
939 setFallbackPattern(UCAL_ERA, skeleton, status);
940 }
941
942 /*
943 * 2) otherwise, present the date followed by the
944 * range expression for the time.
945 */
946
947 if ( fDateTimeFormat == nullptr ) {
948 // earlier failure getting dateTimeFormat
949 return;
950 }
951
952 UnicodeString datePattern = DateFormat::getBestPattern(
953 locale, dateSkeleton, status);
954
955 concatSingleDate2TimeInterval(*fDateTimeFormat, datePattern, UCAL_AM_PM, status);
956 concatSingleDate2TimeInterval(*fDateTimeFormat, datePattern, UCAL_HOUR, status);
957 concatSingleDate2TimeInterval(*fDateTimeFormat, datePattern, UCAL_MINUTE, status);
958 }
959}
960
961
962
963UnicodeString
964DateIntervalFormat::normalizeHourMetacharacters(const UnicodeString& skeleton) const {
965 UnicodeString result = skeleton;
966
967 UChar hourMetachar = u'\0';
968 UChar dayPeriodChar = u'\0';
969 int32_t metacharStart = 0;
970 int32_t metacharCount = 0;
971 for (int32_t i = 0; i < result.length(); i++) {
972 UChar c = result[i];
973 if (c == LOW_J((UChar)0x006a) || c == CAP_J((UChar)0x004A) || c == CAP_C((UChar)0x0043) || c == LOW_H((UChar)0x0068) || c == CAP_H((UChar)0x0048) || c == LOW_K((UChar)0x006B) || c == CAP_K((UChar)0x004B)) {
974 if (hourMetachar == u'\0') {
975 hourMetachar = c;
976 metacharStart = i;
977 }
978 ++metacharCount;
979 } else if (c == LOW_A((UChar)0x0061) || c == LOW_B((UChar)0x0062) || c == CAP_B((UChar)0x0042)) {
980 if (dayPeriodChar == u'\0') {
981 dayPeriodChar = c;
982 }
983 ++metacharCount;
984 } else {
985 if (hourMetachar != u'\0') {
986 break;
987 }
988 }
989 }
990
991 if (hourMetachar != u'\0') {
992 UErrorCode err = U_ZERO_ERROR;
993 UChar hourChar = CAP_H((UChar)0x0048);
994 UnicodeString convertedPattern = DateFormat::getBestPattern(fLocale, UnicodeString(hourMetachar), err);
995
996 if (U_SUCCESS(err)) {
997 // strip literal text from the pattern (so literal characters don't get mistaken for pattern
998 // characters-- such as the 'h' in 'Uhr' in Germam)
999 int32_t firstQuotePos;
1000 while ((firstQuotePos = convertedPattern.indexOf(u'\'')) != -1) {
1001 int32_t secondQuotePos = convertedPattern.indexOf(u'\'', firstQuotePos + 1);
1002 if (secondQuotePos == -1) {
1003 secondQuotePos = firstQuotePos;
1004 }
1005 convertedPattern.replace(firstQuotePos, (secondQuotePos - firstQuotePos) + 1, UnicodeString());
1006 }
1007
1008 if (convertedPattern.indexOf(LOW_H((UChar)0x0068)) != -1) {
1009 hourChar = LOW_H((UChar)0x0068);
1010 } else if (convertedPattern.indexOf(CAP_K((UChar)0x004B)) != -1) {
1011 hourChar = CAP_K((UChar)0x004B);
1012 } else if (convertedPattern.indexOf(LOW_K((UChar)0x006B)) != -1) {
1013 hourChar = LOW_K((UChar)0x006B);
1014 }
1015
1016 if (convertedPattern.indexOf(LOW_B((UChar)0x0062)) != -1) {
1017 dayPeriodChar = LOW_B((UChar)0x0062);
1018 } else if (convertedPattern.indexOf(CAP_B((UChar)0x0042)) != -1) {
1019 dayPeriodChar = CAP_B((UChar)0x0042);
1020 } else if (dayPeriodChar == u'\0') {
1021 dayPeriodChar = LOW_A((UChar)0x0061);
1022 }
1023 }
1024
1025 if (hourChar == CAP_H((UChar)0x0048) || hourChar == LOW_K((UChar)0x006B)) {
1026 result.replace(metacharStart, metacharCount, hourChar);
1027 } else {
1028 UnicodeString hourAndDayPeriod(hourChar);
1029 switch (metacharCount) {
1030 case 1:
1031 case 2:
1032 default:
1033 hourAndDayPeriod.append(UnicodeString(dayPeriodChar));
1034 break;
1035 case 3:
1036 case 4:
1037 for (int32_t i = 0; i < 4; i++) {
1038 hourAndDayPeriod.append(dayPeriodChar);
1039 }
1040 break;
1041 case 5:
1042 case 6:
1043 for (int32_t i = 0; i < 5; i++) {
1044 hourAndDayPeriod.append(dayPeriodChar);
1045 }
1046 break;
1047 }
1048 result.replace(metacharStart, metacharCount, hourAndDayPeriod);
1049 }
1050 }
1051 return result;
1052}
1053
1054
1055void U_EXPORT2
1056DateIntervalFormat::getDateTimeSkeleton(const UnicodeString& skeleton,
1057 UnicodeString& dateSkeleton,
1058 UnicodeString& normalizedDateSkeleton,
1059 UnicodeString& timeSkeleton,
1060 UnicodeString& normalizedTimeSkeleton) {
1061 // dateSkeleton follows the sequence of y*M*E*d*
1062 // timeSkeleton follows the sequence of hm*[v|z]?
1063 int32_t ECount = 0;
1064 int32_t dCount = 0;
1065 int32_t MCount = 0;
1066 int32_t yCount = 0;
1067 int32_t mCount = 0;
1068 int32_t vCount = 0;
1069 int32_t zCount = 0;
1070 UChar hourChar = u'\0';
1071 int32_t i;
1072
1073 for (i = 0; i < skeleton.length(); ++i) {
1074 UChar ch = skeleton[i];
1075 switch ( ch ) {
1076 case CAP_E((UChar)0x0045):
1077 dateSkeleton.append(ch);
1078 ++ECount;
1079 break;
1080 case LOW_D((UChar)0x0064):
1081 dateSkeleton.append(ch);
1082 ++dCount;
1083 break;
1084 case CAP_M((UChar)0x004D):
1085 dateSkeleton.append(ch);
1086 ++MCount;
1087 break;
1088 case LOW_Y((UChar)0x0079):
1089 dateSkeleton.append(ch);
1090 ++yCount;
1091 break;
1092 case CAP_G((UChar)0x0047):
1093 case CAP_Y((UChar)0x0059):
1094 case LOW_U((UChar)0x0075):
1095 case CAP_Q((UChar)0x0051):
1096 case LOW_Q((UChar)0x0071):
1097 case CAP_L((UChar)0x004C):
1098 case LOW_L((UChar)0x006C):
1099 case CAP_W((UChar)0x0057):
1100 case LOW_W((UChar)0x0077):
1101 case CAP_D((UChar)0x0044):
1102 case CAP_F((UChar)0x0046):
1103 case LOW_G((UChar)0x0067):
1104 case LOW_E((UChar)0x0065):
1105 case LOW_C((UChar)0x0063):
1106 case CAP_U((UChar)0x0055):
1107 case LOW_R((UChar)0x0072):
1108 normalizedDateSkeleton.append(ch);
1109 dateSkeleton.append(ch);
1110 break;
1111 case LOW_H((UChar)0x0068):
1112 case CAP_H((UChar)0x0048):
1113 case LOW_K((UChar)0x006B):
1114 case CAP_K((UChar)0x004B):
1115 timeSkeleton.append(ch);
1116 if (hourChar == u'\0') {
1117 hourChar = ch;
1118 }
1119 break;
1120 case LOW_M((UChar)0x006D):
1121 timeSkeleton.append(ch);
1122 ++mCount;
1123 break;
1124 case LOW_Z((UChar)0x007A):
1125 ++zCount;
1126 timeSkeleton.append(ch);
1127 break;
1128 case LOW_V((UChar)0x0076):
1129 ++vCount;
1130 timeSkeleton.append(ch);
1131 break;
1132 case LOW_A((UChar)0x0061):
1133 case CAP_V((UChar)0x0056):
1134 case CAP_Z((UChar)0x005A):
1135 case LOW_J((UChar)0x006a):
1136 case LOW_S((UChar)0x0073):
1137 case CAP_S((UChar)0x0053):
1138 case CAP_A((UChar)0x0041):
1139 case LOW_B((UChar)0x0062):
1140 case CAP_B((UChar)0x0042):
1141 timeSkeleton.append(ch);
1142 normalizedTimeSkeleton.append(ch);
1143 break;
1144 }
1145 }
1146
1147 /* generate normalized form for date*/
1148 if ( yCount != 0 ) {
1149 for (i = 0; i < yCount; ++i) {
1150 normalizedDateSkeleton.append(LOW_Y((UChar)0x0079));
1151 }
1152 }
1153 if ( MCount != 0 ) {
1154 if ( MCount < 3 ) {
1155 normalizedDateSkeleton.append(CAP_M((UChar)0x004D));
1156 } else {
1157 for ( int32_t j = 0; j < MCount && j < MAX_M_COUNT5; ++j) {
1158 normalizedDateSkeleton.append(CAP_M((UChar)0x004D));
1159 }
1160 }
1161 }
1162 if ( ECount != 0 ) {
1163 if ( ECount <= 3 ) {
1164 normalizedDateSkeleton.append(CAP_E((UChar)0x0045));
1165 } else {
1166 for ( int32_t j = 0; j < ECount && j < MAX_E_COUNT5; ++j ) {
1167 normalizedDateSkeleton.append(CAP_E((UChar)0x0045));
1168 }
1169 }
1170 }
1171 if ( dCount != 0 ) {
1172 normalizedDateSkeleton.append(LOW_D((UChar)0x0064));
1173 }
1174
1175 /* generate normalized form for time */
1176 if ( hourChar != u'\0' ) {
1177 normalizedTimeSkeleton.append(hourChar);
1178 }
1179 if ( mCount != 0 ) {
1180 normalizedTimeSkeleton.append(LOW_M((UChar)0x006D));
1181 }
1182 if ( zCount != 0 ) {
1183 normalizedTimeSkeleton.append(LOW_Z((UChar)0x007A));
1184 }
1185 if ( vCount != 0 ) {
1186 normalizedTimeSkeleton.append(LOW_V((UChar)0x0076));
1187 }
1188}
1189
1190
1191/**
1192 * Generate date or time interval pattern from resource,
1193 * and set them into the interval pattern locale to this formatter.
1194 *
1195 * It needs to handle the following:
1196 * 1. need to adjust field width.
1197 * For example, the interval patterns saved in DateIntervalInfo
1198 * includes "dMMMy", but not "dMMMMy".
1199 * Need to get interval patterns for dMMMMy from dMMMy.
1200 * Another example, the interval patterns saved in DateIntervalInfo
1201 * includes "hmv", but not "hmz".
1202 * Need to get interval patterns for "hmz' from 'hmv'
1203 *
1204 * 2. there might be no pattern for 'y' differ for skeleton "Md",
1205 * in order to get interval patterns for 'y' differ,
1206 * need to look for it from skeleton 'yMd'
1207 *
1208 * @param dateSkeleton normalized date skeleton
1209 * @param timeSkeleton normalized time skeleton
1210 * @return whether the resource is found for the skeleton.
1211 * TRUE if interval pattern found for the skeleton,
1212 * FALSE otherwise.
1213 * @stable ICU 4.0
1214 */
1215UBool
1216DateIntervalFormat::setSeparateDateTimePtn(
1217 const UnicodeString& dateSkeleton,
1218 const UnicodeString& timeSkeleton) {
1219 const UnicodeString* skeleton;
1220 // if both date and time skeleton present,
1221 // the final interval pattern might include time interval patterns
1222 // ( when, am_pm, hour, minute differ ),
1223 // but not date interval patterns ( when year, month, day differ ).
1224 // For year/month/day differ, it falls back to fall-back pattern.
1225 if ( timeSkeleton.length() != 0 ) {
1226 skeleton = &timeSkeleton;
1227 } else {
1228 skeleton = &dateSkeleton;
1229 }
1230
1231 /* interval patterns for skeleton "dMMMy" (but not "dMMMMy")
1232 * are defined in resource,
1233 * interval patterns for skeleton "dMMMMy" are calculated by
1234 * 1. get the best match skeleton for "dMMMMy", which is "dMMMy"
1235 * 2. get the interval patterns for "dMMMy",
1236 * 3. extend "MMM" to "MMMM" in above interval patterns for "dMMMMy"
1237 * getBestSkeleton() is step 1.
1238 */
1239 // best skeleton, and the difference information
1240 int8_t differenceInfo = 0;
1241 const UnicodeString* bestSkeleton = fInfo->getBestSkeleton(*skeleton,
1242 differenceInfo);
1243 /* best skeleton could be nullptr.
1244 For example: in "ca" resource file,
1245 interval format is defined as following
1246 intervalFormats{
1247 fallback{"{0} - {1}"}
1248 }
1249 there is no skeletons/interval patterns defined,
1250 and the best skeleton match could be nullptr
1251 */
1252 if ( bestSkeleton == nullptr ) {
1253 return false;
1254 }
1255
1256 // Set patterns for fallback use, need to do this
1257 // before returning if differenceInfo == -1
1258 UErrorCode status;
1259 if ( dateSkeleton.length() != 0) {
1260 status = U_ZERO_ERROR;
1261 fDatePattern = new UnicodeString(DateFormat::getBestPattern(
1262 fLocale, dateSkeleton, status));
1263 // no way to report OOM. :(
1264 }
1265 if ( timeSkeleton.length() != 0) {
1266 status = U_ZERO_ERROR;
1267 fTimePattern = new UnicodeString(DateFormat::getBestPattern(
1268 fLocale, timeSkeleton, status));
1269 // no way to report OOM. :(
1270 }
1271
1272 // difference:
1273 // 0 means the best matched skeleton is the same as input skeleton
1274 // 1 means the fields are the same, but field width are different
1275 // 2 means the only difference between fields are v/z,
1276 // -1 means there are other fields difference
1277 // (this will happen, for instance, if the supplied skeleton has seconds,
1278 // but no skeletons in the intervalFormats data do)
1279 if ( differenceInfo == -1 ) {
1280 // skeleton has different fields, not only v/z difference
1281 return false;
1282 }
1283
1284 if ( timeSkeleton.length() == 0 ) {
1285 UnicodeString extendedSkeleton;
1286 UnicodeString extendedBestSkeleton;
1287 // only has date skeleton
1288 setIntervalPattern(UCAL_DATE, skeleton, bestSkeleton, differenceInfo,
1289 &extendedSkeleton, &extendedBestSkeleton);
1290
1291 UBool extended = setIntervalPattern(UCAL_MONTH, skeleton, bestSkeleton,
1292 differenceInfo,
1293 &extendedSkeleton, &extendedBestSkeleton);
1294
1295 if ( extended ) {
1296 bestSkeleton = &extendedBestSkeleton;
1297 skeleton = &extendedSkeleton;
1298 }
1299 setIntervalPattern(UCAL_YEAR, skeleton, bestSkeleton, differenceInfo,
1300 &extendedSkeleton, &extendedBestSkeleton);
1301 setIntervalPattern(UCAL_ERA, skeleton, bestSkeleton, differenceInfo,
1302 &extendedSkeleton, &extendedBestSkeleton);
1303 } else {
1304 setIntervalPattern(UCAL_MINUTE, skeleton, bestSkeleton, differenceInfo);
1305 setIntervalPattern(UCAL_HOUR, skeleton, bestSkeleton, differenceInfo);
1306 setIntervalPattern(UCAL_AM_PM, skeleton, bestSkeleton, differenceInfo);
1307 }
1308 return true;
1309}
1310
1311
1312
1313void
1314DateIntervalFormat::setFallbackPattern(UCalendarDateFields field,
1315 const UnicodeString& skeleton,
1316 UErrorCode& status) {
1317 if ( U_FAILURE(status) ) {
1318 return;
1319 }
1320 UnicodeString pattern = DateFormat::getBestPattern(
1321 fLocale, skeleton, status);
1322 if ( U_FAILURE(status) ) {
1323 return;
1324 }
1325 setPatternInfo(field, nullptr, &pattern, fInfo->getDefaultOrder());
1326}
1327
1328
1329
1330
1331void
1332DateIntervalFormat::setPatternInfo(UCalendarDateFields field,
1333 const UnicodeString* firstPart,
1334 const UnicodeString* secondPart,
1335 UBool laterDateFirst) {
1336 // for fall back interval patterns,
1337 // the first part of the pattern is empty,
1338 // the second part of the pattern is the full-pattern
1339 // should be used in fall-back.
1340 UErrorCode status = U_ZERO_ERROR;
1341 // following should not set any wrong status.
1342 int32_t itvPtnIndex = DateIntervalInfo::calendarFieldToIntervalIndex(field,
1343 status);
1344 if ( U_FAILURE(status) ) {
1345 return;
1346 }
1347 PatternInfo& ptn = fIntervalPatterns[itvPtnIndex];
1348 if ( firstPart ) {
1349 ptn.firstPart = *firstPart;
1350 }
1351 if ( secondPart ) {
1352 ptn.secondPart = *secondPart;
1353 }
1354 ptn.laterDateFirst = laterDateFirst;
1355}
1356
1357void
1358DateIntervalFormat::setIntervalPattern(UCalendarDateFields field,
1359 const UnicodeString& intervalPattern) {
1360 UBool order = fInfo->getDefaultOrder();
1361 setIntervalPattern(field, intervalPattern, order);
1362}
1363
1364
1365void
1366DateIntervalFormat::setIntervalPattern(UCalendarDateFields field,
1367 const UnicodeString& intervalPattern,
1368 UBool laterDateFirst) {
1369 const UnicodeString* pattern = &intervalPattern;
1370 UBool order = laterDateFirst;
1371 // check for "latestFirst:" or "earliestFirst:" prefix
1372 int8_t prefixLength = UPRV_LENGTHOF(gLaterFirstPrefix)(int32_t)(sizeof(gLaterFirstPrefix)/sizeof((gLaterFirstPrefix
)[0]))
;
1373 int8_t earliestFirstLength = UPRV_LENGTHOF(gEarlierFirstPrefix)(int32_t)(sizeof(gEarlierFirstPrefix)/sizeof((gEarlierFirstPrefix
)[0]))
;
1374 UnicodeString realPattern;
1375 if ( intervalPattern.startsWith(gLaterFirstPrefix, prefixLength) ) {
1376 order = true;
1377 intervalPattern.extract(prefixLength,
1378 intervalPattern.length() - prefixLength,
1379 realPattern);
1380 pattern = &realPattern;
1381 } else if ( intervalPattern.startsWith(gEarlierFirstPrefix,
1382 earliestFirstLength) ) {
1383 order = false;
1384 intervalPattern.extract(earliestFirstLength,
1385 intervalPattern.length() - earliestFirstLength,
1386 realPattern);
1387 pattern = &realPattern;
1388 }
1389
1390 int32_t splitPoint = splitPatternInto2Part(*pattern);
1391
1392 UnicodeString firstPart;
1393 UnicodeString secondPart;
1394 pattern->extract(0, splitPoint, firstPart);
1395 if ( splitPoint < pattern->length() ) {
1396 pattern->extract(splitPoint, pattern->length()-splitPoint, secondPart);
1397 }
1398 setPatternInfo(field, &firstPart, &secondPart, order);
1399}
1400
1401
1402
1403
1404/**
1405 * Generate interval pattern from existing resource
1406 *
1407 * It not only save the interval patterns,
1408 * but also return the extended skeleton and its best match skeleton.
1409 *
1410 * @param field largest different calendar field
1411 * @param skeleton skeleton
1412 * @param bestSkeleton the best match skeleton which has interval pattern
1413 * defined in resource
1414 * @param differenceInfo the difference between skeleton and best skeleton
1415 * 0 means the best matched skeleton is the same as input skeleton
1416 * 1 means the fields are the same, but field width are different
1417 * 2 means the only difference between fields are v/z,
1418 * -1 means there are other fields difference
1419 *
1420 * @param extendedSkeleton extended skeleton
1421 * @param extendedBestSkeleton extended best match skeleton
1422 * @return whether the interval pattern is found
1423 * through extending skeleton or not.
1424 * TRUE if interval pattern is found by
1425 * extending skeleton, FALSE otherwise.
1426 * @stable ICU 4.0
1427 */
1428UBool
1429DateIntervalFormat::setIntervalPattern(UCalendarDateFields field,
1430 const UnicodeString* skeleton,
1431 const UnicodeString* bestSkeleton,
1432 int8_t differenceInfo,
1433 UnicodeString* extendedSkeleton,
1434 UnicodeString* extendedBestSkeleton) {
1435 UErrorCode status = U_ZERO_ERROR;
1436 // following getIntervalPattern() should not generate error status
1437 UnicodeString pattern;
1438 fInfo->getIntervalPattern(*bestSkeleton, field, pattern, status);
1439 if ( pattern.isEmpty() ) {
1440 // single date
1441 if ( SimpleDateFormat::isFieldUnitIgnored(*bestSkeleton, field) ) {
1442 // do nothing, format will handle it
1443 return false;
1444 }
1445
1446 // for 24 hour system, interval patterns in resource file
1447 // might not include pattern when am_pm differ,
1448 // which should be the same as hour differ.
1449 // add it here for simplicity
1450 if ( field == UCAL_AM_PM ) {
1451 fInfo->getIntervalPattern(*bestSkeleton, UCAL_HOUR, pattern,status);
1452 if ( !pattern.isEmpty() ) {
1453 UBool suppressDayPeriodField = fSkeleton.indexOf(CAP_J((UChar)0x004A)) != -1;
1454 UnicodeString adjustIntervalPattern;
1455 adjustFieldWidth(*skeleton, *bestSkeleton, pattern, differenceInfo,
1456 suppressDayPeriodField, adjustIntervalPattern);
1457 setIntervalPattern(field, adjustIntervalPattern);
1458 }
1459 return false;
1460 }
1461 // else, looking for pattern when 'y' differ for 'dMMMM' skeleton,
1462 // first, get best match pattern "MMMd",
1463 // since there is no pattern for 'y' differs for skeleton 'MMMd',
1464 // need to look for it from skeleton 'yMMMd',
1465 // if found, adjust field width in interval pattern from
1466 // "MMM" to "MMMM".
1467 UChar fieldLetter = fgCalendarFieldToPatternLetter[field];
1468 if ( extendedSkeleton ) {
1469 *extendedSkeleton = *skeleton;
1470 *extendedBestSkeleton = *bestSkeleton;
1471 extendedSkeleton->insert(0, fieldLetter);
1472 extendedBestSkeleton->insert(0, fieldLetter);
1473 // for example, looking for patterns when 'y' differ for
1474 // skeleton "MMMM".
1475 fInfo->getIntervalPattern(*extendedBestSkeleton,field,pattern,status);
1476 if ( pattern.isEmpty() && differenceInfo == 0 ) {
1477 // if there is no skeleton "yMMMM" defined,
1478 // look for the best match skeleton, for example: "yMMM"
1479 const UnicodeString* tmpBest = fInfo->getBestSkeleton(
1480 *extendedBestSkeleton, differenceInfo);
1481 if ( tmpBest != 0 && differenceInfo != -1 ) {
1482 fInfo->getIntervalPattern(*tmpBest, field, pattern, status);
1483 bestSkeleton = tmpBest;
1484 }
1485 }
1486 }
1487 }
1488 if ( !pattern.isEmpty() ) {
1489 UBool suppressDayPeriodField = fSkeleton.indexOf(CAP_J((UChar)0x004A)) != -1;
1490 if ( differenceInfo != 0 || suppressDayPeriodField) {
1491 UnicodeString adjustIntervalPattern;
1492 adjustFieldWidth(*skeleton, *bestSkeleton, pattern, differenceInfo,
1493 suppressDayPeriodField, adjustIntervalPattern);
1494 setIntervalPattern(field, adjustIntervalPattern);
1495 } else {
1496 setIntervalPattern(field, pattern);
1497 }
1498 if ( extendedSkeleton && !extendedSkeleton->isEmpty() ) {
1499 return TRUE1;
1500 }
1501 }
1502 return FALSE0;
1503}
1504
1505
1506
1507int32_t U_EXPORT2
1508DateIntervalFormat::splitPatternInto2Part(const UnicodeString& intervalPattern) {
1509 UBool inQuote = false;
1510 UChar prevCh = 0;
1511 int32_t count = 0;
1512
1513 /* repeatedPattern used to record whether a pattern has already seen.
1514 It is a pattern applies to first calendar if it is first time seen,
1515 otherwise, it is a pattern applies to the second calendar
1516 */
1517 UBool patternRepeated[] =
1518 {
1519 // A B C D E F G H I J K L M N O
1520 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1521 // P Q R S T U V W X Y Z
1522 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1523 // a b c d e f g h i j k l m n o
1524 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1525 // p q r s t u v w x y z
1526 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1527 };
1528
1529 int8_t PATTERN_CHAR_BASE = 0x41;
1530
1531 /* loop through the pattern string character by character looking for
1532 * the first repeated pattern letter, which breaks the interval pattern
1533 * into 2 parts.
1534 */
1535 int32_t i;
1536 UBool foundRepetition = false;
1537 for (i = 0; i < intervalPattern.length(); ++i) {
1538 UChar ch = intervalPattern.charAt(i);
1539
1540 if (ch != prevCh && count > 0) {
1541 // check the repeativeness of pattern letter
1542 UBool repeated = patternRepeated[(int)(prevCh - PATTERN_CHAR_BASE)];
1543 if ( repeated == FALSE0 ) {
1544 patternRepeated[prevCh - PATTERN_CHAR_BASE] = TRUE1;
1545 } else {
1546 foundRepetition = true;
1547 break;
1548 }
1549 count = 0;
1550 }
1551 if (ch == 0x0027 /*'*/) {
1552 // Consecutive single quotes are a single quote literal,
1553 // either outside of quotes or between quotes
1554 if ((i+1) < intervalPattern.length() &&
1555 intervalPattern.charAt(i+1) == 0x0027 /*'*/) {
1556 ++i;
1557 } else {
1558 inQuote = ! inQuote;
1559 }
1560 }
1561 else if (!inQuote && ((ch >= 0x0061 /*'a'*/ && ch <= 0x007A /*'z'*/)
1562 || (ch >= 0x0041 /*'A'*/ && ch <= 0x005A /*'Z'*/))) {
1563 // ch is a date-time pattern character
1564 prevCh = ch;
1565 ++count;
1566 }
1567 }
1568 // check last pattern char, distinguish
1569 // "dd MM" ( no repetition ),
1570 // "d-d"(last char repeated ), and
1571 // "d-d MM" ( repetition found )
1572 if ( count > 0 && foundRepetition == FALSE0 ) {
1573 if ( patternRepeated[(int)(prevCh - PATTERN_CHAR_BASE)] == FALSE0 ) {
1574 count = 0;
1575 }
1576 }
1577 return (i - count);
1578}
1579
1580// The following is only called from fallbackFormat, i.e. within the gFormatterMutex lock
1581void DateIntervalFormat::fallbackFormatRange(
1582 Calendar& fromCalendar,
1583 Calendar& toCalendar,
1584 UnicodeString& appendTo,
1585 int8_t& firstIndex,
1586 FieldPositionHandler& fphandler,
1587 UErrorCode& status) const {
1588 UnicodeString fallbackPattern;
1589 fInfo->getFallbackIntervalPattern(fallbackPattern);
1590 SimpleFormatter sf(fallbackPattern, 2, 2, status);
1591 if (U_FAILURE(status)) {
1592 return;
1593 }
1594 int32_t offsets[2];
1595 UnicodeString patternBody = sf.getTextWithNoArguments(offsets, 2);
1596
1597 UErrorCode tempStatus = U_ZERO_ERROR; // for setContext, ignored
1598 // TODO(ICU-20406): Use SimpleFormatter Iterator interface when available.
1599 if (offsets[0] < offsets[1]) {
1600 firstIndex = 0;
1601 appendTo.append(patternBody.tempSubStringBetween(0, offsets[0]));
1602 fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
1603 appendTo.append(patternBody.tempSubStringBetween(offsets[0], offsets[1]));
1604 // No capitalization for second part of interval
1605 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
1606 fDateFormat->_format(toCalendar, appendTo, fphandler, status);
1607 appendTo.append(patternBody.tempSubStringBetween(offsets[1]));
1608 } else {
1609 firstIndex = 1;
1610 appendTo.append(patternBody.tempSubStringBetween(0, offsets[1]));
1611 fDateFormat->_format(toCalendar, appendTo, fphandler, status);
1612 appendTo.append(patternBody.tempSubStringBetween(offsets[1], offsets[0]));
1613 // No capitalization for second part of interval
1614 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
1615 fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
1616 appendTo.append(patternBody.tempSubStringBetween(offsets[0]));
1617 }
1618}
1619
1620// The following is only called from formatImpl, i.e. within the gFormatterMutex lock
1621UnicodeString&
1622DateIntervalFormat::fallbackFormat(Calendar& fromCalendar,
1623 Calendar& toCalendar,
1624 UBool fromToOnSameDay, // new
1625 UnicodeString& appendTo,
1626 int8_t& firstIndex,
1627 FieldPositionHandler& fphandler,
1628 UErrorCode& status) const {
1629 if ( U_FAILURE(status) ) {
1630 return appendTo;
1631 }
1632
1633 UBool formatDatePlusTimeRange = (fromToOnSameDay && fDatePattern && fTimePattern);
1634 if (formatDatePlusTimeRange) {
1635 SimpleFormatter sf(*fDateTimeFormat, 2, 2, status);
1636 if (U_FAILURE(status)) {
1637 return appendTo;
1638 }
1639 int32_t offsets[2];
1640 UnicodeString patternBody = sf.getTextWithNoArguments(offsets, 2);
1641
1642 UnicodeString fullPattern; // for saving the pattern in fDateFormat
1643 fDateFormat->toPattern(fullPattern); // save current pattern, restore later
1644
1645 UErrorCode tempStatus = U_ZERO_ERROR; // for setContext, ignored
1646 // {0} is time range
1647 // {1} is single date portion
1648 // TODO(ICU-20406): Use SimpleFormatter Iterator interface when available.
1649 if (offsets[0] < offsets[1]) {
1650 appendTo.append(patternBody.tempSubStringBetween(0, offsets[0]));
1651 fDateFormat->applyPattern(*fTimePattern);
1652 fallbackFormatRange(fromCalendar, toCalendar, appendTo, firstIndex, fphandler, status);
1653 appendTo.append(patternBody.tempSubStringBetween(offsets[0], offsets[1]));
1654 fDateFormat->applyPattern(*fDatePattern);
1655 // No capitalization for second portion
1656 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
1657 fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
1658 appendTo.append(patternBody.tempSubStringBetween(offsets[1]));
1659 } else {
1660 appendTo.append(patternBody.tempSubStringBetween(0, offsets[1]));
1661 fDateFormat->applyPattern(*fDatePattern);
1662 fDateFormat->_format(fromCalendar, appendTo, fphandler, status);
1663 appendTo.append(patternBody.tempSubStringBetween(offsets[1], offsets[0]));
1664 fDateFormat->applyPattern(*fTimePattern);
1665 // No capitalization for second portion
1666 fDateFormat->setContext(UDISPCTX_CAPITALIZATION_NONE, tempStatus);
1667 fallbackFormatRange(fromCalendar, toCalendar, appendTo, firstIndex, fphandler, status);
1668 appendTo.append(patternBody.tempSubStringBetween(offsets[0]));
1669 }
1670
1671 // restore full pattern
1672 fDateFormat->applyPattern(fullPattern);
1673 } else {
1674 fallbackFormatRange(fromCalendar, toCalendar, appendTo, firstIndex, fphandler, status);
1675 }
1676 return appendTo;
1677}
1678
1679
1680
1681
1682UBool U_EXPORT2
1683DateIntervalFormat::fieldExistsInSkeleton(UCalendarDateFields field,
1684 const UnicodeString& skeleton)
1685{
1686 const UChar fieldChar = fgCalendarFieldToPatternLetter[field];
1687 return ( (skeleton.indexOf(fieldChar) == -1)?FALSE0:TRUE1 ) ;
1688}
1689
1690
1691
1692void U_EXPORT2
1693DateIntervalFormat::adjustFieldWidth(const UnicodeString& inputSkeleton,
1694 const UnicodeString& bestMatchSkeleton,
1695 const UnicodeString& bestIntervalPattern,
1696 int8_t differenceInfo,
1697 UBool suppressDayPeriodField,
1698 UnicodeString& adjustedPtn) {
1699 adjustedPtn = bestIntervalPattern;
1700 int32_t inputSkeletonFieldWidth[] =
1701 {
1702 // A B C D E F G H I J K L M N O
1703 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1704 // P Q R S T U V W X Y Z
1705 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1706 // a b c d e f g h i j k l m n o
1707 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1708 // p q r s t u v w x y z
1709 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1710 };
1711
1712 int32_t bestMatchSkeletonFieldWidth[] =
1713 {
1714 // A B C D E F G H I J K L M N O
1715 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1716 // P Q R S T U V W X Y Z
1717 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1718 // a b c d e f g h i j k l m n o
1719 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1720 // p q r s t u v w x y z
1721 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1722 };
1723
1724 const int8_t PATTERN_CHAR_BASE = 0x41;
1725
1726 DateIntervalInfo::parseSkeleton(inputSkeleton, inputSkeletonFieldWidth);
1727 DateIntervalInfo::parseSkeleton(bestMatchSkeleton, bestMatchSkeletonFieldWidth);
1728 if (suppressDayPeriodField) {
1729 findReplaceInPattern(adjustedPtn, UnicodeString(LOW_A((UChar)0x0061)), UnicodeString());
1730 findReplaceInPattern(adjustedPtn, UnicodeString(" "), UnicodeString(" "));
1731 adjustedPtn.trim();
1732 }
1733 if ( differenceInfo == 2 ) {
1734 if (inputSkeleton.indexOf(LOW_Z((UChar)0x007A)) != -1) {
1735 findReplaceInPattern(adjustedPtn, UnicodeString(LOW_V((UChar)0x0076)), UnicodeString(LOW_Z((UChar)0x007A)));
1736 }
1737 if (inputSkeleton.indexOf(CAP_K((UChar)0x004B)) != -1) {
1738 findReplaceInPattern(adjustedPtn, UnicodeString(LOW_H((UChar)0x0068)), UnicodeString(CAP_K((UChar)0x004B)));
1739 }
1740 if (inputSkeleton.indexOf(LOW_K((UChar)0x006B)) != -1) {
1741 findReplaceInPattern(adjustedPtn, UnicodeString(CAP_H((UChar)0x0048)), UnicodeString(LOW_K((UChar)0x006B)));
1742 }
1743 if (inputSkeleton.indexOf(LOW_B((UChar)0x0062)) != -1) {
1744 findReplaceInPattern(adjustedPtn, UnicodeString(LOW_A((UChar)0x0061)), UnicodeString(LOW_B((UChar)0x0062)));
1745 }
1746 }
1747 if (adjustedPtn.indexOf(LOW_A((UChar)0x0061)) != -1 && bestMatchSkeletonFieldWidth[LOW_A((UChar)0x0061) - PATTERN_CHAR_BASE] == 0) {
1748 bestMatchSkeletonFieldWidth[LOW_A((UChar)0x0061) - PATTERN_CHAR_BASE] = 1;
1749 }
1750 if (adjustedPtn.indexOf(LOW_B((UChar)0x0062)) != -1 && bestMatchSkeletonFieldWidth[LOW_B((UChar)0x0062) - PATTERN_CHAR_BASE] == 0) {
1751 bestMatchSkeletonFieldWidth[LOW_B((UChar)0x0062) - PATTERN_CHAR_BASE] = 1;
1752 }
1753
1754 UBool inQuote = false;
1755 UChar prevCh = 0;
1756 int32_t count = 0;
1757
1758 // loop through the pattern string character by character
1759 int32_t adjustedPtnLength = adjustedPtn.length();
1760 int32_t i;
1761 for (i = 0; i < adjustedPtnLength; ++i) {
1762 UChar ch = adjustedPtn.charAt(i);
1763 if (ch != prevCh && count > 0) {
1764 // check the repeativeness of pattern letter
1765 UChar skeletonChar = prevCh;
1766 if ( skeletonChar == CAP_L((UChar)0x004C) ) {
1767 // there is no "L" (always be "M") in skeleton,
1768 // but there is "L" in pattern.
1769 // for skeleton "M+", the pattern might be "...L..."
1770 skeletonChar = CAP_M((UChar)0x004D);
1771 }
1772 int32_t fieldCount = bestMatchSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)];
1773 int32_t inputFieldCount = inputSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)];
1774 if ( fieldCount == count && inputFieldCount > fieldCount ) {
1775 count = inputFieldCount - fieldCount;
1776 int32_t j;
1777 for ( j = 0; j < count; ++j ) {
1778 adjustedPtn.insert(i, prevCh);
1779 }
1780 i += count;
1781 adjustedPtnLength += count;
1782 }
1783 count = 0;
1784 }
1785 if (ch == 0x0027 /*'*/) {
1786 // Consecutive single quotes are a single quote literal,
1787 // either outside of quotes or between quotes
1788 if ((i+1) < adjustedPtn.length() && adjustedPtn.charAt(i+1) == 0x0027 /* ' */) {
1789 ++i;
1790 } else {
1791 inQuote = ! inQuote;
1792 }
1793 }
1794 else if ( ! inQuote && ((ch >= 0x0061 /*'a'*/ && ch <= 0x007A /*'z'*/)
1795 || (ch >= 0x0041 /*'A'*/ && ch <= 0x005A /*'Z'*/))) {
1796 // ch is a date-time pattern character
1797 prevCh = ch;
1798 ++count;
1799 }
1800 }
1801 if ( count > 0 ) {
1802 // last item
1803 // check the repeativeness of pattern letter
1804 UChar skeletonChar = prevCh;
1805 if ( skeletonChar == CAP_L((UChar)0x004C) ) {
1806 // there is no "L" (always be "M") in skeleton,
1807 // but there is "L" in pattern.
1808 // for skeleton "M+", the pattern might be "...L..."
1809 skeletonChar = CAP_M((UChar)0x004D);
1810 }
1811 int32_t fieldCount = bestMatchSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)];
1812 int32_t inputFieldCount = inputSkeletonFieldWidth[(int)(skeletonChar - PATTERN_CHAR_BASE)];
1813 if ( fieldCount == count && inputFieldCount > fieldCount ) {
1814 count = inputFieldCount - fieldCount;
1815 int32_t j;
1816 for ( j = 0; j < count; ++j ) {
1817 adjustedPtn.append(prevCh);
1818 }
1819 }
1820 }
1821}
1822
1823void
1824DateIntervalFormat::findReplaceInPattern(UnicodeString& targetString,
1825 const UnicodeString& strToReplace,
1826 const UnicodeString& strToReplaceWith) {
1827 int32_t firstQuoteIndex = targetString.indexOf(u'\'');
1828 if (firstQuoteIndex == -1) {
1829 targetString.findAndReplace(strToReplace, strToReplaceWith);
1830 } else {
1831 UnicodeString result;
1832 UnicodeString source = targetString;
1833
1834 while (firstQuoteIndex >= 0) {
1835 int32_t secondQuoteIndex = source.indexOf(u'\'', firstQuoteIndex + 1);
1836 if (secondQuoteIndex == -1) {
1837 secondQuoteIndex = source.length() - 1;
1838 }
1839
1840 UnicodeString unquotedText(source, 0, firstQuoteIndex);
1841 UnicodeString quotedText(source, firstQuoteIndex, secondQuoteIndex - firstQuoteIndex + 1);
1842
1843 unquotedText.findAndReplace(strToReplace, strToReplaceWith);
1844 result += unquotedText;
1845 result += quotedText;
1846
1847 source.remove(0, secondQuoteIndex + 1);
1848 firstQuoteIndex = source.indexOf(u'\'');
1849 }
1850 source.findAndReplace(strToReplace, strToReplaceWith);
1851 result += source;
1852 targetString = result;
1853 }
1854}
1855
1856
1857
1858void
1859DateIntervalFormat::concatSingleDate2TimeInterval(UnicodeString& format,
1860 const UnicodeString& datePattern,
1861 UCalendarDateFields field,
1862 UErrorCode& status) {
1863 // following should not set wrong status
1864 int32_t itvPtnIndex = DateIntervalInfo::calendarFieldToIntervalIndex(field,
1865 status);
1866 if ( U_FAILURE(status) ) {
1867 return;
1868 }
1869 PatternInfo& timeItvPtnInfo = fIntervalPatterns[itvPtnIndex];
1870 if ( !timeItvPtnInfo.firstPart.isEmpty() ) {
1871 UnicodeString timeIntervalPattern(timeItvPtnInfo.firstPart);
1872 timeIntervalPattern.append(timeItvPtnInfo.secondPart);
1873 UnicodeString combinedPattern;
1874 SimpleFormatter(format, 2, 2, status).
1875 format(timeIntervalPattern, datePattern, combinedPattern, status);
1876 if ( U_FAILURE(status) ) {
1877 return;
1878 }
1879 setIntervalPattern(field, combinedPattern, timeItvPtnInfo.laterDateFirst);
1880 }
1881 // else: fall back
1882 // it should not happen if the interval format defined is valid
1883}
1884
1885
1886
1887const UChar
1888DateIntervalFormat::fgCalendarFieldToPatternLetter[] =
1889{
1890 /*GyM*/ CAP_G((UChar)0x0047), LOW_Y((UChar)0x0079), CAP_M((UChar)0x004D),
1891 /*wWd*/ LOW_W((UChar)0x0077), CAP_W((UChar)0x0057), LOW_D((UChar)0x0064),
1892 /*DEF*/ CAP_D((UChar)0x0044), CAP_E((UChar)0x0045), CAP_F((UChar)0x0046),
1893 /*ahH*/ LOW_A((UChar)0x0061), LOW_H((UChar)0x0068), CAP_H((UChar)0x0048),
1894 /*msS*/ LOW_M((UChar)0x006D), LOW_S((UChar)0x0073), CAP_S((UChar)0x0053), // MINUTE, SECOND, MILLISECOND
1895 /*z.Y*/ LOW_Z((UChar)0x007A), SPACE((UChar)0x0020), CAP_Y((UChar)0x0059), // ZONE_OFFSET, DST_OFFSET, YEAR_WOY,
1896 /*eug*/ LOW_E((UChar)0x0065), LOW_U((UChar)0x0075), LOW_G((UChar)0x0067), // DOW_LOCAL, EXTENDED_YEAR, JULIAN_DAY,
1897 /*A..*/ CAP_A((UChar)0x0041), SPACE((UChar)0x0020), SPACE((UChar)0x0020), // MILLISECONDS_IN_DAY, IS_LEAP_MONTH, FIELD_COUNT
1898};
1899
1900
1901
1902U_NAMESPACE_END}
1903
1904#endif