Bug Summary

File:root/firefox-clang/intl/icu/source/i18n/datefmt.cpp
Warning:line 462, column 19
Forming reference to null pointer

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name datefmt.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -ffp-contract=off -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/config/external/icu/i18n -fcoverage-compilation-dir=/root/firefox-clang/obj-x86_64-pc-linux-gnu/config/external/icu/i18n -resource-dir /usr/lib/llvm-21/lib/clang/21 -include /root/firefox-clang/config/gcc_hidden.h -include /root/firefox-clang/obj-x86_64-pc-linux-gnu/mozilla-config.h -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/system_wrappers -U _FORTIFY_SOURCE -D _FORTIFY_SOURCE=2 -D _GLIBCXX_ASSERTIONS -D DEBUG=1 -D U_I18N_IMPLEMENTATION -D _LIBCPP_DISABLE_DEPRECATION_WARNINGS -D U_USING_ICU_NAMESPACE=0 -D U_NO_DEFAULT_INCLUDE_UTF_HEADERS=1 -D U_HIDE_OBSOLETE_UTF_OLD_H=1 -D UCONFIG_NO_LEGACY_CONVERSION -D UCONFIG_NO_TRANSLITERATION -D UCONFIG_NO_REGULAR_EXPRESSIONS -D UCONFIG_NO_BREAK_ITERATION -D UCONFIG_NO_IDNA -D UCONFIG_NO_MF2 -D U_CHARSET_IS_UTF8 -D UNISTR_FROM_CHAR_EXPLICIT=explicit -D UNISTR_FROM_STRING_EXPLICIT=explicit -D U_ENABLE_DYLOAD=0 -D U_DEBUG=1 -I /root/firefox-clang/config/external/icu/i18n -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/config/external/icu/i18n -I /root/firefox-clang/intl/icu/source/common -I /root/firefox-clang/mfbt/double-conversion -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nspr -I /root/firefox-clang/obj-x86_64-pc-linux-gnu/dist/include/nss -D MOZILLA_CLIENT -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/x86_64-linux-gnu/c++/14 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/backward -internal-isystem /usr/lib/llvm-21/lib/clang/21/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-error=pessimizing-move -Wno-error=large-by-value-copy=128 -Wno-error=implicit-int-float-conversion -Wno-error=thread-safety-analysis -Wno-error=tautological-type-limit-compare -Wno-invalid-offsetof -Wno-range-loop-analysis -Wno-deprecated-anon-enum-enum-conversion -Wno-deprecated-enum-enum-conversion -Wno-deprecated-this-capture -Wno-inline-new-delete -Wno-error=deprecated-declarations -Wno-error=array-bounds -Wno-error=free-nonheap-object -Wno-error=atomic-alignment -Wno-error=deprecated-builtins -Wno-psabi -Wno-error=builtin-macro-redefined -Wno-vla-cxx-extension -Wno-unknown-warning-option -Wno-comma -Wno-implicit-const-int-float-conversion -Wno-macro-redefined -Wno-microsoft-include -Wno-tautological-unsigned-enum-zero-compare -Wno-unreachable-code-loop-increment -Wno-unreachable-code-return -fdeprecated-macro -ferror-limit 19 -fstrict-flex-arrays=1 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fno-sized-deallocation -fno-aligned-allocation -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2025-06-27-100320-3286336-1 -x c++ /root/firefox-clang/intl/icu/source/i18n/datefmt.cpp

/root/firefox-clang/intl/icu/source/i18n/datefmt.cpp

1// © 2016 and later: Unicode, Inc. and others.
2// License & terms of use: http://www.unicode.org/copyright.html
3/*
4 *******************************************************************************
5 * Copyright (C) 1997-2015, International Business Machines Corporation and *
6 * others. All Rights Reserved. *
7 *******************************************************************************
8 *
9 * File DATEFMT.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 * 08/12/97 aliu Fixed operator== to use Calendar::equivalentTo.
18 * 07/20/98 stephen Changed ParsePosition initialization
19 ********************************************************************************
20 */
21
22#include "unicode/utypes.h"
23
24#if !UCONFIG_NO_FORMATTING0
25
26#include "unicode/ures.h"
27#include "unicode/datefmt.h"
28#include "unicode/smpdtfmt.h"
29#include "unicode/dtptngen.h"
30#include "unicode/udisplaycontext.h"
31#include "unicode/gregocal.h"
32#include "reldtfmt.h"
33#include "sharedobject.h"
34#include "unifiedcache.h"
35#include "uarrsort.h"
36
37#include "cstring.h"
38#include "windtfmt.h"
39
40#if defined( U_DEBUG_CALSVC ) || defined (U_DEBUG_CAL)
41#include <stdio.h>
42#endif
43#include <typeinfo>
44
45// *****************************************************************************
46// class DateFormat
47// *****************************************************************************
48
49U_NAMESPACE_BEGINnamespace icu_77 {
50
51class DateFmtBestPattern : public SharedObject {
52public:
53 UnicodeString fPattern;
54
55 DateFmtBestPattern(const UnicodeString &pattern)
56 : fPattern(pattern) { }
57 ~DateFmtBestPattern();
58};
59
60DateFmtBestPattern::~DateFmtBestPattern() {
61}
62
63template<>
64const DateFmtBestPattern *LocaleCacheKey<DateFmtBestPattern>::createObject(
65 const void * /*creationContext*/, UErrorCode &status) const {
66 status = U_UNSUPPORTED_ERROR;
67 return nullptr;
68}
69
70class DateFmtBestPatternKey : public LocaleCacheKey<DateFmtBestPattern> {
71private:
72 UnicodeString fSkeleton;
73protected:
74 virtual bool equals(const CacheKeyBase &other) const override {
75 if (!LocaleCacheKey<DateFmtBestPattern>::equals(other)) {
76 return false;
77 }
78 // We know that this and other are of same class if we get this far.
79 return operator==(static_cast<const DateFmtBestPatternKey &>(other));
80 }
81public:
82 DateFmtBestPatternKey(
83 const Locale &loc,
84 const UnicodeString &skeleton,
85 UErrorCode &status)
86 : LocaleCacheKey<DateFmtBestPattern>(loc),
87 fSkeleton(DateTimePatternGenerator::staticGetSkeleton(skeleton, status)) { }
88 DateFmtBestPatternKey(const DateFmtBestPatternKey &other) :
89 LocaleCacheKey<DateFmtBestPattern>(other),
90 fSkeleton(other.fSkeleton) { }
91 virtual ~DateFmtBestPatternKey();
92 virtual int32_t hashCode() const override {
93 return static_cast<int32_t>(37u * static_cast<uint32_t>(LocaleCacheKey<DateFmtBestPattern>::hashCode()) + static_cast<uint32_t>(fSkeleton.hashCode()));
94 }
95 inline bool operator==(const DateFmtBestPatternKey &other) const {
96 return fSkeleton == other.fSkeleton;
97 }
98 virtual CacheKeyBase *clone() const override {
99 return new DateFmtBestPatternKey(*this);
100 }
101 virtual const DateFmtBestPattern *createObject(
102 const void * /*unused*/, UErrorCode &status) const override {
103 LocalPointer<DateTimePatternGenerator> dtpg(
104 DateTimePatternGenerator::createInstance(fLoc, status));
105 if (U_FAILURE(status)) {
106 return nullptr;
107 }
108
109 LocalPointer<DateFmtBestPattern> pattern(
110 new DateFmtBestPattern(
111 dtpg->getBestPattern(fSkeleton, status)),
112 status);
113 if (U_FAILURE(status)) {
114 return nullptr;
115 }
116 DateFmtBestPattern *result = pattern.orphan();
117 result->addRef();
118 return result;
119 }
120};
121
122DateFmtBestPatternKey::~DateFmtBestPatternKey() { }
123
124
125DateFormat::DateFormat()
126: fCalendar(nullptr),
127 fNumberFormat(nullptr),
128 fCapitalizationContext(UDISPCTX_CAPITALIZATION_NONE)
129{
130}
131
132//----------------------------------------------------------------------
133
134DateFormat::DateFormat(const DateFormat& other)
135: Format(other),
136 fCalendar(nullptr),
137 fNumberFormat(nullptr),
138 fCapitalizationContext(UDISPCTX_CAPITALIZATION_NONE)
139{
140 *this = other;
141}
142
143//----------------------------------------------------------------------
144
145DateFormat& DateFormat::operator=(const DateFormat& other)
146{
147 if (this != &other)
148 {
149 delete fCalendar;
150 delete fNumberFormat;
151 if(other.fCalendar) {
152 fCalendar = other.fCalendar->clone();
153 } else {
154 fCalendar = nullptr;
155 }
156 if(other.fNumberFormat) {
157 fNumberFormat = other.fNumberFormat->clone();
158 } else {
159 fNumberFormat = nullptr;
160 }
161 fBoolFlags = other.fBoolFlags;
162 fCapitalizationContext = other.fCapitalizationContext;
163 }
164 return *this;
165}
166
167//----------------------------------------------------------------------
168
169DateFormat::~DateFormat()
170{
171 delete fCalendar;
172 delete fNumberFormat;
173}
174
175//----------------------------------------------------------------------
176
177bool
178DateFormat::operator==(const Format& other) const
179{
180 if (this == &other) {
181 return true;
182 }
183 if (!(Format::operator==(other))) {
184 return false;
185 }
186 // Format::operator== guarantees that this cast is safe
187 DateFormat* fmt = (DateFormat*)&other;
188 return fCalendar&&(fCalendar->isEquivalentTo(*fmt->fCalendar)) &&
189 (fNumberFormat && *fNumberFormat == *fmt->fNumberFormat) &&
190 (fCapitalizationContext == fmt->fCapitalizationContext);
191}
192
193//----------------------------------------------------------------------
194
195UnicodeString&
196DateFormat::format(const Formattable& obj,
197 UnicodeString& appendTo,
198 FieldPosition& fieldPosition,
199 UErrorCode& status) const
200{
201 if (U_FAILURE(status)) return appendTo;
202
203 // if the type of the Formattable is double or long, treat it as if it were a Date
204 UDate date = 0;
205 switch (obj.getType())
206 {
207 case Formattable::kDate:
208 date = obj.getDate();
209 break;
210 case Formattable::kDouble:
211 date = static_cast<UDate>(obj.getDouble());
212 break;
213 case Formattable::kLong:
214 date = static_cast<UDate>(obj.getLong());
215 break;
216 default:
217 status = U_ILLEGAL_ARGUMENT_ERROR;
218 return appendTo;
219 }
220
221 // Is this right?
222 //if (fieldPosition.getBeginIndex() == fieldPosition.getEndIndex())
223 // status = U_ILLEGAL_ARGUMENT_ERROR;
224
225 return format(date, appendTo, fieldPosition);
226}
227
228//----------------------------------------------------------------------
229
230UnicodeString&
231DateFormat::format(const Formattable& obj,
232 UnicodeString& appendTo,
233 FieldPositionIterator* posIter,
234 UErrorCode& status) const
235{
236 if (U_FAILURE(status)) return appendTo;
237
238 // if the type of the Formattable is double or long, treat it as if it were a Date
239 UDate date = 0;
240 switch (obj.getType())
241 {
242 case Formattable::kDate:
243 date = obj.getDate();
244 break;
245 case Formattable::kDouble:
246 date = static_cast<UDate>(obj.getDouble());
247 break;
248 case Formattable::kLong:
249 date = static_cast<UDate>(obj.getLong());
250 break;
251 default:
252 status = U_ILLEGAL_ARGUMENT_ERROR;
253 return appendTo;
254 }
255
256 // Is this right?
257 //if (fieldPosition.getBeginIndex() == fieldPosition.getEndIndex())
258 // status = U_ILLEGAL_ARGUMENT_ERROR;
259
260 return format(date, appendTo, posIter, status);
261}
262
263//----------------------------------------------------------------------
264
265// Default implementation for backwards compatibility, subclasses should implement.
266UnicodeString&
267DateFormat::format(Calendar& /* unused cal */,
268 UnicodeString& appendTo,
269 FieldPositionIterator* /* unused posIter */,
270 UErrorCode& status) const {
271 if (U_SUCCESS(status)) {
272 status = U_UNSUPPORTED_ERROR;
273 }
274 return appendTo;
275}
276
277//----------------------------------------------------------------------
278
279UnicodeString&
280DateFormat::format(UDate date, UnicodeString& appendTo, FieldPosition& fieldPosition) const {
281 if (fCalendar != nullptr) {
282 UErrorCode ec = U_ZERO_ERROR;
283 // Avoid a heap allocation and corresponding free for the common case
284 if (typeid(*fCalendar) == typeid(GregorianCalendar)) {
285 GregorianCalendar cal(*static_cast<GregorianCalendar*>(fCalendar));
286 cal.setTime(date, ec);
287 if (U_SUCCESS(ec)) {
288 format(cal, appendTo, fieldPosition);
289 }
290 } else {
291 // Use a clone of our calendar instance
292 Calendar *calClone = fCalendar->clone();
293 if (calClone != nullptr) {
294 calClone->setTime(date, ec);
295 if (U_SUCCESS(ec)) {
296 format(*calClone, appendTo, fieldPosition);
297 }
298 delete calClone;
299 }
300 }
301 }
302 return appendTo;
303}
304
305//----------------------------------------------------------------------
306
307UnicodeString&
308DateFormat::format(UDate date, UnicodeString& appendTo, FieldPositionIterator* posIter,
309 UErrorCode& status) const {
310 if (fCalendar != nullptr) {
311 UErrorCode ec = U_ZERO_ERROR;
312 // Avoid a heap allocation and corresponding free for the common case
313 if (typeid(*fCalendar) == typeid(GregorianCalendar)) {
314 GregorianCalendar cal(*static_cast<GregorianCalendar*>(fCalendar));
315 cal.setTime(date, ec);
316 if (U_SUCCESS(ec)) {
317 format(cal, appendTo, posIter, status);
318 }
319 } else {
320 Calendar* calClone = fCalendar->clone();
321 if (calClone != nullptr) {
322 calClone->setTime(date, status);
323 if (U_SUCCESS(status)) {
324 format(*calClone, appendTo, posIter, status);
325 }
326 delete calClone;
327 }
328 }
329 }
330 return appendTo;
331}
332
333//----------------------------------------------------------------------
334
335UnicodeString&
336DateFormat::format(UDate date, UnicodeString& appendTo) const
337{
338 // Note that any error information is just lost. That's okay
339 // for this convenience method.
340 FieldPosition fpos(FieldPosition::DONT_CARE);
341 return format(date, appendTo, fpos);
342}
343
344//----------------------------------------------------------------------
345
346UDate
347DateFormat::parse(const UnicodeString& text,
348 ParsePosition& pos) const
349{
350 UDate d = 0; // Error return UDate is 0 (the epoch)
351 if (fCalendar != nullptr) {
352 Calendar* calClone = fCalendar->clone();
353 if (calClone != nullptr) {
354 int32_t start = pos.getIndex();
355 calClone->clear();
356 parse(text, *calClone, pos);
357 if (pos.getIndex() != start) {
358 UErrorCode ec = U_ZERO_ERROR;
359 d = calClone->getTime(ec);
360 if (U_FAILURE(ec)) {
361 // We arrive here if fCalendar => calClone is non-lenient and
362 // there is an out-of-range field. We don't know which field
363 // was illegal so we set the error index to the start.
364 pos.setIndex(start);
365 pos.setErrorIndex(start);
366 d = 0;
367 }
368 }
369 delete calClone;
370 }
371 }
372 return d;
373}
374
375//----------------------------------------------------------------------
376
377UDate
378DateFormat::parse(const UnicodeString& text,
379 UErrorCode& status) const
380{
381 if (U_FAILURE(status)) return 0;
382
383 ParsePosition pos(0);
384 UDate result = parse(text, pos);
385 if (pos.getIndex() == 0) {
386#if defined (U_DEBUG_CAL)
387 fprintf(stderrstderr, "%s:%d - - failed to parse - err index %d\n"
388 , __FILE__"/root/firefox-clang/intl/icu/source/i18n/datefmt.cpp", __LINE__388, pos.getErrorIndex() );
389#endif
390 status = U_ILLEGAL_ARGUMENT_ERROR;
391 }
392 return result;
393}
394
395//----------------------------------------------------------------------
396
397void
398DateFormat::parseObject(const UnicodeString& source,
399 Formattable& result,
400 ParsePosition& pos) const
401{
402 result.setDate(parse(source, pos));
403}
404
405//----------------------------------------------------------------------
406
407DateFormat* U_EXPORT2
408DateFormat::createTimeInstance(DateFormat::EStyle style,
409 const Locale& aLocale)
410{
411 return createDateTimeInstance(kNone, style, aLocale);
412}
413
414//----------------------------------------------------------------------
415
416DateFormat* U_EXPORT2
417DateFormat::createDateInstance(DateFormat::EStyle style,
418 const Locale& aLocale)
419{
420 return createDateTimeInstance(style, kNone, aLocale);
421}
422
423//----------------------------------------------------------------------
424
425DateFormat* U_EXPORT2
426DateFormat::createDateTimeInstance(EStyle dateStyle,
427 EStyle timeStyle,
428 const Locale& aLocale)
429{
430 if(dateStyle != kNone)
431 {
432 dateStyle = static_cast<EStyle>(dateStyle + kDateOffset);
433 }
434 return create(timeStyle, dateStyle, aLocale);
435}
436
437//----------------------------------------------------------------------
438
439DateFormat* U_EXPORT2
440DateFormat::createInstance()
441{
442 return createDateTimeInstance(kShort, kShort, Locale::getDefault());
443}
444
445//----------------------------------------------------------------------
446
447UnicodeString U_EXPORT2
448DateFormat::getBestPattern(
449 const Locale &locale,
450 const UnicodeString &skeleton,
451 UErrorCode &status) {
452 UnifiedCache *cache = UnifiedCache::getInstance(status);
453 if (U_FAILURE(status)) {
4
Taking false branch
454 return {};
455 }
456 DateFmtBestPatternKey key(locale, skeleton, status);
457 const DateFmtBestPattern *patternPtr = nullptr;
5
'patternPtr' initialized to a null pointer value
458 cache->get(key, patternPtr, status);
6
Calling 'UnifiedCache::get'
19
Returning from 'UnifiedCache::get'
459 if (U_FAILURE(status)) {
20
Taking false branch
460 return {};
461 }
462 UnicodeString result(patternPtr->fPattern);
21
Forming reference to null pointer
463 patternPtr->removeRef();
464 return result;
465}
466
467DateFormat* U_EXPORT2
468DateFormat::createInstanceForSkeleton(
469 Calendar *calendarToAdopt,
470 const UnicodeString& skeleton,
471 const Locale &locale,
472 UErrorCode &status) {
473 LocalPointer<Calendar> calendar(calendarToAdopt);
474 if (U_FAILURE(status)) {
475 return nullptr;
476 }
477 if (calendar.isNull()) {
478 status = U_ILLEGAL_ARGUMENT_ERROR;
479 return nullptr;
480 }
481 Locale localeWithCalendar = locale;
482 localeWithCalendar.setKeywordValue("calendar", calendar->getType(), status);
483 if (U_FAILURE(status)) {
484 return nullptr;
485 }
486 DateFormat *result = createInstanceForSkeleton(skeleton, localeWithCalendar, status);
487 if (U_FAILURE(status)) {
488 return nullptr;
489 }
490 result->adoptCalendar(calendar.orphan());
491 return result;
492}
493
494DateFormat* U_EXPORT2
495DateFormat::createInstanceForSkeleton(
496 const UnicodeString& skeleton,
497 const Locale &locale,
498 UErrorCode &status) {
499 if (U_FAILURE(status)) {
2
Taking false branch
500 return nullptr;
501 }
502 LocalPointer<DateFormat> df(
503 new SimpleDateFormat(
504 getBestPattern(locale, skeleton, status),
3
Calling 'DateFormat::getBestPattern'
505 locale, status),
506 status);
507 return U_SUCCESS(status) ? df.orphan() : nullptr;
508}
509
510DateFormat* U_EXPORT2
511DateFormat::createInstanceForSkeleton(
512 const UnicodeString& skeleton,
513 UErrorCode &status) {
514 return createInstanceForSkeleton(
1
Calling 'DateFormat::createInstanceForSkeleton'
515 skeleton, Locale::getDefault(), status);
516}
517
518//----------------------------------------------------------------------
519
520DateFormat* U_EXPORT2
521DateFormat::create(EStyle timeStyle, EStyle dateStyle, const Locale& locale)
522{
523 UErrorCode status = U_ZERO_ERROR;
524#if U_PLATFORM_USES_ONLY_WIN32_API0
525 char buffer[8];
526 int32_t count = locale.getKeywordValue("compat", buffer, sizeof(buffer), status);
527
528 // if the locale has "@compat=host", create a host-specific DateFormat...
529 if (count > 0 && uprv_strcmp(buffer, "host"):: strcmp(buffer, "host") == 0) {
530 Win32DateFormat *f = new Win32DateFormat(timeStyle, dateStyle, locale, status);
531
532 if (U_SUCCESS(status)) {
533 return f;
534 }
535
536 delete f;
537 }
538#endif
539
540 // is it relative?
541 if(/*((timeStyle!=UDAT_NONE)&&(timeStyle & UDAT_RELATIVE)) || */((dateStyle!=kNone)&&((dateStyle-kDateOffset) & UDAT_RELATIVE))) {
542 RelativeDateFormat* r = new RelativeDateFormat(static_cast<UDateFormatStyle>(timeStyle), static_cast<UDateFormatStyle>(dateStyle - kDateOffset), locale, status);
543 if(U_SUCCESS(status)) return r;
544 delete r;
545 status = U_ZERO_ERROR;
546 }
547
548 // Try to create a SimpleDateFormat of the desired style.
549 SimpleDateFormat *f = new SimpleDateFormat(timeStyle, dateStyle, locale, status);
550 if (U_SUCCESS(status)) return f;
551 delete f;
552
553 // If that fails, try to create a format using the default pattern and
554 // the DateFormatSymbols for this locale.
555 status = U_ZERO_ERROR;
556 f = new SimpleDateFormat(locale, status);
557 if (U_SUCCESS(status)) return f;
558 delete f;
559
560 // This should never really happen, because the preceding constructor
561 // should always succeed. If the resource data is unavailable, a last
562 // resort object should be returned.
563 return nullptr;
564}
565
566//----------------------------------------------------------------------
567
568const Locale* U_EXPORT2
569DateFormat::getAvailableLocales(int32_t& count)
570{
571 // Get the list of installed locales.
572 // Even if root has the correct date format for this locale,
573 // it's still a valid locale (we don't worry about data fallbacks).
574 return Locale::getAvailableLocales(count);
575}
576
577//----------------------------------------------------------------------
578
579void
580DateFormat::adoptCalendar(Calendar* newCalendar)
581{
582 delete fCalendar;
583 fCalendar = newCalendar;
584}
585
586//----------------------------------------------------------------------
587void
588DateFormat::setCalendar(const Calendar& newCalendar)
589{
590 Calendar* newCalClone = newCalendar.clone();
591 if (newCalClone != nullptr) {
592 adoptCalendar(newCalClone);
593 }
594}
595
596//----------------------------------------------------------------------
597
598const Calendar*
599DateFormat::getCalendar() const
600{
601 return fCalendar;
602}
603
604//----------------------------------------------------------------------
605
606void
607DateFormat::adoptNumberFormat(NumberFormat* newNumberFormat)
608{
609 delete fNumberFormat;
610 fNumberFormat = newNumberFormat;
611 newNumberFormat->setParseIntegerOnly(true);
612 newNumberFormat->setGroupingUsed(false);
613}
614//----------------------------------------------------------------------
615
616void
617DateFormat::setNumberFormat(const NumberFormat& newNumberFormat)
618{
619 NumberFormat* newNumFmtClone = newNumberFormat.clone();
620 if (newNumFmtClone != nullptr) {
621 adoptNumberFormat(newNumFmtClone);
622 }
623}
624
625//----------------------------------------------------------------------
626
627const NumberFormat*
628DateFormat::getNumberFormat() const
629{
630 return fNumberFormat;
631}
632
633//----------------------------------------------------------------------
634
635void
636DateFormat::adoptTimeZone(TimeZone* zone)
637{
638 if (fCalendar != nullptr) {
639 fCalendar->adoptTimeZone(zone);
640 }
641}
642//----------------------------------------------------------------------
643
644void
645DateFormat::setTimeZone(const TimeZone& zone)
646{
647 if (fCalendar != nullptr) {
648 fCalendar->setTimeZone(zone);
649 }
650}
651
652//----------------------------------------------------------------------
653
654const TimeZone&
655DateFormat::getTimeZone() const
656{
657 if (fCalendar != nullptr) {
658 return fCalendar->getTimeZone();
659 }
660 // If calendar doesn't exists, create default timezone.
661 // fCalendar is rarely null
662 return *(TimeZone::createDefault());
663}
664
665//----------------------------------------------------------------------
666
667void
668DateFormat::setLenient(UBool lenient)
669{
670 if (fCalendar != nullptr) {
671 fCalendar->setLenient(lenient);
672 }
673 UErrorCode status = U_ZERO_ERROR;
674 setBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, lenient, status);
675 setBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, lenient, status);
676}
677
678//----------------------------------------------------------------------
679
680UBool
681DateFormat::isLenient() const
682{
683 UBool lenient = true;
684 if (fCalendar != nullptr) {
685 lenient = fCalendar->isLenient();
686 }
687 UErrorCode status = U_ZERO_ERROR;
688 return lenient
689 && getBooleanAttribute(UDAT_PARSE_ALLOW_WHITESPACE, status)
690 && getBooleanAttribute(UDAT_PARSE_ALLOW_NUMERIC, status);
691}
692
693void
694DateFormat::setCalendarLenient(UBool lenient)
695{
696 if (fCalendar != nullptr) {
697 fCalendar->setLenient(lenient);
698 }
699}
700
701//----------------------------------------------------------------------
702
703UBool
704DateFormat::isCalendarLenient() const
705{
706 if (fCalendar != nullptr) {
707 return fCalendar->isLenient();
708 }
709 // fCalendar is rarely null
710 return false;
711}
712
713
714//----------------------------------------------------------------------
715
716
717void DateFormat::setContext(UDisplayContext value, UErrorCode& status)
718{
719 if (U_FAILURE(status))
720 return;
721 if (static_cast<UDisplayContextType>(static_cast<uint32_t>(value) >> 8) == UDISPCTX_TYPE_CAPITALIZATION) {
722 fCapitalizationContext = value;
723 } else {
724 status = U_ILLEGAL_ARGUMENT_ERROR;
725 }
726}
727
728
729//----------------------------------------------------------------------
730
731
732UDisplayContext DateFormat::getContext(UDisplayContextType type, UErrorCode& status) const
733{
734 if (U_FAILURE(status))
735 return static_cast<UDisplayContext>(0);
736 if (type != UDISPCTX_TYPE_CAPITALIZATION) {
737 status = U_ILLEGAL_ARGUMENT_ERROR;
738 return static_cast<UDisplayContext>(0);
739 }
740 return fCapitalizationContext;
741}
742
743
744//----------------------------------------------------------------------
745
746
747DateFormat&
748DateFormat::setBooleanAttribute(UDateFormatBooleanAttribute attr,
749 UBool newValue,
750 UErrorCode &status) {
751 if(!fBoolFlags.isValidValue(newValue)) {
752 status = U_ILLEGAL_ARGUMENT_ERROR;
753 } else {
754 fBoolFlags.set(attr, newValue);
755 }
756
757 return *this;
758}
759
760//----------------------------------------------------------------------
761
762UBool
763DateFormat::getBooleanAttribute(UDateFormatBooleanAttribute attr, UErrorCode &/*status*/) const {
764
765 return fBoolFlags.get(attr);
766}
767
768U_NAMESPACE_END}
769
770#endif /* #if !UCONFIG_NO_FORMATTING */
771
772//eof

/root/firefox-clang/intl/icu/source/common/unifiedcache.h

1// © 2016 and later: Unicode, Inc. and others.
2// License & terms of use: http://www.unicode.org/copyright.html
3/*
4******************************************************************************
5* Copyright (C) 2015, International Business Machines Corporation and
6* others. All Rights Reserved.
7******************************************************************************
8*
9* File UNIFIEDCACHE.H - The ICU Unified cache.
10******************************************************************************
11*/
12
13#ifndef __UNIFIED_CACHE_H__
14#define __UNIFIED_CACHE_H__
15
16#include "utypeinfo.h" // for 'typeid' to work
17
18#include "unicode/uobject.h"
19#include "unicode/locid.h"
20#include "sharedobject.h"
21#include "unicode/unistr.h"
22#include "cstring.h"
23#include "ustr_imp.h"
24
25struct UHashtable;
26struct UHashElement;
27
28U_NAMESPACE_BEGINnamespace icu_77 {
29
30class UnifiedCache;
31
32/**
33 * A base class for all cache keys.
34 */
35class U_COMMON_API CacheKeyBase : public UObject {
36 public:
37 CacheKeyBase() : fCreationStatus(U_ZERO_ERROR), fIsPrimary(false) {}
38
39 /**
40 * Copy constructor. Needed to support cloning.
41 */
42 CacheKeyBase(const CacheKeyBase &other)
43 : UObject(other), fCreationStatus(other.fCreationStatus), fIsPrimary(false) { }
44 virtual ~CacheKeyBase();
45
46 /**
47 * Returns the hash code for this object.
48 */
49 virtual int32_t hashCode() const = 0;
50
51 /**
52 * Clones this object polymorphically. Caller owns returned value.
53 */
54 virtual CacheKeyBase *clone() const = 0;
55
56 /**
57 * Create a new object for this key. Called by cache on cache miss.
58 * createObject must add a reference to the object it returns. Note
59 * that getting an object from the cache and returning it without calling
60 * removeRef on it satisfies this requirement. It can also return nullptr
61 * and set status to an error.
62 *
63 * @param creationContext the context in which the object is being
64 * created. May be nullptr.
65 * @param status Implementations can return a failure here.
66 * In addition, implementations may return a
67 * non nullptr object and set a warning status.
68 */
69 virtual const SharedObject *createObject(
70 const void *creationContext, UErrorCode &status) const = 0;
71
72 /**
73 * Writes a description of this key to buffer and returns buffer. Written
74 * description is nullptr terminated.
75 */
76 virtual char *writeDescription(char *buffer, int32_t bufSize) const = 0;
77
78 friend inline bool operator==(const CacheKeyBase& lhs,
79 const CacheKeyBase& rhs) {
80 return lhs.equals(rhs);
81 }
82
83 friend inline bool operator!=(const CacheKeyBase& lhs,
84 const CacheKeyBase& rhs) {
85 return !lhs.equals(rhs);
86 }
87
88 protected:
89 virtual bool equals(const CacheKeyBase& other) const = 0;
90
91 private:
92 mutable UErrorCode fCreationStatus;
93 mutable UBool fIsPrimary;
94 friend class UnifiedCache;
95};
96
97
98
99/**
100 * Templated version of CacheKeyBase.
101 * A key of type LocaleCacheKey<T> maps to a value of type T.
102 */
103template<typename T>
104class CacheKey : public CacheKeyBase {
105 public:
106 virtual ~CacheKey() { }
107 /**
108 * The template parameter, T, determines the hash code returned.
109 */
110 virtual int32_t hashCode() const override {
111 const char *s = typeid(T).name();
112 return ustr_hashCharsNustr_hashCharsN_77(s, static_cast<int32_t>(uprv_strlen(s):: strlen(s)));
113 }
114
115 /**
116 * Use the value type, T, as the description.
117 */
118 virtual char *writeDescription(char *buffer, int32_t bufLen) const override {
119 const char *s = typeid(T).name();
120 uprv_strncpy(buffer, s, bufLen):: strncpy(buffer, s, bufLen);
121 buffer[bufLen - 1] = 0;
122 return buffer;
123 }
124
125 protected:
126 /**
127 * Two objects are equal if they are of the same type.
128 */
129 virtual bool equals(const CacheKeyBase &other) const override {
130 return this == &other || typeid(*this) == typeid(other);
131 }
132};
133
134/**
135 * Cache key based on locale.
136 * A key of type LocaleCacheKey<T> maps to a value of type T.
137 */
138template<typename T>
139class LocaleCacheKey : public CacheKey<T> {
140 protected:
141 Locale fLoc;
142 virtual bool equals(const CacheKeyBase &other) const override {
143 if (!CacheKey<T>::equals(other)) {
144 return false;
145 }
146 // We know this and other are of same class because equals() on
147 // CacheKey returned true.
148 return operator==(static_cast<const LocaleCacheKey<T> &>(other));
149 }
150 public:
151 LocaleCacheKey(const Locale &loc) : fLoc(loc) {}
152 LocaleCacheKey(const LocaleCacheKey<T> &other)
153 : CacheKey<T>(other), fLoc(other.fLoc) { }
154 virtual ~LocaleCacheKey() { }
155 virtual int32_t hashCode() const override {
156 return (int32_t)(37u * (uint32_t)CacheKey<T>::hashCode() + (uint32_t)fLoc.hashCode());
157 }
158 inline bool operator == (const LocaleCacheKey<T> &other) const {
159 return fLoc == other.fLoc;
160 }
161 virtual CacheKeyBase *clone() const override {
162 return new LocaleCacheKey<T>(*this);
163 }
164 virtual const T *createObject(
165 const void *creationContext, UErrorCode &status) const override;
166 /**
167 * Use the locale id as the description.
168 */
169 virtual char *writeDescription(char *buffer, int32_t bufLen) const override {
170 const char *s = fLoc.getName();
171 uprv_strncpy(buffer, s, bufLen):: strncpy(buffer, s, bufLen);
172 buffer[bufLen - 1] = 0;
173 return buffer;
174 }
175
176};
177
178/**
179 * The unified cache. A singleton type.
180 * Design doc here:
181 * https://docs.google.com/document/d/1RwGQJs4N4tawNbf809iYDRCvXoMKqDJihxzYt1ysmd8/edit?usp=sharing
182 */
183class U_COMMON_API UnifiedCache : public UnifiedCacheBase {
184 public:
185 /**
186 * @internal
187 * Do not call directly. Instead use UnifiedCache::getInstance() as
188 * there should be only one UnifiedCache in an application.
189 */
190 UnifiedCache(UErrorCode &status);
191
192 /**
193 * Return a pointer to the global cache instance.
194 */
195 static UnifiedCache *getInstance(UErrorCode &status);
196
197 /**
198 * Fetches a value from the cache by key. Equivalent to
199 * get(key, nullptr, ptr, status);
200 */
201 template<typename T>
202 void get(
203 const CacheKey<T>& key,
204 const T *&ptr,
205 UErrorCode &status) const {
206 get(key, nullptr, ptr, status);
7
Calling 'UnifiedCache::get'
17
Returning from 'UnifiedCache::get'
207 }
18
Returning without writing to 'ptr'
208
209 /**
210 * Fetches value from the cache by key.
211 *
212 * @param key the cache key.
213 * @param creationContext passed verbatim to createObject method of key
214 * @param ptr On entry, ptr must be nullptr or be included if
215 * the reference count of the object it points
216 * to. On exit, ptr points to the fetched object
217 * from the cache or is left unchanged on
218 * failure. Caller must call removeRef on ptr
219 * if set to a non nullptr value.
220 * @param status Any error returned here. May be set to a
221 * warning value even if ptr is set.
222 */
223 template<typename T>
224 void get(
225 const CacheKey<T>& key,
226 const void *creationContext,
227 const T *&ptr,
228 UErrorCode &status) const {
229 if (U_FAILURE(status)) {
8
Taking false branch
230 return;
231 }
232 UErrorCode creationStatus = U_ZERO_ERROR;
233 const SharedObject *value = nullptr;
234 _get(key, value, creationContext, creationStatus);
235 const T *tvalue = (const T *) value;
236 if (U_SUCCESS(creationStatus)) {
9
Taking true branch
237 SharedObject::copyPtr(tvalue, ptr);
10
Calling 'SharedObject::copyPtr'
14
Returning from 'SharedObject::copyPtr'
238 }
239 SharedObject::clearPtr(tvalue);
240 // Take care not to overwrite a warning status passed in with
241 // another warning or U_ZERO_ERROR.
242 if (status == U_ZERO_ERROR || U_FAILURE(creationStatus)) {
15
Assuming 'status' is equal to U_ZERO_ERROR
243 status = creationStatus;
244 }
245 }
16
Returning without writing to 'ptr'
246
247#ifdef UNIFIED_CACHE_DEBUG
248 /**
249 * Dumps the contents of this cache to standard error. Used for testing of
250 * cache only.
251 */
252 void dumpContents() const;
253#endif
254
255 /**
256 * Convenience method to get a value of type T from cache for a
257 * particular locale with creationContext == nullptr.
258 * @param loc the locale
259 * @param ptr On entry, must be nullptr or included in the ref count
260 * of the object to which it points.
261 * On exit, fetched value stored here or is left
262 * unchanged on failure. Caller must call removeRef on
263 * ptr if set to a non nullptr value.
264 * @param status Any error returned here. May be set to a
265 * warning value even if ptr is set.
266 */
267 template<typename T>
268 static void getByLocale(
269 const Locale &loc, const T *&ptr, UErrorCode &status) {
270 const UnifiedCache *cache = getInstance(status);
271 if (U_FAILURE(status)) {
272 return;
273 }
274 cache->get(LocaleCacheKey<T>(loc), ptr, status);
275 }
276
277#ifdef UNIFIED_CACHE_DEBUG
278 /**
279 * Dumps the cache contents to stderr. For testing only.
280 */
281 static void dump();
282#endif
283
284 /**
285 * Returns the number of keys in this cache. For testing only.
286 */
287 int32_t keyCount() const;
288
289 /**
290 * Removes any values from cache that are not referenced outside
291 * the cache.
292 */
293 void flush() const;
294
295 /**
296 * Configures at what point eviction of unused entries will begin.
297 * Eviction is triggered whenever the number of evictable keys exceeds
298 * BOTH count AND (number of in-use items) * (percentageOfInUseItems / 100).
299 * Once the number of unused entries drops below one of these,
300 * eviction ceases. Because eviction happens incrementally,
301 * the actual unused entry count may exceed both these numbers
302 * from time to time.
303 *
304 * A cache entry is defined as unused if it is not essential to guarantee
305 * that for a given key X, the cache returns the same reference to the
306 * same value as long as the client already holds a reference to that
307 * value.
308 *
309 * If this method is never called, the default settings are 1000 and 100%.
310 *
311 * Although this method is thread-safe, it is designed to be called at
312 * application startup. If it is called in the middle of execution, it
313 * will have no immediate effect on the cache. However over time, the
314 * cache will perform eviction slices in an attempt to honor the new
315 * settings.
316 *
317 * If a client already holds references to many different unique values
318 * in the cache such that the number of those unique values far exceeds
319 * "count" then the cache may not be able to maintain this maximum.
320 * However, if this happens, the cache still guarantees that the number of
321 * unused entries will remain only a small percentage of the total cache
322 * size.
323 *
324 * If the parameters passed are negative, setEvctionPolicy sets status to
325 * U_ILLEGAL_ARGUMENT_ERROR.
326 */
327 void setEvictionPolicy(
328 int32_t count, int32_t percentageOfInUseItems, UErrorCode &status);
329
330
331 /**
332 * Returns how many entries have been auto evicted during the lifetime
333 * of this cache. This only includes auto evicted entries, not
334 * entries evicted because of a call to flush().
335 */
336 int64_t autoEvictedCount() const;
337
338 /**
339 * Returns the unused entry count in this cache. For testing only,
340 * Regular clients will not need this.
341 */
342 int32_t unusedCount() const;
343
344 virtual void handleUnreferencedObject() const override;
345 virtual ~UnifiedCache();
346
347 private:
348 UHashtable *fHashtable;
349 mutable int32_t fEvictPos;
350 mutable int32_t fNumValuesTotal;
351 mutable int32_t fNumValuesInUse;
352 int32_t fMaxUnused;
353 int32_t fMaxPercentageOfInUse;
354 mutable int64_t fAutoEvictedCount;
355 SharedObject *fNoValue;
356
357 UnifiedCache(const UnifiedCache &other) = delete;
358 UnifiedCache &operator=(const UnifiedCache &other) = delete;
359
360 /**
361 * Flushes the contents of the cache. If cache values hold references to other
362 * cache values then _flush should be called in a loop until it returns false.
363 *
364 * On entry, gCacheMutex must be held.
365 * On exit, those values with are evictable are flushed.
366 *
367 * @param all if false flush evictable items only, which are those with no external
368 * references, plus those that can be safely recreated.<br>
369 * if true, flush all elements. Any values (sharedObjects) with remaining
370 * hard (external) references are not deleted, but are detached from
371 * the cache, so that a subsequent removeRefs can delete them.
372 * _flush is not thread safe when all is true.
373 * @return true if any value in cache was flushed or false otherwise.
374 */
375 UBool _flush(UBool all) const;
376
377 /**
378 * Gets value out of cache.
379 * On entry. gCacheMutex must not be held. value must be nullptr. status
380 * must be U_ZERO_ERROR.
381 * On exit. value and status set to what is in cache at key or on cache
382 * miss the key's createObject() is called and value and status are set to
383 * the result of that. In this latter case, best effort is made to add the
384 * value and status to the cache. If createObject() fails to create a value,
385 * fNoValue is stored in cache, and value is set to nullptr. Caller must call
386 * removeRef on value if non nullptr.
387 */
388 void _get(
389 const CacheKeyBase &key,
390 const SharedObject *&value,
391 const void *creationContext,
392 UErrorCode &status) const;
393
394 /**
395 * Attempts to fetch value and status for key from cache.
396 * On entry, gCacheMutex must not be held value must be nullptr and status must
397 * be U_ZERO_ERROR.
398 * On exit, either returns false (In this
399 * case caller should try to create the object) or returns true with value
400 * pointing to the fetched value and status set to fetched status. When
401 * false is returned status may be set to failure if an in progress hash
402 * entry could not be made but value will remain unchanged. When true is
403 * returned, caller must call removeRef() on value.
404 */
405 UBool _poll(
406 const CacheKeyBase &key,
407 const SharedObject *&value,
408 UErrorCode &status) const;
409
410 /**
411 * Places a new value and creationStatus in the cache for the given key.
412 * On entry, gCacheMutex must be held. key must not exist in the cache.
413 * On exit, value and creation status placed under key. Soft reference added
414 * to value on successful add. On error sets status.
415 */
416 void _putNew(
417 const CacheKeyBase &key,
418 const SharedObject *value,
419 const UErrorCode creationStatus,
420 UErrorCode &status) const;
421
422 /**
423 * Places value and status at key if there is no value at key or if cache
424 * entry for key is in progress. Otherwise, it leaves the current value and
425 * status there.
426 *
427 * On entry. gCacheMutex must not be held. Value must be
428 * included in the reference count of the object to which it points.
429 *
430 * On exit, value and status are changed to what was already in the cache if
431 * something was there and not in progress. Otherwise, value and status are left
432 * unchanged in which case they are placed in the cache on a best-effort basis.
433 * Caller must call removeRef() on value.
434 */
435 void _putIfAbsentAndGet(
436 const CacheKeyBase &key,
437 const SharedObject *&value,
438 UErrorCode &status) const;
439
440 /**
441 * Returns the next element in the cache round robin style.
442 * Returns nullptr if the cache is empty.
443 * On entry, gCacheMutex must be held.
444 */
445 const UHashElement *_nextElement() const;
446
447 /**
448 * Return the number of cache items that would need to be evicted
449 * to bring usage into conformance with eviction policy.
450 *
451 * An item corresponds to an entry in the hash table, a hash table element.
452 *
453 * On entry, gCacheMutex must be held.
454 */
455 int32_t _computeCountOfItemsToEvict() const;
456
457 /**
458 * Run an eviction slice.
459 * On entry, gCacheMutex must be held.
460 * _runEvictionSlice runs a slice of the evict pipeline by examining the next
461 * 10 entries in the cache round robin style evicting them if they are eligible.
462 */
463 void _runEvictionSlice() const;
464
465 /**
466 * Register a primary cache entry. A primary key is the first key to create
467 * a given SharedObject value. Subsequent keys whose create function
468 * produce references to an already existing SharedObject are not primary -
469 * they can be evicted and subsequently recreated.
470 *
471 * On entry, gCacheMutex must be held.
472 * On exit, items in use count incremented, entry is marked as a primary
473 * entry, and value registered with cache so that subsequent calls to
474 * addRef() and removeRef() on it correctly interact with the cache.
475 */
476 void _registerPrimary(const CacheKeyBase *theKey, const SharedObject *value) const;
477
478 /**
479 * Store a value and creation error status in given hash entry.
480 * On entry, gCacheMutex must be held. Hash entry element must be in progress.
481 * value must be non nullptr.
482 * On Exit, soft reference added to value. value and status stored in hash
483 * entry. Soft reference removed from previous stored value. Waiting
484 * threads notified.
485 */
486 void _put(
487 const UHashElement *element,
488 const SharedObject *value,
489 const UErrorCode status) const;
490 /**
491 * Remove a soft reference, and delete the SharedObject if no references remain.
492 * To be used from within the UnifiedCache implementation only.
493 * gCacheMutex must be held by caller.
494 * @param value the SharedObject to be acted on.
495 */
496 void removeSoftRef(const SharedObject *value) const;
497
498 /**
499 * Increment the hard reference count of the given SharedObject.
500 * gCacheMutex must be held by the caller.
501 * Update numValuesEvictable on transitions between zero and one reference.
502 *
503 * @param value The SharedObject to be referenced.
504 * @return the hard reference count after the addition.
505 */
506 int32_t addHardRef(const SharedObject *value) const;
507
508 /**
509 * Decrement the hard reference count of the given SharedObject.
510 * gCacheMutex must be held by the caller.
511 * Update numValuesEvictable on transitions between one and zero reference.
512 *
513 * @param value The SharedObject to be referenced.
514 * @return the hard reference count after the removal.
515 */
516 int32_t removeHardRef(const SharedObject *value) const;
517
518
519#ifdef UNIFIED_CACHE_DEBUG
520 void _dumpContents() const;
521#endif
522
523 /**
524 * Fetch value and error code from a particular hash entry.
525 * On entry, gCacheMutex must be held. value must be either nullptr or must be
526 * included in the ref count of the object to which it points.
527 * On exit, value and status set to what is in the hash entry. Caller must
528 * eventually call removeRef on value.
529 * If hash entry is in progress, value will be set to gNoValue and status will
530 * be set to U_ZERO_ERROR.
531 */
532 void _fetch(const UHashElement *element, const SharedObject *&value,
533 UErrorCode &status) const;
534
535 /**
536 * Determine if given hash entry is in progress.
537 * On entry, gCacheMutex must be held.
538 */
539 UBool _inProgress(const UHashElement *element) const;
540
541 /**
542 * Determine if given hash entry is in progress.
543 * On entry, gCacheMutex must be held.
544 */
545 UBool _inProgress(const SharedObject *theValue, UErrorCode creationStatus) const;
546
547 /**
548 * Determine if given hash entry is eligible for eviction.
549 * On entry, gCacheMutex must be held.
550 */
551 UBool _isEvictable(const UHashElement *element) const;
552};
553
554U_NAMESPACE_END}
555
556#endif

/root/firefox-clang/intl/icu/source/common/sharedobject.h

1// © 2016 and later: Unicode, Inc. and others.
2// License & terms of use: http://www.unicode.org/copyright.html
3/*
4******************************************************************************
5* Copyright (C) 2015-2016, International Business Machines
6* Corporation and others. All Rights Reserved.
7******************************************************************************
8* sharedobject.h
9*/
10
11#ifndef __SHAREDOBJECT_H__
12#define __SHAREDOBJECT_H__
13
14
15#include "unicode/uobject.h"
16#include "umutex.h"
17
18U_NAMESPACE_BEGINnamespace icu_77 {
19
20class SharedObject;
21
22/**
23 * Base class for unified cache exposing enough methods to SharedObject
24 * instances to allow their addRef() and removeRef() methods to
25 * update cache metrics. No other part of ICU, except for SharedObject,
26 * should directly call the methods of this base class.
27 */
28class U_COMMON_API UnifiedCacheBase : public UObject {
29public:
30 UnifiedCacheBase() { }
31
32 /**
33 * Notify the cache implementation that an object was seen transitioning to
34 * zero hard references. The cache may use this to keep track the number of
35 * unreferenced SharedObjects, and to trigger evictions.
36 */
37 virtual void handleUnreferencedObject() const = 0;
38
39 virtual ~UnifiedCacheBase();
40private:
41 UnifiedCacheBase(const UnifiedCacheBase &) = delete;
42 UnifiedCacheBase &operator=(const UnifiedCacheBase &) = delete;
43};
44
45/**
46 * Base class for shared, reference-counted, auto-deleted objects.
47 * Subclasses can be immutable.
48 * If they are mutable, then they must implement their copy constructor
49 * so that copyOnWrite() works.
50 *
51 * Either stack-allocate, use LocalPointer, or use addRef()/removeRef().
52 * Sharing requires reference-counting.
53 */
54class U_COMMON_API SharedObject : public UObject {
55public:
56 /** Initializes totalRefCount, softRefCount to 0. */
57 SharedObject() :
58 softRefCount(0),
59 hardRefCount(0),
60 cachePtr(nullptr) {}
61
62 /** Initializes totalRefCount, softRefCount to 0. */
63 SharedObject(const SharedObject &other) :
64 UObject(other),
65 softRefCount(0),
66 hardRefCount(0),
67 cachePtr(nullptr) {}
68
69 virtual ~SharedObject();
70
71 /**
72 * Increments the number of hard references to this object. Thread-safe.
73 * Not for use from within the Unified Cache implementation.
74 */
75 void addRef() const;
76
77 /**
78 * Decrements the number of hard references to this object, and
79 * arrange for possible cache-eviction and/or deletion if ref
80 * count goes to zero. Thread-safe.
81 *
82 * Not for use from within the UnifiedCache implementation.
83 */
84 void removeRef() const;
85
86 /**
87 * Returns the number of hard references for this object.
88 * Uses a memory barrier.
89 */
90 int32_t getRefCount() const;
91
92 /**
93 * If noHardReferences() == true then this object has no hard references.
94 * Must be called only from within the internals of UnifiedCache.
95 */
96 inline UBool noHardReferences() const { return getRefCount() == 0; }
97
98 /**
99 * If hasHardReferences() == true then this object has hard references.
100 * Must be called only from within the internals of UnifiedCache.
101 */
102 inline UBool hasHardReferences() const { return getRefCount() != 0; }
103
104 /**
105 * Deletes this object if it has no references.
106 * Available for non-cached SharedObjects only. Ownership of cached objects
107 * is with the UnifiedCache, which is solely responsible for eviction and deletion.
108 */
109 void deleteIfZeroRefCount() const;
110
111
112 /**
113 * Returns a writable version of ptr.
114 * If there is exactly one owner, then ptr itself is returned as a
115 * non-const pointer.
116 * If there are multiple owners, then ptr is replaced with a
117 * copy-constructed clone,
118 * and that is returned.
119 * Returns nullptr if cloning failed.
120 *
121 * T must be a subclass of SharedObject.
122 */
123 template<typename T>
124 static T *copyOnWrite(const T *&ptr) {
125 const T *p = ptr;
126 if(p->getRefCount() <= 1) { return const_cast<T *>(p); }
127 T *p2 = new T(*p);
128 if(p2 == nullptr) { return nullptr; }
129 p->removeRef();
130 ptr = p2;
131 p2->addRef();
132 return p2;
133 }
134
135 /**
136 * Makes dest an owner of the object pointed to by src while adjusting
137 * reference counts and deleting the previous object dest pointed to
138 * if necessary. Before this call is made, dest must either be nullptr or
139 * be included in the reference count of the object it points to.
140 *
141 * T must be a subclass of SharedObject.
142 */
143 template<typename T>
144 static void copyPtr(const T *src, const T *&dest) {
145 if(src != dest) {
11
Assuming 'src' is equal to 'dest'
12
Taking false branch
146 if(dest != nullptr) { dest->removeRef(); }
147 dest = src;
148 if(src != nullptr) { src->addRef(); }
149 }
150 }
13
Returning without writing to 'dest'
151
152 /**
153 * Equivalent to copyPtr(nullptr, dest).
154 */
155 template<typename T>
156 static void clearPtr(const T *&ptr) {
157 if (ptr != nullptr) {
158 ptr->removeRef();
159 ptr = nullptr;
160 }
161 }
162
163private:
164 /**
165 * The number of references from the UnifiedCache, which is
166 * the number of times that the sharedObject is stored as a hash table value.
167 * For use by UnifiedCache implementation code only.
168 * All access is synchronized by UnifiedCache's gCacheMutex
169 */
170 mutable int32_t softRefCount;
171 friend class UnifiedCache;
172
173 /**
174 * Reference count, excluding references from within the UnifiedCache implementation.
175 */
176 mutable u_atomic_int32_t hardRefCount;
177
178 mutable const UnifiedCacheBase *cachePtr;
179
180};
181
182U_NAMESPACE_END}
183
184#endif