aboutsummaryrefslogtreecommitdiff
path: root/lib/util.h
blob: 7769abce3f6ac23993f4d572f2c12ba697bd3339 (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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/******************************************************************************
 * Copyright (C) 2016 Kitsune Ral <kitsune-ral@users.sf.net>
 *
 * This library 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.
 *
 * This library 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 this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#pragma once

#include <QtCore/QPointer>
#if (QT_VERSION < QT_VERSION_CHECK(5, 5, 0))
#include <QtCore/QMetaEnum>
#include <QtCore/QDebug>
#endif

#include <functional>
#include <memory>

#if __cplusplus >= 201703L
#define FALLTHROUGH [[fallthrough]]
#elif __has_cpp_attribute(clang::fallthrough)
#define FALLTHROUGH [[clang::fallthrough]]
#else
#define FALLTHROUGH // -fallthrough
#endif

// Along the lines of Q_DISABLE_COPY
#define DISABLE_MOVE(_ClassName) \
    _ClassName(_ClassName&&) Q_DECL_EQ_DELETE; \
    _ClassName& operator=(_ClassName&&) Q_DECL_EQ_DELETE;

namespace QMatrixClient
{
    // The below enables pretty-printing of enums in logs
#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0))
#define REGISTER_ENUM(EnumName) Q_ENUM(EnumName)
#else
    // Thanks to Olivier for spelling it and for making Q_ENUM to replace it:
    // https://woboq.com/blog/q_enum.html
#define REGISTER_ENUM(EnumName) \
    Q_ENUMS(EnumName) \
    friend QDebug operator<<(QDebug dbg, EnumName val) \
    { \
        static int enumIdx = staticMetaObject.indexOfEnumerator(#EnumName); \
        return dbg << Event::staticMetaObject.enumerator(enumIdx).valueToKey(int(val)); \
    }
#endif

    /** static_cast<> for unique_ptr's */
    template <typename T1, typename PtrT2>
    inline auto unique_ptr_cast(PtrT2&& p)
    {
        return std::unique_ptr<T1>(static_cast<T1*>(p.release()));
    }

    struct NoneTag {};
    constexpr NoneTag none {};

    /** A crude substitute for `optional` while we're not C++17
     *
     * Only works with default-constructible types.
     */
    template <typename T>
    class Omittable
    {
            static_assert(!std::is_reference<T>::value,
                "You cannot make an Omittable<> with a reference type");
        public:
            explicit Omittable() : Omittable(none) { }
            Omittable(NoneTag) : _value(std::decay_t<T>()), _omitted(true) { }
            Omittable(const std::decay_t<T>& val) : _value(val) { }
            Omittable(std::decay_t<T>&& val) : _value(std::move(val)) { }
            Omittable<T>& operator=(const std::decay_t<T>& val)
            {
                _value = val;
                _omitted = false;
                return *this;
            }
            Omittable<T>& operator=(std::decay_t<T>&& val)
            {
                _value = std::move(val);
                _omitted = false;
                return *this;
            }

            bool omitted() const { return _omitted; }
            const std::decay_t<T>& value() const { Q_ASSERT(!_omitted); return _value; }
            std::decay_t<T>& value() { Q_ASSERT(!_omitted); return _value; }
            std::decay_t<T>&& release() { _omitted = true; return std::move(_value); }

            operator bool() const { return !omitted(); }
            const std::decay<T>* operator->() const { return &value(); }
            std::decay_t<T>* operator->() { return &value(); }
            const std::decay_t<T>& operator*() const { return value(); }
            std::decay_t<T>& operator*() { return value(); }

        private:
            T _value;
            bool _omitted = false;
    };

    /** Determine traits of an arbitrary function/lambda/functor
     * This only works with arity of 1 (1-argument) for now but is extendable
     * to other cases. Also, doesn't work with generic lambdas and function
     * objects that have operator() overloaded
     * \sa https://stackoverflow.com/questions/7943525/is-it-possible-to-figure-out-the-parameter-type-and-return-type-of-a-lambda#7943765
     */
    template <typename T>
    struct function_traits : public function_traits<decltype(&T::operator())>
    { }; // A generic function object that has (non-overloaded) operator()

    // Specialisation for a function
    template <typename ReturnT, typename ArgT>
    struct function_traits<ReturnT(ArgT)>
    {
        using return_type = ReturnT;
        using arg_type = ArgT;
    };

    // Specialisation for a member function
    template <typename ReturnT, typename ClassT, typename ArgT>
    struct function_traits<ReturnT(ClassT::*)(ArgT)>
        : function_traits<ReturnT(ArgT)>
    { };

    // Specialisation for a const member function
    template <typename ReturnT, typename ClassT, typename ArgT>
    struct function_traits<ReturnT(ClassT::*)(ArgT) const>
        : function_traits<ReturnT(ArgT)>
    { };

    template <typename FnT>
    using fn_return_t = typename function_traits<FnT>::return_type;

    template <typename FnT>
    using fn_arg_t = typename function_traits<FnT>::arg_type;

#if QT_VERSION < QT_VERSION_CHECK(5, 7, 0)
    // Copy-pasted from Qt 5.10
    template <typename T>
    Q_DECL_CONSTEXPR typename std::add_const<T>::type &qAsConst(T &t) Q_DECL_NOTHROW { return t; }
    // prevent rvalue arguments:
    template <typename T>
    static void qAsConst(const T &&) Q_DECL_EQ_DELETE;
#endif

    inline auto operator"" _ls(const char* s, std::size_t size)
    {
        return QLatin1String(s, int(size));
    }

    /** An abstraction over a pair of iterators
     * This is a very basic range type over a container with iterators that
     * are at least ForwardIterators. Inspired by Ranges TS.
     */
    template <typename ArrayT>
    class Range
    {
            // Looking forward for Ranges TS to produce something (in C++23?..)
            using iterator = typename ArrayT::iterator;
            using const_iterator = typename ArrayT::const_iterator;
            using size_type = typename ArrayT::size_type;
        public:
            Range(ArrayT& arr) : from(std::begin(arr)), to(std::end(arr)) { }
            Range(iterator from, iterator to) : from(from), to(to) { }

            size_type size() const
            {
                Q_ASSERT(std::distance(from, to) >= 0);
                return size_type(std::distance(from, to));
            }
            bool empty() const { return from == to; }
            const_iterator begin() const { return from; }
            const_iterator end() const { return to; }
            iterator begin() { return from; }
            iterator end() { return to; }

        private:
            iterator from;
            iterator to;
    };

    /** A replica of std::find_first_of that returns a pair of iterators
     *
     * Convenient for cases when you need to know which particular "first of"
     * [sFirst, sLast) has been found in [first, last).
     */
    template<typename InputIt, typename ForwardIt, typename Pred>
    inline std::pair<InputIt, ForwardIt> findFirstOf(
            InputIt first, InputIt last, ForwardIt sFirst, ForwardIt sLast,
            Pred pred)
    {
        for (; first != last; ++first)
            for (auto it = sFirst; it != sLast; ++it)
                if (pred(*first, *it))
                    return std::make_pair(first, it);

        return std::make_pair(last, sLast);
    }

    /** A guard pointer that disconnects an interested object upon destruction
     * It's almost QPointer<> except that you have to initialise it with one
     * more additional parameter - a pointer to a QObject that will be
     * disconnected from signals of the underlying pointer upon the guard's
     * destruction.
     */
    template <typename T>
    class ConnectionsGuard : public QPointer<T>
    {
        public:
            ConnectionsGuard(T* publisher, QObject* subscriber)
                : QPointer<T>(publisher), subscriber(subscriber)
            { }
            ~ConnectionsGuard()
            {
                if (*this)
                    (*this)->disconnect(subscriber);
            }
            ConnectionsGuard(ConnectionsGuard&&) = default;
            ConnectionsGuard& operator=(ConnectionsGuard&&) = default;
            ConnectionsGuard& operator=(const ConnectionsGuard&) = delete;
            using QPointer<T>::operator=;

        private:
            QObject* subscriber;
    };

    /** Pretty-prints plain text into HTML
     * This includes HTML escaping of <,>,",& and URLs linkification.
     */
    QString prettyPrint(const QString& plainText);
}  // namespace QMatrixClient