summaryrefslogtreecommitdiffstats
path: root/src/corelib/tools/quniquehandle_p.h
blob: 7af1536c2edf6aa32a1d2bd15e2ba1a70a3785f6 (plain)
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
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#ifndef QUNIQUEHANDLE_P_H
#define QUNIQUEHANDLE_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <QtCore/qtconfigmacros.h>
#include <QtCore/qassert.h>

#include <memory>

QT_BEGIN_NAMESPACE

/*! \internal QUniqueHandle is a general purpose RAII wrapper intended
    for interfacing with resource-allocating C-style APIs, for example
    operating system APIs, database engine APIs, or any other scenario
    where resources are allocated and released, and where pointer
    semantics does not seem a perfect fit.

    QUniqueHandle does not support copying, because it is intended to
    maintain ownership of resources that can not be copied. This makes
    it safer to use than naked handle types, since ownership is
    maintained by design.

    The underlying handle object is described using a client supplied
    HandleTraits object that is implemented per resource type. The
    traits struct must describe two properties of a handle:

    1) What value is considered invalid
    2) How to close a resource.

    Example 1:

        struct InvalidHandleTraits {
            using Type = HANDLE;

            static Type invalidValue() {
                return INVALID_HANDLE_VALUE;
            }

            static bool close(Type handle) {
                return CloseHandle(handle) != 0;
            }
        }

        using FileHandle = QUniqueHandle<InvalidHandleTraits>;

    Usage:

        // Takes ownership of returned handle.
        FileHandle handle{ CreateFile(...) };

        if (!handle.isValid()) {
            qDebug() << GetLastError()
            return;
        }

        ...

    Example 2:

        struct SqLiteTraits {
            using Type = sqlite3*;

            static Type invalidValue() {
                return nullptr;
            }

            static bool close(Type handle) {
                sqlite3_close(handle);
                return true;
            }
        }

        using DbHandle = QUniqueHandle<SqLiteTraits>;

    Usage:

        DbHandle h;

        // Take ownership of returned handle.
        int result = sqlite3_open(":memory:", &h);

        ...

    NOTE: The QUniqueHandle assumes that closing a resource is
    guaranteed to succeed, and provides no support for handling failure
    to close a resource. It is therefore only recommended for use cases
    where failure to close a resource is either not an error, or an
    unrecoverable error.
*/

// clang-format off

template <typename HandleTraits>
class QUniqueHandle
{
public:
    using Type = typename HandleTraits::Type;

    QUniqueHandle() = default;

    explicit QUniqueHandle(const Type &handle) noexcept
        : m_handle{ handle }
    {}

    QUniqueHandle(QUniqueHandle &&other) noexcept
        : m_handle{ other.release() }
    {}

    ~QUniqueHandle() noexcept
    {
        close();
    }

    QUniqueHandle& operator=(QUniqueHandle &&rhs) noexcept
    {
        if (this != std::addressof(rhs))
            reset(rhs.release());

        return *this;
    }

    QUniqueHandle(const QUniqueHandle &) = delete;
    QUniqueHandle &operator=(const QUniqueHandle &) = delete;


    [[nodiscard]] bool isValid() const noexcept
    {
        return m_handle != HandleTraits::invalidValue();
    }

    [[nodiscard]] explicit operator bool() const noexcept
    {
        return isValid();
    }

    [[nodiscard]] Type get() const noexcept
    {
        return m_handle;
    }

    void reset(const Type& handle) noexcept
    {
        if (handle == m_handle)
            return;

        close();
        m_handle = handle;
    }

    [[nodiscard]] Type release() noexcept
    {
        Type handle = m_handle;
        m_handle = HandleTraits::invalidValue();
        return handle;
    }

    [[nodiscard]] Type *operator&() noexcept  // NOLINT(google-runtime-operator)
    {
        Q_ASSERT(!isValid());
        return &m_handle;
    }

    void close() noexcept
    {
        if (!isValid())
            return;

        const bool success = HandleTraits::close(m_handle);
        Q_ASSERT(success);

        m_handle = HandleTraits::invalidValue();
    }

    [[nodiscard]] friend bool operator==(const QUniqueHandle &lhs, const QUniqueHandle &rhs) noexcept
    {
        return lhs.get() == rhs.get();
    }

    [[nodiscard]] friend bool operator!=(const QUniqueHandle &lhs, const QUniqueHandle &rhs) noexcept
    {
        return lhs.get() != rhs.get();
    }

    [[nodiscard]] friend bool operator<(const QUniqueHandle &lhs, const QUniqueHandle &rhs) noexcept
    {
        return lhs.get() < rhs.get();
    }

    [[nodiscard]] friend bool operator<=(const QUniqueHandle &lhs, const QUniqueHandle &rhs) noexcept
    {
        return lhs.get() <= rhs.get();
    }

    [[nodiscard]] friend bool operator>(const QUniqueHandle &lhs, const QUniqueHandle &rhs) noexcept
    {
        return lhs.get() > rhs.get();
    }

    [[nodiscard]] friend bool operator>=(const QUniqueHandle &lhs, const QUniqueHandle &rhs) noexcept
    {
        return lhs.get() >= rhs.get();
    }

private:
    Type m_handle{ HandleTraits::invalidValue() };
};

// clang-format on

QT_END_NAMESPACE

#endif