1// Licensed to the .NET Foundation under one or more agreements.
2// The .NET Foundation licenses this file to you under the MIT license.
3// See the LICENSE file in the project root for more information.
4
5// IcuHolder is a template that can manage the lifetime of a raw pointer to ensure that it is cleaned up at the correct
6// time. The general usage pattern is to aquire some ICU resource via an _open call, then construct a holder using the
7// pointer and UErrorCode to manage the lifetime. When the holder goes out of scope, the coresponding close method is
8// called on the pointer.
9template <typename T, typename Closer>
10class IcuHolder
11{
12 public:
13 IcuHolder(T* p, UErrorCode err)
14 {
15 m_p = U_SUCCESS(err) ? p : nullptr;
16 }
17
18 ~IcuHolder()
19 {
20 if (m_p != nullptr)
21 {
22 Closer()(m_p);
23 }
24 }
25
26 private:
27 T* m_p;
28 IcuHolder(const IcuHolder&) = delete;
29 IcuHolder operator=(const IcuHolder&) = delete;
30};
31
32struct UCalendarCloser
33{
34 void operator()(UCalendar* pCal) const
35 {
36 ucal_close(pCal);
37 }
38};
39
40struct UEnumerationCloser
41{
42 void operator()(UEnumeration* pEnum) const
43 {
44 uenum_close(pEnum);
45 }
46};
47
48struct UDateTimePatternGeneratorCloser
49{
50 void operator()(UDateTimePatternGenerator* pGenerator) const
51 {
52 udatpg_close(pGenerator);
53 }
54};
55
56struct UDateFormatCloser
57{
58 void operator()(UDateFormat* pDateFormat) const
59 {
60 udat_close(pDateFormat);
61 }
62};
63
64struct UNumberFormatCloser
65{
66 void operator()(UNumberFormat* pNumberFormat) const
67 {
68 unum_close(pNumberFormat);
69 }
70};
71
72struct ULocaleDisplayNamesCloser
73{
74 void operator()(ULocaleDisplayNames* pLocaleDisplayNames) const
75 {
76 uldn_close(pLocaleDisplayNames);
77 }
78};
79
80struct UResourceBundleCloser
81{
82 void operator()(UResourceBundle* pResourceBundle) const
83 {
84 ures_close(pResourceBundle);
85 }
86};
87
88typedef IcuHolder<UCalendar, UCalendarCloser> UCalendarHolder;
89typedef IcuHolder<UEnumeration, UEnumerationCloser> UEnumerationHolder;
90typedef IcuHolder<UDateTimePatternGenerator, UDateTimePatternGeneratorCloser> UDateTimePatternGeneratorHolder;
91typedef IcuHolder<UDateFormat, UDateFormatCloser> UDateFormatHolder;
92typedef IcuHolder<UNumberFormat, UNumberFormatCloser> UNumberFormatHolder;
93typedef IcuHolder<ULocaleDisplayNames, ULocaleDisplayNamesCloser> ULocaleDisplayNamesHolder;
94typedef IcuHolder<UResourceBundle, UResourceBundleCloser> UResourceBundleHolder;
95