File: weak_ptr.hpp

package info (click to toggle)
dnf5 5.4.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 17,960 kB
  • sloc: cpp: 94,312; python: 3,370; xml: 1,073; ruby: 600; sql: 250; ansic: 232; sh: 104; perl: 62; makefile: 30
file content (242 lines) | stat: -rw-r--r-- 8,361 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Copyright Contributors to the DNF5 project.
// Copyright Contributors to the libdnf project.
// SPDX-License-Identifier: LGPL-2.1-or-later
//
// This file is part of libdnf: https://github.com/rpm-software-management/libdnf/
//
// Libdnf is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or
// (at your option) any later version.
//
// Libdnf is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with libdnf.  If not, see <https://www.gnu.org/licenses/>.

#ifndef LIBDNF5_UTILS_WEAK_PTR_HPP
#define LIBDNF5_UTILS_WEAK_PTR_HPP

#include "exception.hpp"

#include <mutex>
#include <unordered_set>


namespace libdnf5 {

template <typename TPtr, bool ptr_owner>
struct WeakPtr;


/// WeakPtrGuard is a resource guard. WeakPtr instances register itself to the resource guard.
/// And the resource guard invalidates the registered WeakPtrs when the resource is unusable
/// (eg. its dependecny was released).
/// Note on thread safety:
/// Destroying the WeakPtrGuard while simultaneously using its WeakPtrs in another thread is not safe
/// and can still trigger a race condition.
template <typename TPtr, bool weak_ptr_is_owner>
struct WeakPtrGuard {
public:
    using TWeakPtr = WeakPtr<TPtr, weak_ptr_is_owner>;

    WeakPtrGuard() = default;
    WeakPtrGuard(const WeakPtrGuard &) = delete;
    WeakPtrGuard(WeakPtrGuard && src) noexcept = delete;
    ~WeakPtrGuard() { clear(); }

    WeakPtrGuard & operator=(const WeakPtrGuard & src) = delete;
    WeakPtrGuard & operator=(WeakPtrGuard && src) noexcept = delete;

    /// Returns true if the guard is empty, false otherwise.
    bool empty() const noexcept {
        std::lock_guard<std::mutex> guard(registered_weak_ptrs_mutex);
        return registered_weak_ptrs.empty();
    }

    /// Returns the number of registered weak pointers.
    size_t size() const noexcept {
        std::lock_guard<std::mutex> guard(registered_weak_ptrs_mutex);
        return registered_weak_ptrs.size();
    }

    /// Deregisters and invalidates all registered weak pointers. After this call, size() returns zero.
    void clear() noexcept {
        std::lock_guard<std::mutex> guard(registered_weak_ptrs_mutex);
        for (auto it : registered_weak_ptrs) {
            it->invalidate_guard();
        }
        registered_weak_ptrs.clear();
    }

private:
    friend TWeakPtr;
    void register_ptr(TWeakPtr * weak_ptr) {
        std::lock_guard<std::mutex> guard(registered_weak_ptrs_mutex);
        registered_weak_ptrs.insert(weak_ptr);
    }
    void unregister_ptr(TWeakPtr * weak_ptr) noexcept {
        std::lock_guard<std::mutex> guard(registered_weak_ptrs_mutex);
        registered_weak_ptrs.erase(weak_ptr);
    }
    std::unordered_set<TWeakPtr *> registered_weak_ptrs;
    mutable std::mutex registered_weak_ptrs_mutex;
};


/// WeakPtr is a "smart" pointer. It contains a pointer to resource and to guard of resource.
/// WeakPtr pointer can be owner of the resource. However, the resource itself may depend on another resource.
/// WeakPtr registers/unregisters itself at the guard of resource. And the resource guard invalidates
/// the registered WeakPtrs when the resource is unusable (eg. its dependecny was released).
/// Note on thread safety:
/// It is safe to create, access and destroy WeakPtrs in multiple threads simultaneously.
template <typename TPtr, bool ptr_owner>
struct WeakPtr {
public:
    using TWeakPtrGuard = WeakPtrGuard<TPtr, ptr_owner>;

    WeakPtr() : ptr(nullptr), guard(nullptr) {}

    WeakPtr(TPtr * ptr, TWeakPtrGuard * guard) : ptr(ptr), guard(guard) {
        libdnf_assert(guard != nullptr, "When initializing WeakPtr with a pointer, guard cannot be nullptr");
        guard->register_ptr(this);
    }

    // TODO(jrohel): Want we to allow copying invalid WeakPtr?
    WeakPtr(const WeakPtr & src) : guard(src.guard) {
        if constexpr (ptr_owner) {
            ptr = src.ptr ? new TPtr(*src.ptr) : nullptr;
        } else {
            ptr = src.ptr;
        }
        if (is_valid()) {
            guard->register_ptr(this);
        }
    }

    // TODO(jrohel): Want we to allow moving invalid WeakPtr?
    template <typename T = TPtr, typename std::enable_if<sizeof(T) && ptr_owner, int>::type = 0>
    WeakPtr(WeakPtr && src) : guard(src.guard) {
        if (src.is_valid()) {
            src.guard->unregister_ptr(&src);
        }
        src.guard = nullptr;
        ptr = src.ptr;
        src.ptr = nullptr;
        if (is_valid()) {
            guard->register_ptr(this);
        }
    }

    ~WeakPtr() {
        if (is_valid()) {
            guard->unregister_ptr(this);
        }
        if constexpr (ptr_owner) {
            delete ptr;
        }
    }

    // TODO(jrohel): Want we to allow copying invalid WeakPtr?
    WeakPtr & operator=(const WeakPtr & src) {
        if (guard == src.guard) {
            if (this == &src) {
                return *this;
            }
            if constexpr (ptr_owner) {
                delete ptr;
                ptr = src.ptr ? new TPtr(*src.ptr) : nullptr;
            } else {
                ptr = src.ptr;
            }
        } else {
            if (is_valid()) {
                guard->unregister_ptr(this);
            }
            guard = src.guard;
            if constexpr (ptr_owner) {
                delete ptr;
                ptr = src.ptr ? new TPtr(*src.ptr) : nullptr;
            } else {
                ptr = src.ptr;
            }
            if (is_valid()) {
                guard->register_ptr(this);
            }
        }
        return *this;
    }

    // TODO(jrohel): Want we to allow moving invalid WeakPtr?
    template <typename T = TPtr, typename std::enable_if<sizeof(T) && ptr_owner, int>::type = 0>
    WeakPtr & operator=(WeakPtr && src) {
        if (guard == src.guard) {
            if (this == &src) {
                return *this;
            }
            if (src.is_valid()) {
                src.guard->unregister_ptr(&src);
            }
            src.guard = nullptr;
            delete ptr;
            ptr = src.ptr;
            src.ptr = nullptr;
        } else {
            if (is_valid()) {
                guard->unregister_ptr(this);
            }
            if (src.is_valid()) {
                src.guard->unregister_ptr(&src);
            }
            guard = src.guard;
            src.guard = nullptr;
            delete ptr;
            ptr = src.ptr;
            src.ptr = nullptr;
            if (is_valid()) {
                guard->register_ptr(this);
            }
        }
        return *this;
    }

    /// Provides access to the managed object. Generates exception if object is not valid.
    TPtr * operator->() const {
        libdnf_assert(is_valid(), "Dereferencing an invalidated WeakPtr");
        return ptr;
    }

    /// Returns a pointer to the managed object. Generates exception if object is not valid.
    TPtr * get() const {
        libdnf_assert(is_valid(), "Dereferencing an invalidated WeakPtr");
        return ptr;
    }

    /// Checks if managed object is valid.
    bool is_valid() const noexcept { return guard; }

    /// Checks if the other WeakPtr instance has the same WeakPtrGuard.
    bool has_same_guard(const WeakPtr & other) const noexcept { return guard == other.guard; }

    TPtr & operator*() const { return *get(); }
    bool operator==(const WeakPtr & other) const { return ptr == other.ptr; }
    bool operator!=(const WeakPtr & other) const { return ptr != other.ptr; }
    bool operator<(const WeakPtr & other) const { return ptr < other.ptr; }
    bool operator>(const WeakPtr & other) const { return ptr > other.ptr; }
    bool operator<=(const WeakPtr & other) const { return ptr <= other.ptr; }
    bool operator>=(const WeakPtr & other) const { return ptr >= other.ptr; }

private:
    friend TWeakPtrGuard;
    void invalidate_guard() noexcept { guard = nullptr; }

    TPtr * ptr;
    TWeakPtrGuard * guard;
};

}  // namespace libdnf5

#endif