1 | //===-- CFUtils.h -----------------------------------------------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // Created by Greg Clayton on 3/5/07. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLDB_TOOLS_DEBUGSERVER_SOURCE_MACOSX_CFUTILS_H |
14 | #define LLDB_TOOLS_DEBUGSERVER_SOURCE_MACOSX_CFUTILS_H |
15 | |
16 | #include <CoreFoundation/CoreFoundation.h> |
17 | |
18 | // Templatized CF helper class that can own any CF pointer and will |
19 | // call CFRelease() on any valid pointer it owns unless that pointer is |
20 | // explicitly released using the release() member function. |
21 | template <class T> class CFReleaser { |
22 | public: |
23 | // Type names for the value |
24 | typedef T element_type; |
25 | |
26 | // Constructors and destructors |
27 | CFReleaser(T ptr = NULL) : _ptr(ptr) {} |
28 | CFReleaser(const CFReleaser ©) : _ptr(copy.get()) { |
29 | if (get()) |
30 | ::CFRetain(get()); |
31 | } |
32 | virtual ~CFReleaser() { reset(); } |
33 | |
34 | // Assignments |
35 | CFReleaser &operator=(const CFReleaser<T> ©) { |
36 | if (copy != *this) { |
37 | // Replace our owned pointer with the new one |
38 | reset(ptr: copy.get()); |
39 | // Retain the current pointer that we own |
40 | if (get()) |
41 | ::CFRetain(get()); |
42 | } |
43 | } |
44 | // Get the address of the contained type |
45 | T *ptr_address() { return &_ptr; } |
46 | |
47 | // Access the pointer itself |
48 | const T get() const { return _ptr; } |
49 | T get() { return _ptr; } |
50 | |
51 | // Set a new value for the pointer and CFRelease our old |
52 | // value if we had a valid one. |
53 | void reset(T ptr = NULL) { |
54 | if (ptr != _ptr) { |
55 | if (_ptr != NULL) |
56 | ::CFRelease(_ptr); |
57 | _ptr = ptr; |
58 | } |
59 | } |
60 | |
61 | // Release ownership without calling CFRelease |
62 | T release() { |
63 | T tmp = _ptr; |
64 | _ptr = NULL; |
65 | return tmp; |
66 | } |
67 | |
68 | private: |
69 | element_type _ptr; |
70 | }; |
71 | |
72 | #endif // LLDB_TOOLS_DEBUGSERVER_SOURCE_MACOSX_CFUTILS_H |
73 | |