Bug Summary

File:out/../deps/icu-small/source/i18n/datefmt.cpp
Warning:line 442, column 19
Forming reference to null pointer

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 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 -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/datefmt.cpp

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

../deps/icu-small/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_71 {
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 NULL
61 * and set status to an error.
62 *
63 * @param creationContext the context in which the object is being
64 * created. May be NULL.
65 * @param status Implementations can return a failure here.
66 * In addition, implementations may return a
67 * non NULL 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 NULL 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_71(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, NULL, 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, NULL__null, 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 NULL 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 NULL 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 = NULL__null;
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 == NULL.
258 * @param loc the locale
259 * @param ptr On entry, must be NULL 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 NULL 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);
358 UnifiedCache &operator=(const UnifiedCache &other);
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 NULL. 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 NULL. Caller must call
386 * removeRef on value if non NULL.
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 NULL 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 NULL.
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 NULL 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

../deps/icu-small/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_71 {
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 &);
42 UnifiedCacheBase &operator=(const UnifiedCacheBase &);
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(NULL__null) {}
61
62 /** Initializes totalRefCount, softRefCount to 0. */
63 SharedObject(const SharedObject &other) :
64 UObject(other),
65 softRefCount(0),
66 hardRefCount(0),
67 cachePtr(NULL__null) {}
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 NULL 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 == NULL__null) { return NULL__null; }
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 NULL 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 != NULL__null) { dest->removeRef(); }
147 dest = src;
148 if(src != NULL__null) { src->addRef(); }
149 }
150 }
13
Returning without writing to 'dest'
151
152 /**
153 * Equivalent to copyPtr(NULL, dest).
154 */
155 template<typename T>
156 static void clearPtr(const T *&ptr) {
157 if (ptr != NULL__null) {
158 ptr->removeRef();
159 ptr = NULL__null;
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