summaryrefslogtreecommitdiffstats
path: root/src/qjson_p.h
blob: 36b0659e77e6be2adfa9eed011b2d1a0c6dd4962 (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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#ifndef QJSON_P_H
#define QJSON_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <qjsonglobal.h>
#include <qjsonobject.h>
#include <qjsonvalue.h>
#include <qjsondocument.h>
#include <qjsonarray.h>
#include <qoldbasicatomic.h>
#include <qstring.h>
#include <qendian.h>

/*
  This defines a binary data structure for Json data. The data structure is optimised for fast reading and minimum allocations.
  The whole data structure can be mmap'ed and used directly.

  In most cases the binary structure is not as space efficient as a utf8 encoded text representation, but much faster to access.

  The size requirements are:

  String: 16 bytes header + 2*(string.length())

  Values: 4 bytes + size of data (size can be 0 for some data)
    bool: 0 bytes
    number: 8 bytes
    string: 4 + 2*length of string
    array: size of array
    object: size of object
  Array: 12 bytes + 4*length + size of Value data
  Object: 12 bytes + 8*length + size of Key Strings + size of Value data

  For an example such as

    {                                           // object: 12 + 5*8                = 52
         "firstName": "John",                   // key 4+12, value 8          = 24
         "lastName" : "Smith",                  // key 4+8, value 8         = 20
         "age"      : 25,                       // key 4+4, value 0             = 8
         "address"  :                           // key 4+8, object below = 154
         {                                      // object: 12 + 4*8
             "streetAddress": "21 2nd Street",  // key 4+16, value 16
             "city"         : "New York",       // key 4+4, value 12
             "state"        : "NY",             // key 4+8, value 4
             "postalCode"   : "10021"           // key 4+12, value 8
         },                                     // object total: 148
         "phoneNumber":                         // key: 4+12, value array below = 208
         [                                      // array: 12 + 2*4 + values below = 176
             {                                  // object 12 + 2*8
               "type"  : "home",                // key 4+4, value 8
               "number": "212 555-1234"         // key 4+8, value 16
             },                                 // object total: 84
             {                                  // object 12 + 2*8
               "type"  : "fax",                 // key 4+4, value 8
               "number": "646 555-4567"         // key 4+8, value 16
             }                                  // object total: 84
         ]                                      // array total: 248
    }                                           // great total:                       416 bytes

    The uncompressed text file used roughly 500 bytes, so we end up using about the same space
    as the text representation.
*/
namespace QtJson
{

namespace Private {

struct Array;
struct Object;
struct Value;
struct Entry;

template<typename T>
struct q_littleendian
{
    T val;

    q_littleendian &operator =(T i) { val = qToLittleEndian(i); return *this; }
    operator T() const { return qFromLittleEndian(val); }

    bool operator ==(T i) { return qFromLittleEndian(val) == i; }
    bool operator !=(T i) { return qFromLittleEndian(val) != i; }
    bool operator <(T i) { return qFromLittleEndian(val) < i; }
    bool operator >(T i) { return qFromLittleEndian(val) > i; }
    bool operator <=(T i) { return qFromLittleEndian(val) <= i; }
    bool operator >=(T i) { return qFromLittleEndian(val) >= i; }
    q_littleendian &operator +=(T i) {
        val = qToLittleEndian(qFromLittleEndian(val) + i);
        return *this;
    }
};

typedef q_littleendian<short> qle_short;
typedef q_littleendian<unsigned short> qle_ushort;
typedef q_littleendian<int> qle_int;
typedef q_littleendian<unsigned int> qle_uint;

template<int pos, int width>
struct qle_bitfield
{
    uint val;

    enum {
        mask = ((1u << width) - 1) << pos
    };

    void operator =(uint t) {
        uint i = qFromLittleEndian(val);
        i &= ~mask;
        i |= t << pos;
        val = qToLittleEndian(i);
    }
    operator uint() const {
        uint t = qFromLittleEndian(val);
        t &= mask;
        t >>= pos;
        return t;
    }
    bool operator !() const {
        return !operator uint();
    }

    bool operator ==(uint t) { return uint(*this) == t; }
    bool operator !=(uint t) { return uint(*this) != t; }
    bool operator <(uint t) { return uint(*this) < t; }
    bool operator >(uint t) { return uint(*this) > t; }
    bool operator <=(uint t) { return uint(*this) <= t; }
    bool operator >=(uint t) { return uint(*this) >= t; }
    qle_bitfield &operator +=(uint i) {
        *this = (uint(*this) + i);
        return *this;
    }
    qle_bitfield &operator -=(uint i) {
        *this = (uint(*this) - i);
        return *this;
    }
};

template<int pos, int width>
struct qle_signedbitfield
{
    uint val;

    enum {
        mask = ((1u << width) - 1) << pos
    };

    void operator =(int t) {
        uint i = qFromLittleEndian(val);
        i &= ~mask;
        i |= t << pos;
        val = qToLittleEndian(i);
    }
    operator int() const {
        uint i = qFromLittleEndian(val);
        i <<= 32 - width - pos;
        int t = (int) i;
        t >>= pos;
        return t;
    }
    bool operator !() const {
        return !operator int();
    }

    bool operator ==(int t) { return int(*this) == t; }
    bool operator !=(int t) { return int(*this) != t; }
    bool operator <(int t) { return int(*this) < t; }
    bool operator >(int t) { return int(*this) > t; }
    bool operator <=(int t) { return int(*this) <= t; }
    bool operator >=(int t) { return int(*this) >= t; }
    qle_signedbitfield &operator +=(int i) {
        *this = (int(*this) + i);
        return *this;
    }
    qle_signedbitfield &operator -=(int i) {
        *this = (int(*this) - i);
        return *this;
    }
};

typedef qle_uint offset;

static inline int alignedSize(int size) { return (size + 3) & ~3; }

static inline bool useCompressed(const QString &s)
{
    if (s.length() >= 0x8000)
        return false;
    const ushort *uc = (const ushort *)s.constData();
    const ushort *e = uc + s.length();
    while (uc < e) {
        if (*uc > 0xff)
            return false;
        ++uc;
    }
    return true;
}

static inline int qStringSize(const QString &string, bool compress)
{
    int l = 2 + string.length();
    if (!compress)
        l *= 2;
    return alignedSize(l);
}


// returns INT_MAX if it can't compress it into 28 bits
static inline int compressedNumber(double d)
{
    // this relies on details of how ieee floats are represented
    const int exponent_off = 52;
    const quint64 fraction_mask = 0x000fffffffffffffull;
    const quint64 exponent_mask = 0x7ff0000000000000ull;

    union {
        quint64 val;
        double dbl;
    };
    dbl = d;
    int exp = (int)((val & exponent_mask) >> exponent_off) - 1023;
    if (exp < 0 || exp > 25)
        return INT_MAX;

    quint64 non_int = val & (fraction_mask >> exp);
    if (non_int)
        return INT_MAX;

    bool neg = (val >> 63);
    val &= fraction_mask;
    val |= ((quint64)1 << 52);
    int res = (int)(val >> (52 - exp));
    return neg ? -res : res;
}

struct Latin1String;

struct String
{
    String(const char *data) { d = (Data *)data; }

    struct Data {
        qle_int length;
        qle_ushort utf16[1];
    };

    Data *d;

    inline String &operator=(const QString &str)
    {
        d->length = str.length();
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
        for (int i = 0; i < str.length(); ++i)
            d->utf16[i] = uc[i];
#else
        memcpy(d->utf16, str.unicode(), str.length()*sizeof(ushort));
#endif
        if (str.length() & 1)
            d->utf16[str.length()] = 0;
        return *this;
    }

    bool operator ==(const QString &str) {
        int slen = str.length();
        const ushort *s = (const ushort *)str.constData();
        int l = d->length;
        if (slen != l)
            return false;
        const qle_ushort *a = d->utf16;
        const ushort *b = s;
        while (l-- && *a == *b)
            a++,b++;
        return (l == -1);
    }
    bool operator !=(const QString &str) {
        return !operator ==(str);
    }
    QString toString() const {
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
        return QString((QChar *)d->utf16, d->length);
#else
        int l = d->length;
        QString str(l, QChar());
        QChar *ch = str.data();
        for (int i = 0; i < l; ++i)
            ch[i] = d->utf16[i];
        return str;
#endif
    }

};

struct Latin1String
{
    Latin1String(const char *data) { d = (Data *)data; }

    struct Data {
        qle_short length;
        char latin1[1];
    };
    Data *d;

    inline Latin1String &operator=(const QString &str)
    {
        d->length = str.length();
        uchar *l = (uchar *)d->latin1;
        const ushort *uc = (const ushort *)str.unicode();
        for (int i = 0; i < str.length(); ++i)
            *l++ = uc[i];
        while ((quintptr)l & 0x3)
            *l++ = 0;
        return *this;
    }

    bool operator ==(const QString &str) {
        int slen = str.length();
        const ushort *s = (const ushort *)str.constData();
        if (slen != d->length)
            return false;
        int l = d->length;
        const uchar *a = (uchar *)d->latin1;
        const ushort *b = s;
        while (l-- && *a == *b)
            a++,b++;
        return (l == -1);
    }
    bool operator !=(const QString &str) {
        return !operator ==(str);
    }

    QString toString() const {
        return QString::fromLatin1(d->latin1, d->length);
    }
};


static inline void copyString(char *dest, const QString &str, bool compress)
{
    if (compress) {
        Latin1String string(dest);
        string = str;
    } else {
        String string(dest);
        string = str;
    }
}



struct Base
{
    qle_uint size;
    union {
        uint _dummy;
        qle_bitfield<0, 1> is_object;
        qle_bitfield<1, 31> length;
    };
    offset tableOffset;
    // content follows here

    inline bool isObject() const { return is_object; }
    inline bool isArray() const { return !isObject(); }

    inline offset *table() const { return (offset *) (((char *) this) + tableOffset); }

    int reserveSpace(uint dataSize, int posInTable, uint numItems, bool replace);
    void removeItems(int pos, int numItems);
};

struct Object : public Base
{

    Entry *entryAt(int i) const {
        return reinterpret_cast<Entry *>(((char *)this) + table()[i]);
    }
    int indexOf(const QString &key);

    bool isValid() const;
};


struct Array : public Base
{
    inline Value at(int i) const;
    inline Value &operator [](int i);

    bool isValid() const;
};


struct Value
{
    // unfortunately some compilers can't handle mixed types in bitfields.
    // this works around the problem
    union {
        uint _dummy;
        qle_bitfield<0, 3> type;
        qle_bitfield<3, 1> latinOrIntValue;
        qle_bitfield<4, 1> latinKey;
        qle_bitfield<5, 27> val;
        qle_signedbitfield<5, 27> int_val;
    };

    inline char *data(const Base *b) const { return ((char *)b) + val; }
    int usedStorage(const Base *b) const;

    bool toBoolean() const;
    double toDouble(const Base *b) const;
    QString toString(const Base *b) const;
    String asString(const Base *b) const;
    Latin1String asLatin1String(const Base *b) const;
    Base *objectOrArray(const Base *b) const;

    bool isValid(const Base *b) const;
};

inline Value Array::at(int i) const
{
    return * (Value *) (((char *) this) + tableOffset + i*sizeof(Value));
}

inline Value &Array::operator [](int i)
{
    return * (Value *) (((char *) this) + tableOffset + i*sizeof(Value));
}



struct Entry {
    Value value;
    // key
    // value data follows key

    int size() const {
        int s = sizeof(Entry);
        if (value.latinKey)
            s += sizeof(ushort) + *(ushort *) ((const char *)this + sizeof(Entry));
        else
            s += sizeof(uint) + *(int *) ((const char *)this + sizeof(Entry));
        return alignedSize(s);
    }

    int usedStorage(Base *b) const {
        return size() + value.usedStorage(b);
    }

    String shallowKey() const
    {
        Q_ASSERT(!value.latinKey);
        return String((const char *)this + sizeof(Entry));
    }
    Latin1String shallowLatin1Key() const
    {
        Q_ASSERT(value.latinKey);
        return Latin1String((const char *)this + sizeof(Entry));
    }
    QString key() const
    {
        if (value.latinKey) {
            return shallowLatin1Key().toString();
        }
        return shallowKey().toString();
    }

    bool matchesKey(const QString &key);
};

struct Header {
    qle_uint tag; // 'qbjs'
    qle_uint version; // 1
    Base *root() { return (Base *)(this + 1); }
};


inline bool Value::toBoolean() const
{
    Q_ASSERT(type == QJsonValue::Bool);
    return val != 0;
}

inline double Value::toDouble(const Base *b) const
{
    Q_ASSERT(type == QJsonValue::Double);
    if (latinOrIntValue)
        return int_val;

    union {
        quint64 i;
        double d;
    };
    i = qFromLittleEndian<quint64>((const uchar *)b + val);
    return d;
}

inline QString Value::toString(const Base *b) const
{
    char *d = data(b);
    if (latinOrIntValue) {
        int l = *(ushort *)d;
        return QString::fromLatin1(d + sizeof(ushort), l);
    }
    int l = *(int *)d;
    const QChar *c = (const QChar *)(d + sizeof(int));
    return QString(c, l);
}

inline String Value::asString(const Base *b) const
{
    Q_ASSERT(type == QJsonValue::String && !latinOrIntValue);
    return String(data(b));
}

inline Latin1String Value::asLatin1String(const Base *b) const
{
    Q_ASSERT(type == QJsonValue::String && latinOrIntValue);
    return Latin1String(data(b));
}

inline Base *Value::objectOrArray(const Base *b) const
{
    Q_ASSERT(type == QJsonValue::Array || type == QJsonValue::Object);
    return reinterpret_cast<Base *>(data(b));
}

struct Data {
    enum Validation {
        Unchecked,
        Validated,
        Invalid
    };

    inline Data(char *raw, int a)
        : alloc(a), compactionCounter(0), valid(Unchecked), ownsData(true), rawData(raw)
    {
        ref.store(0);
    }
    inline Data(int reserved, QJsonValue::Type valueType)
        : compactionCounter(0), valid(Validated), ownsData(true), rawData(0)
    {
        ref.store(0);

        alloc = sizeof(Header) + sizeof(Base) + reserved + sizeof(offset);
        header = (Header *)malloc(alloc);
        header->tag = QJsonDocument::BinaryFormatTag;
        header->version = 1;
        Base *b = header->root();
        b->size = sizeof(Base);
        b->is_object = (valueType == QJsonValue::Object);
        b->tableOffset = sizeof(Base);
        b->length = 0;
    }
    inline ~Data()
    { if (ownsData) free(rawData); }

    QBasicAtomicInt ref;
    int alloc;
    int compactionCounter;
    Validation valid;
    bool ownsData;
    union {
        char *rawData;
        Header *header;
    };

    uint offsetOf(const void *ptr) const { return ((char *)ptr - rawData); }

    Object *object(int offset) const { return reinterpret_cast<Object *>(rawData + offset); }
    Entry *entry(int offset) const { return reinterpret_cast<Entry *>(rawData + offset); }
    Value *value(int offset) const { return reinterpret_cast<Value *>(rawData + offset); }
    Array *array(int offset) const { return reinterpret_cast<Array *>(rawData + offset); }


    QJsonObject toObject(Object *o) const
    {
        return QJsonObject(const_cast<Data *>(this), o);
    }

    QJsonArray toArray(Array *a) const
    {
        return QJsonArray(const_cast<Data *>(this), a);
    }

    Data *detach(Base *b, int reserve = 0)
    {
        int size = sizeof(Header) + b->size + reserve;
        char *raw = (char *)malloc(size);
        memcpy(raw + sizeof(Header), b, b->size);
        Header *h = (Header *)raw;
        h->tag = QJsonDocument::BinaryFormatTag;
        h->version = 1;
        Data *d = new Data(raw, size);
        d->compactionCounter = compactionCounter;
        return d;
    }

    void compact();
    void validate();
};

}

}

#endif // QJSON_P_H