QVariant_impl.h 10.8 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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
/****************************************************************************
 * **
 * ** 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<T,QVariant*> support for the fixed set of QVariantBuilder's BindNative types

class QVariantBuilder : public IWriter
{
    Q_DISABLE_COPY(QVariantBuilder)
public:
    QVariantBuilder(QVariant* v) : variant(v) { Q_ASSERT(v); }
   ~QVariantBuilder() { while (!levels.isEmpty()) _out(); }
    void reset(QVariant* v) { variant=v; Q_ASSERT(v); levels.clear(); }

    // Shortcuts
    /**/             Val<Cursor> value   (                  ) { return Cursor(this).value(); }
    /**/             Seq<Cursor> sequence(quint32* s=nullptr) { return Cursor(this).value().sequence            ( s); }
    template<typename T> Cursor  bind    (             T&& t) { return Cursor(this).value().bind(std::forward<T>(t)); }
protected:
    // TODO Support _meta to be able to cache and restitute all metadata as well as data+datatype

    template<typename T>
EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
66 67 68
    bool _bind    (        T&& t) { set(QVariant::fromValue(t)); return true; }
    bool _bind    (const char* u) { set(QVariant           (u)); return true; }
    bool _null    (             ) { set(QVariant           ( )); return true; }
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

    bool _sequence(quint32* =nullptr) { levels.push(Level(nullptr)); return true; }
    bool _record  (quint32* =nullptr) { levels.push(Level(""     )); return true; }

    bool _item(QName n) { levels.last().key=n      ; 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()) {
            *variant = v;
        }
        else {
            if (!levels.last().key.isNull())
                levels.last().object[levels.last().key]=v;
            else
                levels.last().array.append(v);
        }
    }

    QVariant* variant;
    struct Level { QUtf8String key; /* TODO union */ QVariantMap object; QVariantList array; Level(const char* k=nullptr) : key(k) {} };
    QStack<Level> levels = QStack<Level>(); //!< minimal dynamic context to implement out() and ensure actual building in case QVariantBuilder is abandoned
};

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

class QVariantVisitor : public IReader
{
    Q_DISABLE_COPY(QVariantVisitor)
public:
    Q_ENABLE_MOVE_DEFAULT(QVariantVisitor)
    QVariantVisitor(const QVariant* v) : value(v) { Q_ASSERT(v); }
    void reset(const QVariant* v) { value=v; Q_ASSERT(v); levels.clear(); errors.clear(); }

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

    QUtf8String currentPath() {
        QUtf8String path;
        Q_FOREACH(Level l, levels) {
            if (l.key) { path.append('{').append(l.key); }
            else       { path.append('[').append(QUtf8String::number(l.idx)); }
        }
        return path;
    }
protected:
    // TODO Support _meta to be able to cache and restitute all metadata as well as data+datatype

    template<typename T>
    bool _bind(T& t) { if (current()->type()==qMetaTypeId<T>()) { t = current()->value<T>(); return true; } _reportError("Expected declared metatype T"); return false; }

    bool _bind(QUtf8String& t) { if (current()->type()==qMetaTypeId<QUtf8String>()) { t = current()->value<QUtf8String>(); return true; } _reportError(qBindExpectedText          ); return false; }
    bool _bind(    QString& t) { if (current()->type()==qMetaTypeId<    QString>()) { t = current()->value<    QString>(); return true; } _reportError(qBindExpectedText          ); return false; }
    bool _bind(       bool& t) { if (current()->type()==qMetaTypeId<       bool>()) { t = current()->value<       bool>(); return true; } _reportError(qBindExpectedBoolean       ); return false; }
    bool _bind( QByteArray& t) { if (current()->type()==qMetaTypeId< QByteArray>()) { t = current()->value< QByteArray>(); return true; } _reportError(qBindExpectedBytes         ); return false; }
    // Convert numerical types to strictly larger ones // TODO convert all compatible values
    bool _bind(      qint8& t) { if (current()->type()==qMetaTypeId<      qint8>()) { t = current()->value<      qint8>(); return true; } _reportError(qBindExpectedInteger       ); return false; }
    bool _bind(     qint16& t) { if (current()->type()==qMetaTypeId<      qint8>()||
                                     current()->type()==qMetaTypeId<     qint16>()) { t = current()->value<     qint16>(); return true; } _reportError(qBindExpectedInteger       ); return false; }
    bool _bind(     qint32& t) { if (current()->type()==qMetaTypeId<      qint8>()||
                                     current()->type()==qMetaTypeId<     qint16>()||
                                     current()->type()==qMetaTypeId<     qint32>()) { t = current()->value<     qint32>(); return true; } _reportError(qBindExpectedInteger       ); return false; }
    bool _bind(     qint64& t) { if (current()->type()==qMetaTypeId<      qint8>()||
                                     current()->type()==qMetaTypeId<     qint16>()||
                                     current()->type()==qMetaTypeId<     qint32>()||
                                     current()->type()==qMetaTypeId<     qint64>()) { t = current()->value<     qint64>(); return true; } _reportError(qBindExpectedInteger       ); return false; }
    bool _bind(     quint8& t) { if (current()->type()==qMetaTypeId<     quint8>()) { t = current()->value<     quint8>(); return true; } _reportError(qBindExpectedPositiveNumber); return false; }
    bool _bind(    quint16& t) { if (current()->type()==qMetaTypeId<     quint8>()||
                                     current()->type()==qMetaTypeId<    quint16>()) { t = current()->value<    quint16>(); return true; } _reportError(qBindExpectedPositiveNumber); return false; }
    bool _bind(    quint32& t) { if (current()->type()==qMetaTypeId<     quint8>()||
                                     current()->type()==qMetaTypeId<    quint16>()||
                                     current()->type()==qMetaTypeId<    quint32>()) { t = current()->value<    quint32>(); return true; } _reportError(qBindExpectedPositiveNumber); return false; }
    bool _bind(    quint64& t) { if (current()->type()==qMetaTypeId<     quint8>()||
                                     current()->type()==qMetaTypeId<    quint16>()||
                                     current()->type()==qMetaTypeId<    quint32>()||
                                     current()->type()==qMetaTypeId<    quint64>()) { t = current()->value<    quint64>(); return true; } _reportError(qBindExpectedPositiveNumber); return false; }
    bool _bind(      float& t) { if (current()->type()==qMetaTypeId<      float>()) { t = current()->value<      float>(); return true; } _reportError(qBindExpectedDecimal       ); return false; }
    bool _bind(     double& t) { if (current()->type()==qMetaTypeId<      float>()||
                                     current()->type()==qMetaTypeId<     double>()) { t = current()->value<     double>(); return true; } _reportError(qBindExpectedDecimal       ); return false; }

EXT Arnaud Clère's avatar
EXT Arnaud Clère committed
150 151 152
    bool _sequence(quint32* =nullptr) { if (current()->type()==QVariant::List  ) { levels.push(Level()); return true; } _reportError(qBindExpectedSequence); return false; }
    bool _record  (quint32* =nullptr) { if (current()->type()==QVariant::Map   ) { levels.push(Level()); return true; } _reportError(qBindExpectedRecord  ); return false; }
    bool _null    (                 ) { if (current()->isNull()                ) {                       return true; } _reportError(qBindExpectedNull    ); return false; }
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168

    bool _item(QUtf8String& k) { levels.last().key=k; return (levels.last().item = current(1)->toMap ().value(QString::fromUtf8(levels.last().key), QVariant())).isValid(); }
    bool _item(              ) { levels.last().idx++; return (levels.last().item = current(1)->toList().value(                  levels.last().idx , QVariant())).isValid(); }
    bool _out (              ) { levels.pop()       ; return true; }

    bool _isOk() { return value; }
    void _setChoice(bool v) { isChoice=v; }
    void _reportError(const char* error) { if (!isChoice) errors.append(Error{ error, currentPath() }); }
private:
    const QVariant* current(unsigned outer=0) const { return unsigned(levels.size())-outer <= 0 ? value : &(levels[unsigned(levels.size())-outer-1].item); }

    const QVariant* value;
    struct Level { const char* key=nullptr; int idx=-1; QVariant item; Level() = default; };
    QStack<Level> levels;
    bool isChoice = false;
};