aboutsummaryrefslogtreecommitdiff
path: root/lib/converters.h
blob: eaf2a32e84e7f2a669f6524b6d9eec11f6bcfb1a (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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/******************************************************************************
* Copyright (C) 2017 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/QJsonObject>
#include <QtCore/QJsonArray> // Includes <QtCore/QJsonValue>
#include <QtCore/QDate>
#include <QtCore/QUrlQuery>

#include <unordered_map>
#include <vector>
#include <functional>
#if 0 // Waiting for C++17
#include <experimental/optional>

template <typename T>
using optional = std::experimental::optional<T>;
#endif

// Enable std::unordered_map<QString, T>
namespace std
{
    template <> struct hash<QString>
    {
        size_t operator()(const QString& s) const Q_DECL_NOEXCEPT
        {
            return qHash(s, uint(qGlobalQHashSeed()));
        }
    };
}

class QVariant;

namespace QMatrixClient
{
    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
    {
        public:
            explicit Omittable() : Omittable(none) { }
            Omittable(NoneTag) : _omitted(true) { }
            Omittable(const T& val) : _value(val), _omitted(false) { }
            Omittable(T&& val) : _value(std::move(val)), _omitted(false) { }
            Omittable<T>& operator=(const T& val)
            {
                _value = val;
                _omitted = false;
                return *this;
            }
            Omittable<T>& operator=(T&& val)
            {
                _value = std::move(val);
                _omitted = false;
                return *this;
            }

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

            operator bool() const { return !omitted(); }

        private:
            T _value;
            bool _omitted;
    };

    // This catches anything implicitly convertible to QJsonValue/Object/Array
    inline auto toJson(const QJsonValue& val) { return val; }
    inline auto toJson(const QJsonObject& o) { return o; }
    inline auto toJson(const QJsonArray& arr) { return arr; }
    // Special-case QStrings and bools to avoid ambiguity between QJsonValue
    // and QVariant (also, QString.isEmpty() is used in _impl::AddNode<> below)
    inline auto toJson(const QString& s) { return s; }

    inline QJsonArray toJson(const QStringList& strings)
    {
        return QJsonArray::fromStringList(strings);
    }

    inline QString toJson(const QByteArray& bytes)
    {
        return bytes.constData();
    }

    // QVariant is outrageously omnivorous - it consumes whatever is not
    // exactly matching the signature of other toJson overloads. The trick
    // below disables implicit conversion to QVariant through its numerous
    // non-explicit constructors.
    QJsonValue variantToJson(const QVariant& v);
    template <typename T>
    inline auto toJson(T&& var)
        -> std::enable_if_t<std::is_same<std::decay_t<T>, QVariant>::value,
                            QJsonValue>
    {
        return variantToJson(var);
    }
    QJsonObject toJson(const QMap<QString, QVariant>& map);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0))
    QJsonObject toJson(const QHash<QString, QVariant>& hMap);
#endif

    template <typename T>
    inline QJsonArray toJson(const std::vector<T>& vals)
    {
        QJsonArray ar;
        for (const auto& v: vals)
            ar.push_back(toJson(v));
        return ar;
    }

    template <typename T>
    inline QJsonArray toJson(const QVector<T>& vals)
    {
        QJsonArray ar;
        for (const auto& v: vals)
            ar.push_back(toJson(v));
        return ar;
    }

    template <typename T>
    inline QJsonObject toJson(const QHash<QString, T>& hashMap)
    {
        QJsonObject json;
        for (auto it = hashMap.begin(); it != hashMap.end(); ++it)
            json.insert(it.key(), toJson(it.value()));
        return json;
    }

    template <typename T>
    inline QJsonObject toJson(const std::unordered_map<QString, T>& hashMap)
    {
        QJsonObject json;
        for (auto it = hashMap.begin(); it != hashMap.end(); ++it)
            json.insert(it.key(), toJson(it.value()));
        return json;
    }

#if 0
    template <typename T>
    inline auto toJson(const optional<T>& optVal)
    {
        if (optVal)
            return toJson(optVal.value());

        return decltype(toJson(std::declval<T>()))();
    }
#endif

    template <typename T>
    struct FromJson
    {
        T operator()(const QJsonValue& jv) const { return static_cast<T>(jv); }
    };

    template <typename T>
    inline T fromJson(const QJsonValue& jv)
    {
        return FromJson<T>()(jv);
    }

    template <> struct FromJson<bool>
    {
        auto operator()(const QJsonValue& jv) const { return jv.toBool(); }
    };

    template <> struct FromJson<int>
    {
        auto operator()(const QJsonValue& jv) const { return jv.toInt(); }
    };

    template <> struct FromJson<double>
    {
        auto operator()(const QJsonValue& jv) const { return jv.toDouble(); }
    };

    template <> struct FromJson<qint64>
    {
        auto operator()(const QJsonValue& jv) const { return qint64(jv.toDouble()); }
    };

    template <> struct FromJson<QString>
    {
        auto operator()(const QJsonValue& jv) const { return jv.toString(); }
    };

    template <> struct FromJson<QDateTime>
    {
        auto operator()(const QJsonValue& jv) const
        {
            return QDateTime::fromMSecsSinceEpoch(fromJson<qint64>(jv), Qt::UTC);
        }
    };

    template <> struct FromJson<QDate>
    {
        auto operator()(const QJsonValue& jv) const
        {
            return fromJson<QDateTime>(jv).date();
        }
    };

    template <> struct FromJson<QJsonObject>
    {
        auto operator()(const QJsonValue& jv) const
        {
            return jv.toObject();
        }
    };

    template <> struct FromJson<QJsonArray>
    {
        auto operator()(const QJsonValue& jv) const
        {
            return jv.toArray();
        }
    };

    template <> struct FromJson<QByteArray>
    {
        auto operator()(const QJsonValue& jv) const
        {
            return fromJson<QString>(jv).toLatin1();
        }
    };

    template <> struct FromJson<QVariant>
    {
        QVariant operator()(const QJsonValue& jv) const;
    };

    template <typename T> struct FromJson<std::vector<T>>
    {
        auto operator()(const QJsonValue& jv) const
        {
            using size_type = typename std::vector<T>::size_type;
            const auto jsonArray = jv.toArray();
            std::vector<T> vect; vect.resize(size_type(jsonArray.size()));
            std::transform(jsonArray.begin(), jsonArray.end(),
                           vect.begin(), FromJson<T>());
            return vect;
        }
    };

    template <typename T> struct FromJson<QVector<T>>
    {
        auto operator()(const QJsonValue& jv) const
        {
            const auto jsonArray = jv.toArray();
            QVector<T> vect; vect.resize(jsonArray.size());
            std::transform(jsonArray.begin(), jsonArray.end(),
                           vect.begin(), FromJson<T>());
            return vect;
        }
    };

    template <typename T> struct FromJson<QList<T>>
    {
        auto operator()(const QJsonValue& jv) const
        {
            const auto jsonArray = jv.toArray();
            QList<T> sl; sl.reserve(jsonArray.size());
            std::transform(jsonArray.begin(), jsonArray.end(),
                           std::back_inserter(sl), FromJson<T>());
            return sl;
        }
    };

    template <> struct FromJson<QStringList> : FromJson<QList<QString>> { };

    template <> struct FromJson<QMap<QString, QVariant>>
    {
        QMap<QString, QVariant> operator()(const QJsonValue& jv) const;
    };

    template <typename T> struct FromJson<QHash<QString, T>>
    {
        auto operator()(const QJsonValue& jv) const
        {
            const auto json = jv.toObject();
            QHash<QString, T> h; h.reserve(json.size());
            for (auto it = json.begin(); it != json.end(); ++it)
                h.insert(it.key(), fromJson<T>(it.value()));
            return h;
        }
    };

#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0))
    template <> struct FromJson<QHash<QString, QVariant>>
    {
        QHash<QString, QVariant> operator()(const QJsonValue& jv) const;
    };
#endif

    template <typename T> struct FromJson<std::unordered_map<QString, T>>
    {
        auto operator()(const QJsonValue& jv) const
        {
            const auto json = jv.toObject();
            std::unordered_map<QString, T> h; h.reserve(size_t(json.size()));
            for (auto it = json.begin(); it != json.end(); ++it)
                h.insert(std::make_pair(it.key(), fromJson<T>(it.value())));
            return h;
        }
    };

    // Conditional insertion into a QJsonObject

    namespace _impl
    {
        template <typename ValT>
        inline void addTo(QJsonObject& o, const QString& k, ValT&& v)
        { o.insert(k, toJson(v)); }

        template <typename ValT>
        inline void addTo(QUrlQuery& q, const QString& k, ValT&& v)
        { q.addQueryItem(k, QString("%1").arg(v)); }

        // OpenAPI is entirely JSON-based, which means representing bools as
        // textual true/false, rather than 1/0.
        inline void addTo(QUrlQuery& q, const QString& k, bool v)
        {
            q.addQueryItem(k, v ? QStringLiteral("true")
                                : QStringLiteral("false"));
        }

        // This one is for types that don't have isEmpty()
        template <typename ValT, bool Force = true, typename = bool>
        struct AddNode
        {
            template <typename ContT, typename ForwardedT>
            static void impl(ContT& container, const QString& key,
                             ForwardedT&& value)
            {
                addTo(container, key, std::forward<ForwardedT>(value));
            }
        };

        // This one is for types that have isEmpty()
        template <typename ValT>
        struct AddNode<ValT, false,
                       decltype(std::declval<ValT>().isEmpty())>
        {
            template <typename ContT, typename ForwardedT>
            static void impl(ContT& container, const QString& key,
                             ForwardedT&& value)
            {
                if (!value.isEmpty())
                    AddNode<ValT>::impl(container,
                                        key, std::forward<ForwardedT>(value));
            }
        };

        // This is a special one that unfolds Omittable<>
        template <typename ValT, bool Force>
        struct AddNode<Omittable<ValT>, Force>
        {
            template <typename ContT, typename OmittableT>
            static void impl(ContT& container,
                             const QString& key, const OmittableT& value)
            {
                if (!value.omitted())
                    AddNode<ValT>::impl(container, key, value.value());
                else if (Force) // Edge case, no value but must put something
                    AddNode<ValT>::impl(container, key, QString{});
            }
        };
    }  // namespace _impl

    static constexpr bool IfNotEmpty = false;

    template <bool Force = true, typename ContT, typename ValT>
    inline void addParam(ContT& container, const QString& key, ValT&& value)
    {
        _impl::AddNode<std::decay_t<ValT>, Force>
                ::impl(container, key, std::forward<ValT>(value));
    }
}  // namespace QMatrixClient