summaryrefslogtreecommitdiffstats
path: root/src/corelib/serialization/qcbordiagnostic.cpp
blob: 75feaded17a8f204e4fd7df6138f042d418dc9cd (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
/****************************************************************************
**
** Copyright (C) 2018 Intel Corporation.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qcborvalue.h"
#include "qcborvalue_p.h"

#include "qcborarray.h"
#include "qcbormap.h"

#include <private/qnumeric_p.h>
#include <qstack.h>
#include <private/qtools_p.h>

QT_BEGIN_NAMESPACE

namespace  {
class DiagnosticNotation
{
public:
    static QString create(const QCborValue &v, QCborValue::DiagnosticNotationOptions opts)
    {
        DiagnosticNotation dn(opts);
        dn.appendValue(v);
        return dn.result;
    }

private:
    QStack<int> byteArrayFormatStack;
    QString separator;
    QString result;
    QCborValue::DiagnosticNotationOptions opts;
    int nestingLevel = 0;

    struct Nest {
        enum { IndentationWidth = 4 };
        DiagnosticNotation *dn;
        Nest(DiagnosticNotation *that) : dn(that)
        {
            ++dn->nestingLevel;
            static const char indent[IndentationWidth + 1] = "    ";
            if (dn->opts & QCborValue::LineWrapped)
                dn->separator += QLatin1String(indent, IndentationWidth);
        }
        ~Nest()
        {
            --dn->nestingLevel;
            if (dn->opts & QCborValue::LineWrapped)
                dn->separator.chop(IndentationWidth);
        }
    };

    DiagnosticNotation(QCborValue::DiagnosticNotationOptions opts_)
        : separator(QLatin1String(opts_ & QCborValue::LineWrapped ? "\n" : "")), opts(opts_)
    {
        byteArrayFormatStack.push(int(QCborKnownTags::ExpectedBase16));
    }

    void appendString(const QString &s);
    void appendArray(const QCborArray &a);
    void appendMap(const QCborMap &m);
    void appendValue(const QCborValue &v);
};
}

static QString makeFpString(double d)
{
    QString s;
    quint64 v;
    if (qt_is_inf(d)) {
        s = (d < 0) ? QStringLiteral("-inf") : QStringLiteral("inf");
    } else if (qt_is_nan(d)) {
        s = QStringLiteral("nan");
    } else if (convertDoubleTo(d, &v)) {
        s = QString::fromLatin1("%1.0").arg(v);
        if (d < 0)
            s.prepend(QLatin1Char('-'));
    } else {
        s = QString::number(d, 'g', QLocale::FloatingPointShortest);
        if (!s.contains(QLatin1Char('.')) && !s.contains('e'))
            s += QLatin1Char('.');
    }
    return s;
}

static bool isByteArrayEncodingTag(QCborTag tag)
{
    switch (quint64(tag)) {
    case quint64(QCborKnownTags::ExpectedBase16):
    case quint64(QCborKnownTags::ExpectedBase64):
    case quint64(QCborKnownTags::ExpectedBase64url):
        return true;
    }
    return false;
}

void DiagnosticNotation::appendString(const QString &s)
{
    result += QLatin1Char('"');

    const QChar *begin = s.begin();
    const QChar *end = s.end();
    while (begin < end) {
        // find the longest span comprising only non-escaped characters
        const QChar *ptr = begin;
        for ( ; ptr < end; ++ptr) {
            ushort uc = ptr->unicode();
            if (uc == '\\' || uc == '"' || uc < ' ' || uc >= 0x7f)
                break;
        }

        if (ptr != begin)
            result.append(begin, ptr - begin);

        if (ptr == end)
            break;

        // there's an escaped character
        static const char escapeMap[16] = {
            // The C escape characters \a \b \t \n \v \f and \r indexed by
            // their ASCII values
            0, 0, 0, 0,
            0, 0, 0, 'a',
            'b', 't', 'n', 'v',
            'f', 'r', 0, 0
        };
        int buflen = 2;
        QChar buf[10];
        buf[0] = QLatin1Char('\\');
        buf[1] = QChar::Null;
        char16_t uc = ptr->unicode();

        if (uc < sizeof(escapeMap))
            buf[1] = QLatin1Char(escapeMap[uc]);
        else if (uc == '"' || uc == '\\')
            buf[1] = QChar(uc);

        if (buf[1] == QChar::Null) {
            using QtMiscUtils::toHexUpper;
            if (ptr->isHighSurrogate() && (ptr + 1) != end && ptr[1].isLowSurrogate()) {
                // properly-paired surrogates
                ++ptr;
                char32_t ucs4 = QChar::surrogateToUcs4(uc, ptr->unicode());
                buf[1] = 'U';
                buf[2] = '0'; // toHexUpper(ucs4 >> 28);
                buf[3] = '0'; // toHexUpper(ucs4 >> 24);
                buf[4] = toHexUpper(ucs4 >> 20);
                buf[5] = toHexUpper(ucs4 >> 16);
                buf[6] = toHexUpper(ucs4 >> 12);
                buf[7] = toHexUpper(ucs4 >> 8);
                buf[8] = toHexUpper(ucs4 >> 4);
                buf[9] = toHexUpper(ucs4);
                buflen = 10;
            } else {
                buf[1] = 'u';
                buf[2] = toHexUpper(uc >> 12);
                buf[3] = toHexUpper(uc >> 8);
                buf[4] = toHexUpper(uc >> 4);
                buf[5] = toHexUpper(uc);
                buflen = 6;
            }
        }

        result.append(buf, buflen);
        begin = ptr + 1;
    }

    result += QLatin1Char('"');
}

void DiagnosticNotation::appendArray(const QCborArray &a)
{
    result += QLatin1Char('[');

    // length 2 (including the space) when not line wrapping
    QLatin1String commaValue(", ", opts & QCborValue::LineWrapped ? 1 : 2);
    {
        Nest n(this);
        QLatin1String comma;
        for (auto v : a) {
            result += comma + separator;
            comma = commaValue;
            appendValue(v);
        }
    }

    result += separator + QLatin1Char(']');
}

void DiagnosticNotation::appendMap(const QCborMap &m)
{
    result += QLatin1Char('{');

    // length 2 (including the space) when not line wrapping
    QLatin1String commaValue(", ", opts & QCborValue::LineWrapped ? 1 : 2);
    {
        Nest n(this);
        QLatin1String comma;
        for (auto v : m) {
            result += comma + separator;
            comma = commaValue;
            appendValue(v.first);
            result += QLatin1String(": ");
            appendValue(v.second);
        }
    }

    result += separator + QLatin1Char('}');
};

void DiagnosticNotation::appendValue(const QCborValue &v)
{
    switch (v.type()) {
    case QCborValue::Integer:
        result += QString::number(v.toInteger());
        return;
    case QCborValue::ByteArray:
        switch (byteArrayFormatStack.top()) {
        case int(QCborKnownTags::ExpectedBase16):
            result += QString::fromLatin1("h'" +
                                          v.toByteArray().toHex(opts & QCborValue::ExtendedFormat ? ' ' : '\0') +
                                          '\'');
            return;
        case int(QCborKnownTags::ExpectedBase64):
            result += QString::fromLatin1("b64'" + v.toByteArray().toBase64() + '\'');
            return;
        default:
        case int(QCborKnownTags::ExpectedBase64url):
            result += QString::fromLatin1("b64'" +
                                          v.toByteArray().toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals) +
                                          '\'');
            return;
        }
    case QCborValue::String:
        return appendString(v.toString());
    case QCborValue::Array:
        return appendArray(v.toArray());
    case QCborValue::Map:
        return appendMap(v.toMap());
    case QCborValue::False:
        result += QLatin1String("false");
        return;
    case QCborValue::True:
        result += QLatin1String("true");
        return;
    case QCborValue::Null:
        result += QLatin1String("null");
        return;
    case QCborValue::Undefined:
        result += QLatin1String("undefined");
        return;
    case QCborValue::Double:
        result += makeFpString(v.toDouble());
        return;
    case QCborValue::Invalid:
        result += QStringLiteral("<invalid>");
        return;

    default:
        // Only tags, extended types, and simple types remain; see below.
        break;
    }

    if (v.isTag()) {
        // We handle all extended types as regular tags, so it won't matter
        // whether we understand that tag or not.
        bool byteArrayFormat = opts & QCborValue::ExtendedFormat && isByteArrayEncodingTag(v.tag());
        if (byteArrayFormat)
            byteArrayFormatStack.push(int(v.tag()));
        result += QString::number(quint64(v.tag())) + QLatin1Char('(');
        appendValue(v.taggedValue());
        result += QLatin1Char(')');
        if (byteArrayFormat)
            byteArrayFormatStack.pop();
    } else {
        // must be a simple type
        result += QString::fromLatin1("simple(%1)").arg(quint8(v.toSimpleType()));
    }
}

/*!
    Creates the diagnostic notation equivalent of this CBOR object and returns
    it. The \a opts parameter controls the dialect of the notation. Diagnostic
    notation is useful in debugging, to aid the developer in understanding what
    value is stored in the QCborValue or in a CBOR stream. For that reason, the
    Qt API provides no support for parsing the diagnostic back into the
    in-memory format or CBOR stream, though the representation is unique and it
    would be possible.

    CBOR diagnostic notation is specified by
    \l{https://tools.ietf.org/html/rfc7049#section-6}{section 6} of RFC 7049.
    It is a text representation of the CBOR stream and it is very similar to
    JSON, but it supports the CBOR types not found in JSON. The extended format
    enabled by the \l{DiagnosticNotationOption}{ExtendedFormat} flag is
    currently in some IETF drafts and its format is subject to change.

    This function produces the equivalent representation of the stream that
    toCbor() would produce, without any transformation option provided there.
    This also implies this function may not produce a representation of the
    stream that was used to create the object, if it was created using
    fromCbor(), as that function may have applied transformations. For a
    high-fidelity notation of a stream, without transformation, see the \c
    cbordump example.

    \sa toCbor(), QJsonDocument::toJson()
 */
QString QCborValue::toDiagnosticNotation(DiagnosticNotationOptions opts) const
{
    return DiagnosticNotation::create(*this, opts);
}

QT_END_NAMESPACE