QVariant_impl.h 11.4 KB
Newer Older
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
/****************************************************************************
 * **
 * ** Copyright (C) 2017 MinMaxMedical.
 * ** All rights reserved.
 * ** Contact: MinMaxMedical <InCAS@MinMaxMedical.com>
 * **
 * ** This file is part of the modmedLog module.
 * **
 * ** $QT_BEGIN_LICENSE:BSD$
 * ** You may use this file under the terms of the BSD license as follows:
 * **
 * ** "Redistribution and use in source and binary forms, with or without
 * ** modification, are permitted provided that the following conditions are
 * ** met:
 * **   * Redistributions of source code must retain the above copyright
 * **     notice, this list of conditions and the following disclaimer.
 * **   * Redistributions in binary form must reproduce the above copyright
 * **     notice, this list of conditions and the following disclaimer in
 * **     the documentation and/or other materials provided with the
 * **     distribution.
 * **   * Neither the name of MinMaxMedical S.A.S. and its Subsidiary(-ies) nor
 * **     the names of its contributors may be used to endorse or promote
 * **     products derived from this software without specific prior written
 * **     permission.
 * **
 * ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
 * ** $QT_END_LICENSE$
 * **
 * ****************************************************************************/
#pragma once

#include <QtCore/qvariant.h>
#include <QtCore/qstack.h>

#include "QBind_impl.h"

// //////////////////////////////////////////////////////////////////////////
// QBind<QVariant*,T> support for the fixed set of QVariantBuilder's BindNative types

EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
50
class QVariantBuilder : public IWriter
51
{
EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
52
    Q_DISABLE_COPY(QVariantBuilder)
53
public:
EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
54
    QVariantBuilder(QVariant* v) : variant(v) { Q_ASSERT(v); }
55
56
   ~QVariantBuilder() { while (!levels.isEmpty()) _out(); }

EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
57
    // Shortcuts
EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
58
59
60
61
62
63
64
    /**/             Val<QWriter> value   (                  ) { return QWriter(this).value               (  ); }
    /**/             Val<QWriter> meta    (      MetaData&& m) { return QWriter(this).meta                ( m); }
    /**/             Val<QWriter> meta    (      MetaData&  m) { return QWriter(this).meta                ( m); }
    /**/             Seq<QWriter> sequence(quint32* s=nullptr) { return QWriter(this).sequence            ( s); }
    /**/             Rec<QWriter> record  (quint32* s=nullptr) { return QWriter(this).record              ( s); }
    /**/                 QWriter  null    (                  ) { return QWriter(this).null                (  ); }
    template<typename T> QWriter  bind    (             T&& t) { return QWriter(this).bind(std::forward<T>(t)); }
EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
65
protected:
66
67
68
69
    template<typename T>
    bool _bind    (                 T& t) { set(QVariant::fromValue(t)); return true; }
    bool _bind    (        const char* t) { set(QVariant           (t)); return true; }
    bool _null    (                     ) { set(QVariant           ( )); return true; }
EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
70

71
72
73
74
75
76
77
78
79
    bool _sequence(quint32* rows=nullptr) { Q_UNUSED(rows); levels.push(Step(nullptr)); return true; }
    bool _record  (quint32* cols=nullptr) { Q_UNUSED(cols); levels.push(Step(""     )); return true; }

    bool _item(QByteArray& k) { levels.last().key=k      ; return true; }
    bool _item(             ) { levels.last().key=nullptr; return true; }
    bool _out (             ) { auto level = levels.pop(); set(!level.key.isNull() ? QVariant(level.object) : QVariant(level.array)); return true; }
private:
    void set(const QVariant& v) {
        if (levels.isEmpty()) {
EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
80
            *variant = v;
81
82
83
84
85
86
87
88
89
        }
        else {
            if (!levels.last().key.isNull())
                levels.last().object[levels.last().key]=v;
            else
                levels.last().array.append(v);
        }
    }

EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
90
    QVariant* variant;
91
92
93
94
95
96
97
    struct Step { QByteArray key; /* TODO union */ QVariantMap object; QVariantList array; Step(const char* k=nullptr) : key(k) {} };
    QStack<Step> levels = QStack<Step>(); //!< minimal dynamic context to implement out() and ensure actual building in case QVariantBuilder is abandoned
};

// --------------------------------------------------------------------------

class VariantVisitorImpl;
EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
98
class QVariantVisitor : public QBaseReader<QVariantVisitor, VariantVisitorImpl>
99
100
101
102
103
104
{
    Q_PROTECTED_COPY(QVariantVisitor)
public:
    Q_ENABLE_MOVE_DEFAULT(QVariantVisitor)
    QVariantVisitor(const QVariant* v);
private:
EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
105
    friend class QBaseReader<QVariantVisitor, VariantVisitorImpl>;
106
    friend class VariantVisitorImpl; // uses method below
EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
107
    QVariantVisitor(VariantVisitorImpl* outer) : QBaseReader(outer, false) {}
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
};
class VariantVisitorImpl
{
    Q_DISABLE_COPY(VariantVisitorImpl)
public:
    VariantVisitorImpl(const QVariant* v) : value(v) { Q_ASSERT(v); }

    struct Error { const char* error; QByteArray path; template<class T> T bind(Val<T> value) { return value.bind(QByteArray(error)+' '+path); } };
    QVector<Error> errors;

    QByteArray currentPath() {
        QByteArray path;
        Q_FOREACH(Step s, steps) {
            if (s.key) {
                path.append('{').append(s.key);
            }
            else {
                char index[std::numeric_limits<int>::digits10+1];
                itoa(s.idx, index, 10);
                path.append('[').append(index);
            }
        }
        return path;
    }
protected:
EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
133
    friend class QScopedChoice<Val<QVariantVisitor>>;
134
135
    void setChoice(bool v) { isChoice=v; }

EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
136
    friend class QBaseReader<QVariantVisitor, VariantVisitorImpl>;
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
    void reportError(const char* error) { if (!isChoice) errors.append(Error{ error, currentPath() }); }

    template<class T_> friend class Val; // calls methods below

    template<typename T>
    bool _bind    (                 T& t) {                 if (current()->type()==qMetaTypeId<T>()   ) { t = current()->value<T>(); return true; } reportError("Expected T"         ); return false; }
    bool _sequence(quint32* rows=nullptr) { Q_UNUSED(rows); if (current()->type()==QVariant::List     ) {        steps.push(Step()); return true; } reportError(qBindExpectedSequence); return false; }
    bool _record  (quint32* cols=nullptr) { Q_UNUSED(cols); if (current()->type()==QVariant::Map      ) {        steps.push(Step()); return true; } reportError(qBindExpectedRecord  ); return false; }
    bool _null    (                     ) {                 if (current()->isNull()                   ) {                            return true; } reportError(qBindExpectedNull    ); return false; }

    template<class T_> friend class Seq; // calls methods below
    template<class T_> friend class Rec; // calls methods below

    bool _item(QByteArray& k) { steps.last().key=k; return (steps.last().item = current(1)->toMap ().value(QString::fromUtf8(steps.last().key), QVariant())).isValid(); }
    bool _item(             ) { steps.last().idx++; return (steps.last().item = current(1)->toList().value(                  steps.last().idx , QVariant())).isValid(); }
    bool _out (             ) { steps.pop()       ; return true; }
private:
    const QVariant* current(unsigned outer=0) const { return unsigned(steps.size())-outer <= 0 ? value : &(steps[unsigned(steps.size())-outer-1].item); }

    const QVariant* value;
    struct Step { const char* key=nullptr; int idx=-1; QVariant item; Step() = default; };
    QStack<Step> steps = QStack<Step>();
    bool isChoice = false;
};
EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
161
QVariantVisitor::QVariantVisitor(const QVariant* v) : QBaseReader(new VariantVisitorImpl(v), true) {}
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
template<> struct BindSupport<VariantVisitorImpl,      bool&> : BindNative {};
template<> struct BindSupport<VariantVisitorImpl,qulonglong&> : BindNative {};
template<> struct BindSupport<VariantVisitorImpl, qlonglong&> : BindNative {};
template<> struct BindSupport<VariantVisitorImpl,    double&> : BindNative {};
template<> struct BindSupport<VariantVisitorImpl,QByteArray&> : BindNative {};
template<> struct BindSupport<VariantVisitorImpl,   QString&> : BindNative {}; // also handles const char*

//// //////////////////////////////////////////////////////////////////////////
//// QBind<TResult,QVariant&> example support for the fixed set of QVariantBuilder's BindNative types + other convenient types

template<class TResult>
struct QBind<TResult, QVariant&, IsWriter<TResult>> { static TResult bind(Val<TResult> dst, QVariant& src) {
    if (src.type()==QVariant::List     ) return dst.bind(src.value<QVariantList>()); // TODO  QSequentialIterable ?
    if (src.type()==QVariant::Map      ) return dst.bind(src.value<QVariantMap >()); // TODO QAssociativeIterable ?
    // TODO QVariant::Hash

    if (src.type()==QVariant::Bool     ) return dst.bind(src.value<        bool>());
    if (src.type()==QVariant::ByteArray) return dst.bind(src.value<  QByteArray>());
    if (src.type()==QVariant::String   ) return dst.bind(src.value<     QString>());
    if (src.type()==QVariant::Char     ) return dst.bind(src.toString());

    if (src.type()==QVariant::ULongLong) return dst.bind(src.value<  qulonglong>());
    if (src.type()==QVariant::UInt     ) return dst.bind(src.value<unsigned int>());
    if (src.type()==QVariant::LongLong ) return dst.bind(src.value<   qlonglong>());
    if (src.type()==QVariant::Int      ) return dst.bind(src.value<         int>());
    if (src.type()==QVariant::Double   ) return dst.bind(src.value<      double>());

    // TODO convert builtin types which canConvert<QString>
    // \sa QBind<TSrcResult, Val<TDst>&&, IsReader<TSrcResult>>

    return dst.null();
}};
//template<class TResult>
//struct QBind<TResult, QVariant&, IsReader<TResult>> { static TResult bind(Val<TResult> src, QVariant& dst) {
//    TResult r;
//    {
EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
198
//        QScopedChoice<Val<TResult>> choice(src);
199
200
201
202
203
204
205
206
207
208
209
210
//        QVariantList a; if ((r = src.bind(a))) { dst =          a ; return r; } // NB We cannot try QStringList before QVariantList as it will always work with our logical model...
//        QVariantMap  o; if ((r = src.bind(o))) { dst =          o ; return r; }
//        bool         b; if ((r = src.bind(b))) { dst = QVariant(b); return r; }
//        qulonglong   u; if ((r = src.bind(u))) { dst = QVariant(u); return r; }
//        qlonglong    l; if ((r = src.bind(l))) { dst = QVariant(l); return r; }
//        double       d; if ((r = src.bind(d))) { dst = QVariant(d); return r; }
//        QByteArray   x; if ((r = src.bind(x))) { dst = QVariant(x); return r; }
//        QString      t; if ((r = src.bind(t))) { dst = QVariant(t); return r; }
//    }
//    if (!(r = src.null())) r.reportError("Expected boolean|decimal|text|sequence|record|null");
//    /**/                                         dst = QVariant( ); return r;
//}};