summaryrefslogtreecommitdiffstats
path: root/src/qjson_p.h
blob: 91753668e647f557216cd4ac0bcdd48791d686b3 (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
/****************************************************************************
**
** 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 <qjsonarray.h>
#include <qbasicatomic.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
{

typedef uint offset;
struct Array;
struct Object;
struct Value;
struct Entry;

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 {
        int length;
        ushort utf16[1];
    };

    Data *d;

    inline String &operator=(const QString &str)
    {
        d->length = str.length();
        memcpy(d->utf16, str.unicode(), d->length*sizeof(ushort));
        if (d->length & 1)
            d->utf16[d->length] = 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 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);
    }
};

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

    struct Data {
        short length;
        uchar latin1[1];
    };
    Data *d;

    inline Latin1String &operator=(const QString &str)
    {
        d->length = str.length();
        uchar *l = 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 = d->latin1;
        const ushort *b = s;
        while (l-- && *a == *b)
            a++,b++;
        return (l == -1);
    }
    bool operator !=(const QString &str) {
        return !operator ==(str);
    }
};


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
{
    uint size;
    uint length : 31;
    uint is_object : 1; // object or Array
    offset tableOffset;
    // content follows here

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

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

    int reserveSpace(uint dataSize, int posInTable, uint numItems);
    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);
    int insertKey(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 {
        struct {
            int unused : 5;
            int int_val : 27;
        };
        struct {
            uint type : 3;
            uint latinOrIntValue : 1;
            uint latinKey : 1;
            uint val : 27;
        };
    };


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

    bool toBoolean() const;
    double toNumber(const Base *b) const;
    int toInt() 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;
    ushort *keyData() const { return (ushort *)((const char *)this + sizeof(Entry) + sizeof(int)); }
    uchar *latin1KeyData() const { return (uchar *)((const char *)this + sizeof(Entry) + sizeof(ushort)); }
    // 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) {
            int length = *(ushort *) ((const char *)this + sizeof(Entry));
            return QString::fromLatin1((const char *)latin1KeyData(), length);
        }
        int length = *(int *) ((const char *)this + sizeof(Entry));
        return QString((const QChar *)keyData(), length);
    }

    bool matchesKey(const QString &key);
};

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


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

inline double Value::toNumber(const Base *b) const
{
    Q_ASSERT(type == NumberValue);
    if (latinOrIntValue)
        return int_val;

    union {
        char raw[sizeof(double)];
        double d;
    };
    memcpy(raw, ((char *)b + val), sizeof(double));
    return d;
}

inline int Value::toInt() const
{
    Q_ASSERT(type == NumberValue && latinOrIntValue);
    return int_val;
}

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 == StringValue && !latinOrIntValue);
    return String(data(b));
}

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

inline Base *Value::objectOrArray(const Base *b) const
{
    Q_ASSERT(type == ArrayValue || type == ObjectValue);
    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), rawData(raw)
    {
        ref.store(0);
    }
    inline Data(int reserved, ValueType valueType)
        : compactionCounter(0), valid(Validated), rawData(0)
    {
        ref.store(0);

        alloc = sizeof(Header) + sizeof(Base) + reserved + sizeof(offset);
        header = (Header *)malloc(alloc);
        header->tag = QBJS_Tag;
        header->version = 1;
        Base *b = header->root();
        b->size = sizeof(Base);
        b->is_object = (valueType == ObjectValue);
        b->tableOffset = sizeof(Base);
        b->length = 0;
    }
    inline ~Data()
    { free(rawData); }

    QBasicAtomicInt ref;
    int alloc;
    int compactionCounter;
    Validation valid;
    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); }


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

    JsonArray toArray(Array *a) const
    {
        return JsonArray(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 = QBJS_Tag;
        h->version = 1;
        Data *d = new Data(raw, size);
        d->compactionCounter = compactionCounter;
        return d;
    }

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

}

#endif // QJSON_P_H