Coverage Report

Created: 2025-12-30 13:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/util/jsonb_document.h
Line
Count
Source
1
/*
2
 *  Copyright (c) 2014, Facebook, Inc.
3
 *  All rights reserved.
4
 *
5
 *  This source code is licensed under the BSD-style license found in the
6
 *  LICENSE file in the root directory of this source tree. An additional grant
7
 *  of patent rights can be found in the PATENTS file in the same directory.
8
 *
9
 */
10
11
/*
12
 * This header defines JsonbDocument, JsonbKeyValue, and various value classes
13
 * which are derived from JsonbValue, and a forward iterator for container
14
 * values - essentially everything that is related to JSONB binary data
15
 * structures.
16
 *
17
 * Implementation notes:
18
 *
19
 * None of the classes in this header file can be instantiated directly (i.e.
20
 * you cannot create a JsonbKeyValue or JsonbValue object - all constructors
21
 * are declared non-public). We use the classes as wrappers on the packed JSONB
22
 * bytes (serialized), and cast the classes (types) to the underlying packed
23
 * byte array.
24
 *
25
 * For the same reason, we cannot define any JSONB value class to be virtual,
26
 * since we never call constructors, and will not instantiate vtbl and vptrs.
27
 *
28
 * Therefore, the classes are defined as packed structures (i.e. no data
29
 * alignment and padding), and the private member variables of the classes are
30
 * defined precisely in the same order as the JSONB spec. This ensures we
31
 * access the packed JSONB bytes correctly.
32
 *
33
 * The packed structures are highly optimized for in-place operations with low
34
 * overhead. The reads (and in-place writes) are performed directly on packed
35
 * bytes. There is no memory allocation at all at runtime.
36
 *
37
 * For updates/writes of values that will expand the original JSONB size, the
38
 * write will fail, and the caller needs to handle buffer increase.
39
 *
40
 * ** Iterator **
41
 * Both ObjectVal class and ArrayVal class have iterator type that you can use
42
 * to declare an iterator on a container object to go through the key-value
43
 * pairs or value list. The iterator has both non-const and const types.
44
 *
45
 * Note: iterators are forward direction only.
46
 *
47
 * ** Query **
48
 * Querying into containers is through the member functions find (for key/value
49
 * pairs) and get (for array elements), and is in streaming style. We don't
50
 * need to read/scan the whole JSONB packed bytes in order to return results.
51
 * Once the key/index is found, we will stop search.  You can use text to query
52
 * both objects and array (for array, text will be converted to integer index),
53
 * and use index to retrieve from array. Array index is 0-based.
54
 *
55
 * ** External dictionary **
56
 * During query processing, you can also pass a call-back function, so the
57
 * search will first try to check if the key string exists in the dictionary.
58
 * If so, search will be based on the id instead of the key string.
59
 * @author Tian Xia <tianx@fb.com>
60
 * 
61
 * this file is copied from 
62
 * https://github.com/facebook/mysql-5.6/blob/fb-mysql-5.6.35/fbson/FbsonDocument.h
63
 * and modified by Doris
64
 */
65
66
#ifndef JSONB_JSONBDOCUMENT_H
67
#define JSONB_JSONBDOCUMENT_H
68
69
#include <algorithm>
70
#include <cctype>
71
#include <charconv>
72
#include <cstddef>
73
#include <cstdint>
74
#include <string>
75
#include <string_view>
76
#include <type_traits>
77
78
#include "common/compiler_util.h" // IWYU pragma: keep
79
#include "common/status.h"
80
#include "runtime/define_primitive_type.h"
81
#include "util/string_util.h"
82
#include "vec/common/string_ref.h"
83
#include "vec/core/types.h"
84
85
// #include "util/string_parser.hpp"
86
87
// Concept to check for supported decimal types
88
template <typename T>
89
concept JsonbDecimalType = std::same_as<T, doris::vectorized::Decimal256> ||
90
                           std::same_as<T, doris::vectorized::Decimal64> ||
91
                           std::same_as<T, doris::vectorized::Decimal128V3> ||
92
                           std::same_as<T, doris::vectorized::Decimal32>;
93
94
namespace doris {
95
96
template <typename T>
97
constexpr bool is_pod_v = std::is_trivial_v<T> && std::is_standard_layout_v<T>;
98
99
struct JsonbStringVal;
100
struct ObjectVal;
101
struct ArrayVal;
102
struct JsonbBinaryVal;
103
struct ContainerVal;
104
105
template <JsonbDecimalType T>
106
struct JsonbDecimalVal;
107
108
using JsonbDecimal256 = JsonbDecimalVal<vectorized::Decimal256>;
109
using JsonbDecimal128 = JsonbDecimalVal<vectorized::Decimal128V3>;
110
using JsonbDecimal64 = JsonbDecimalVal<vectorized::Decimal64>;
111
using JsonbDecimal32 = JsonbDecimalVal<vectorized::Decimal32>;
112
113
template <typename T>
114
    requires std::is_integral_v<T> || std::is_floating_point_v<T>
115
struct NumberValT;
116
117
using JsonbInt8Val = NumberValT<int8_t>;
118
using JsonbInt16Val = NumberValT<int16_t>;
119
using JsonbInt32Val = NumberValT<int32_t>;
120
using JsonbInt64Val = NumberValT<int64_t>;
121
using JsonbInt128Val = NumberValT<int128_t>;
122
using JsonbDoubleVal = NumberValT<double>;
123
using JsonbFloatVal = NumberValT<float>;
124
125
template <typename T>
126
concept JsonbPodType = (std::same_as<T, JsonbStringVal> || std::same_as<T, ObjectVal> ||
127
                        std::same_as<T, ContainerVal> || std::same_as<T, ArrayVal> ||
128
                        std::same_as<T, JsonbBinaryVal> || std::same_as<T, JsonbDecimal32> ||
129
                        std::same_as<T, JsonbDecimal64> || std::same_as<T, JsonbDecimal128> ||
130
                        std::same_as<T, JsonbDecimal256> || std::same_as<T, JsonbDecimal32> ||
131
                        std::same_as<T, JsonbInt8Val> || std::same_as<T, JsonbInt16Val> ||
132
                        std::same_as<T, JsonbInt32Val> || std::same_as<T, JsonbInt64Val> ||
133
                        std::same_as<T, JsonbInt128Val> || std::same_as<T, JsonbFloatVal> ||
134
                        std::same_as<T, JsonbFloatVal> || std::same_as<T, JsonbDoubleVal>);
135
136
1.21M
#define JSONB_VER 1
137
138
using int128_t = __int128;
139
140
// forward declaration
141
struct JsonbValue;
142
143
class JsonbOutStream;
144
145
template <class OS_TYPE>
146
class JsonbWriterT;
147
148
using JsonbWriter = JsonbWriterT<JsonbOutStream>;
149
150
const int MaxNestingLevel = 100;
151
152
/*
153
 * JsonbType defines 10 primitive types and 2 container types, as described
154
 * below.
155
 * NOTE: Do NOT modify the existing values or their order in this enum.
156
 *      You may only append new entries at the end before `NUM_TYPES`.
157
 *      This enum will be used in serialized data and/or persisted data.
158
 *      Changing existing values may break backward compatibility
159
 *      with previously stored or transmitted data.
160
 *
161
 * primitive_value ::=
162
 *   0x00        //null value (0 byte)
163
 * | 0x01        //boolean true (0 byte)
164
 * | 0x02        //boolean false (0 byte)
165
 * | 0x03 int8   //char/int8 (1 byte)
166
 * | 0x04 int16  //int16 (2 bytes)
167
 * | 0x05 int32  //int32 (4 bytes)
168
 * | 0x06 int64  //int64 (8 bytes)
169
 * | 0x07 double //floating point (8 bytes)
170
 * | 0x08 string //variable length string
171
 * | 0x09 binary //variable length binary
172
 *
173
 * container ::=
174
 *   0x0A int32 key_value_list //object, int32 is the total bytes of the object
175
 * | 0x0B int32 value_list     //array, int32 is the total bytes of the array
176
 */
177
enum class JsonbType : char {
178
    T_Null = 0x00,
179
    T_True = 0x01,
180
    T_False = 0x02,
181
    T_Int8 = 0x03,
182
    T_Int16 = 0x04,
183
    T_Int32 = 0x05,
184
    T_Int64 = 0x06,
185
    T_Double = 0x07,
186
    T_String = 0x08,
187
    T_Binary = 0x09,
188
    T_Object = 0x0A,
189
    T_Array = 0x0B,
190
    T_Int128 = 0x0C,
191
    T_Float = 0x0D,
192
    T_Decimal32 = 0x0E,  // DecimalV3 only
193
    T_Decimal64 = 0x0F,  // DecimalV3 only
194
    T_Decimal128 = 0x10, // DecimalV3 only
195
    T_Decimal256 = 0x11, // DecimalV3 only
196
    NUM_TYPES,
197
};
198
199
11
inline PrimitiveType get_primitive_type_from_json_type(JsonbType json_type) {
200
11
    switch (json_type) {
201
1
    case JsonbType::T_Null:
202
1
        return TYPE_NULL;
203
1
    case JsonbType::T_True:
204
2
    case JsonbType::T_False:
205
2
        return TYPE_BOOLEAN;
206
0
    case JsonbType::T_Int8:
207
0
        return TYPE_TINYINT;
208
0
    case JsonbType::T_Int16:
209
0
        return TYPE_SMALLINT;
210
0
    case JsonbType::T_Int32:
211
0
        return TYPE_INT;
212
0
    case JsonbType::T_Int64:
213
0
        return TYPE_BIGINT;
214
0
    case JsonbType::T_Double:
215
0
        return TYPE_DOUBLE;
216
1
    case JsonbType::T_String:
217
1
        return TYPE_STRING;
218
0
    case JsonbType::T_Binary:
219
0
        return TYPE_BINARY;
220
0
    case JsonbType::T_Object:
221
0
        return TYPE_STRUCT;
222
1
    case JsonbType::T_Array:
223
1
        return TYPE_ARRAY;
224
1
    case JsonbType::T_Int128:
225
1
        return TYPE_LARGEINT;
226
1
    case JsonbType::T_Float:
227
1
        return TYPE_FLOAT;
228
1
    case JsonbType::T_Decimal32:
229
1
        return TYPE_DECIMAL32;
230
1
    case JsonbType::T_Decimal64:
231
1
        return TYPE_DECIMAL64;
232
1
    case JsonbType::T_Decimal128:
233
1
        return TYPE_DECIMAL128I;
234
1
    case JsonbType::T_Decimal256:
235
1
        return TYPE_DECIMAL256;
236
0
    default:
237
0
        throw Exception(ErrorCode::INTERNAL_ERROR, "Unsupported JsonbType: {}",
238
0
                        static_cast<int>(json_type));
239
11
    }
240
11
}
241
242
//for parse json path
243
constexpr char SCOPE = '$';
244
constexpr char BEGIN_MEMBER = '.';
245
constexpr char BEGIN_ARRAY = '[';
246
constexpr char END_ARRAY = ']';
247
constexpr char DOUBLE_QUOTE = '"';
248
constexpr char WILDCARD = '*';
249
constexpr char MINUS = '-';
250
constexpr char LAST[] = "last";
251
constexpr char ESCAPE = '\\';
252
constexpr unsigned int MEMBER_CODE = 0;
253
constexpr unsigned int ARRAY_CODE = 1;
254
255
/// A simple input stream class for the JSON path parser.
256
class Stream {
257
public:
258
    /// Creates an input stream reading from a character string.
259
    /// @param string  the input string
260
    /// @param length  the length of the input string
261
96
    Stream(const char* string, size_t length) : m_position(string), m_end(string + length) {}
262
263
    /// Returns a pointer to the current position in the stream.
264
90
    const char* position() const { return m_position; }
265
266
    /// Returns a pointer to the position just after the end of the stream.
267
0
    const char* end() const { return m_end; }
268
269
    /// Returns the number of bytes remaining in the stream.
270
1.71k
    size_t remaining() const {
271
1.71k
        assert(m_position <= m_end);
272
1.71k
        return m_end - m_position;
273
1.71k
    }
274
275
    /// Tells if the stream has been exhausted.
276
1.56k
    bool exhausted() const { return remaining() == 0; }
277
278
    /// Reads the next byte from the stream and moves the position forward.
279
96
    char read() {
280
96
        assert(!exhausted());
281
96
        return *m_position++;
282
96
    }
283
284
    /// Reads the next byte from the stream without moving the position forward.
285
796
    char peek() const {
286
796
        assert(!exhausted());
287
796
        return *m_position;
288
796
    }
289
290
    /// Moves the position to the next non-whitespace character.
291
334
    void skip_whitespace() {
292
334
        m_position = std::find_if_not(m_position, m_end, [](char c) { return std::isspace(c); });
293
334
    }
294
295
    /// Moves the position n bytes forward.
296
148
    void skip(size_t n) {
297
148
        assert(remaining() >= n);
298
148
        m_position += n;
299
148
        skip_whitespace();
300
148
    }
301
302
122
    void advance() { m_position++; }
303
304
180
    void clear_leg_ptr() { leg_ptr = nullptr; }
305
306
90
    void set_leg_ptr(char* ptr) {
307
90
        clear_leg_ptr();
308
90
        leg_ptr = ptr;
309
90
    }
310
311
122
    char* get_leg_ptr() { return leg_ptr; }
312
313
90
    void clear_leg_len() { leg_len = 0; }
314
315
122
    void add_leg_len() { leg_len++; }
316
317
180
    unsigned int get_leg_len() const { return leg_len; }
318
319
0
    void remove_escapes() {
320
0
        int new_len = 0;
321
0
        for (int i = 0; i < leg_len; i++) {
322
0
            if (leg_ptr[i] != '\\') {
323
0
                leg_ptr[new_len++] = leg_ptr[i];
324
0
            }
325
0
        }
326
0
        leg_ptr[new_len] = '\0';
327
0
        leg_len = new_len;
328
0
    }
329
330
0
    void set_has_escapes(bool has) { has_escapes = has; }
331
332
32
    bool get_has_escapes() const { return has_escapes; }
333
334
private:
335
    /// The current position in the stream.
336
    const char* m_position = nullptr;
337
338
    /// The end of the stream.
339
    const char* const m_end;
340
341
    ///path leg ptr
342
    char* leg_ptr = nullptr;
343
344
    ///path leg len
345
    unsigned int leg_len;
346
347
    ///Whether to contain escape characters
348
    bool has_escapes = false;
349
};
350
351
struct leg_info {
352
    ///path leg ptr
353
    char* leg_ptr = nullptr;
354
355
    ///path leg len
356
    unsigned int leg_len;
357
358
    ///array_index
359
    int array_index;
360
361
    ///type: 0 is member 1 is array
362
    unsigned int type;
363
364
0
    bool to_string(std::string* str) const {
365
0
        if (type == MEMBER_CODE) {
366
0
            str->push_back(BEGIN_MEMBER);
367
0
            bool contains_space = false;
368
0
            std::string tmp;
369
0
            for (auto* it = leg_ptr; it != (leg_ptr + leg_len); ++it) {
370
0
                if (std::isspace(*it)) {
371
0
                    contains_space = true;
372
0
                } else if (*it == '"' || *it == ESCAPE || *it == '\r' || *it == '\n' ||
373
0
                           *it == '\b' || *it == '\t') {
374
0
                    tmp.push_back(ESCAPE);
375
0
                }
376
0
                tmp.push_back(*it);
377
0
            }
378
0
            if (contains_space) {
379
0
                str->push_back(DOUBLE_QUOTE);
380
0
            }
381
0
            str->append(tmp);
382
0
            if (contains_space) {
383
0
                str->push_back(DOUBLE_QUOTE);
384
0
            }
385
0
            return true;
386
0
        } else if (type == ARRAY_CODE) {
387
0
            str->push_back(BEGIN_ARRAY);
388
0
            std::string int_str = std::to_string(array_index);
389
0
            str->append(int_str);
390
0
            str->push_back(END_ARRAY);
391
0
            return true;
392
0
        } else {
393
0
            return false;
394
0
        }
395
0
    }
396
};
397
398
class JsonbPath {
399
public:
400
    // parse json path
401
    static bool parsePath(Stream* stream, JsonbPath* path);
402
403
    static bool parse_array(Stream* stream, JsonbPath* path);
404
    static bool parse_member(Stream* stream, JsonbPath* path);
405
406
    //return true if json path valid else return false
407
    bool seek(const char* string, size_t length);
408
409
90
    void add_leg_to_leg_vector(std::unique_ptr<leg_info> leg) {
410
90
        leg_vector.emplace_back(leg.release());
411
90
    }
412
413
0
    void pop_leg_from_leg_vector() { leg_vector.pop_back(); }
414
415
0
    bool to_string(std::string* res) const {
416
0
        res->push_back(SCOPE);
417
0
        for (const auto& leg : leg_vector) {
418
0
            auto valid = leg->to_string(res);
419
0
            if (!valid) {
420
0
                return false;
421
0
            }
422
0
        }
423
0
        return true;
424
0
    }
425
426
185
    size_t get_leg_vector_size() const { return leg_vector.size(); }
427
428
295
    leg_info* get_leg_from_leg_vector(size_t i) const { return leg_vector[i].get(); }
429
430
0
    bool is_wildcard() const { return _is_wildcard; }
431
95
    bool is_supper_wildcard() const { return _is_supper_wildcard; }
432
433
6
    void clean() { leg_vector.clear(); }
434
435
private:
436
    std::vector<std::unique_ptr<leg_info>> leg_vector;
437
    bool _is_wildcard = false;        // whether the path is a wildcard path
438
    bool _is_supper_wildcard = false; // supper wildcard likes '$**.a' or '$**[1]'
439
};
440
441
/*
442
 * JsonbFwdIteratorT implements JSONB's iterator template.
443
 *
444
 * Note: it is an FORWARD iterator only due to the design of JSONB format.
445
 */
446
template <class Iter_Type, class Cont_Type>
447
class JsonbFwdIteratorT {
448
public:
449
    using iterator = Iter_Type;
450
    using pointer = typename std::iterator_traits<Iter_Type>::pointer;
451
    using reference = typename std::iterator_traits<Iter_Type>::reference;
452
453
    explicit JsonbFwdIteratorT() : current_(nullptr) {}
454
20.2k
    explicit JsonbFwdIteratorT(const iterator& i) : current_(i) {}
_ZN5doris17JsonbFwdIteratorTIPKNS_13JsonbKeyValueENS_9ObjectValEEC2ERKS3_
Line
Count
Source
454
20.0k
    explicit JsonbFwdIteratorT(const iterator& i) : current_(i) {}
_ZN5doris17JsonbFwdIteratorTIPKNS_10JsonbValueENS_8ArrayValEEC2ERKS3_
Line
Count
Source
454
131
    explicit JsonbFwdIteratorT(const iterator& i) : current_(i) {}
455
456
    // allow non-const to const iterator conversion (same container type)
457
    template <class Iter_Ty>
458
    JsonbFwdIteratorT(const JsonbFwdIteratorT<Iter_Ty, Cont_Type>& rhs) : current_(rhs.base()) {}
459
460
20.3k
    bool operator==(const JsonbFwdIteratorT& rhs) const { return (current_ == rhs.current_); }
_ZNK5doris17JsonbFwdIteratorTIPKNS_13JsonbKeyValueENS_9ObjectValEEeqERKS5_
Line
Count
Source
460
19.0k
    bool operator==(const JsonbFwdIteratorT& rhs) const { return (current_ == rhs.current_); }
_ZNK5doris17JsonbFwdIteratorTIPKNS_10JsonbValueENS_8ArrayValEEeqERKS5_
Line
Count
Source
460
1.32k
    bool operator==(const JsonbFwdIteratorT& rhs) const { return (current_ == rhs.current_); }
461
462
19.8k
    bool operator!=(const JsonbFwdIteratorT& rhs) const { return !operator==(rhs); }
_ZNK5doris17JsonbFwdIteratorTIPKNS_13JsonbKeyValueENS_9ObjectValEEneERKS5_
Line
Count
Source
462
18.5k
    bool operator!=(const JsonbFwdIteratorT& rhs) const { return !operator==(rhs); }
_ZNK5doris17JsonbFwdIteratorTIPKNS_10JsonbValueENS_8ArrayValEEneERKS5_
Line
Count
Source
462
1.26k
    bool operator!=(const JsonbFwdIteratorT& rhs) const { return !operator==(rhs); }
463
464
1.05k
    bool operator<(const JsonbFwdIteratorT& rhs) const { return (current_ < rhs.current_); }
465
466
    bool operator>(const JsonbFwdIteratorT& rhs) const { return !operator<(rhs); }
467
468
18.0k
    JsonbFwdIteratorT& operator++() {
469
18.0k
        current_ = (iterator)(((char*)current_) + current_->numPackedBytes());
470
18.0k
        return *this;
471
18.0k
    }
_ZN5doris17JsonbFwdIteratorTIPKNS_13JsonbKeyValueENS_9ObjectValEEppEv
Line
Count
Source
468
17.4k
    JsonbFwdIteratorT& operator++() {
469
17.4k
        current_ = (iterator)(((char*)current_) + current_->numPackedBytes());
470
17.4k
        return *this;
471
17.4k
    }
_ZN5doris17JsonbFwdIteratorTIPKNS_10JsonbValueENS_8ArrayValEEppEv
Line
Count
Source
468
600
    JsonbFwdIteratorT& operator++() {
469
600
        current_ = (iterator)(((char*)current_) + current_->numPackedBytes());
470
600
        return *this;
471
600
    }
472
473
    JsonbFwdIteratorT operator++(int) {
474
        auto tmp = *this;
475
        current_ = (iterator)(((char*)current_) + current_->numPackedBytes());
476
        return tmp;
477
    }
478
479
600
    explicit operator pointer() { return current_; }
480
481
0
    reference operator*() const { return *current_; }
Unexecuted instantiation: _ZNK5doris17JsonbFwdIteratorTIPKNS_13JsonbKeyValueENS_9ObjectValEEdeEv
Unexecuted instantiation: _ZNK5doris17JsonbFwdIteratorTIPKNS_10JsonbValueENS_8ArrayValEEdeEv
482
483
28.5k
    pointer operator->() const { return current_; }
_ZNK5doris17JsonbFwdIteratorTIPKNS_13JsonbKeyValueENS_9ObjectValEEptEv
Line
Count
Source
483
28.5k
    pointer operator->() const { return current_; }
_ZNK5doris17JsonbFwdIteratorTIPKNS_10JsonbValueENS_8ArrayValEEptEv
Line
Count
Source
483
3
    pointer operator->() const { return current_; }
484
485
    iterator base() const { return current_; }
486
487
private:
488
    iterator current_;
489
};
490
using JsonbTypeUnder = std::underlying_type_t<JsonbType>;
491
492
#if defined(__clang__)
493
#pragma clang diagnostic push
494
#pragma clang diagnostic ignored "-Wzero-length-array"
495
#endif
496
#pragma pack(push, 1)
497
498
/*
499
 * JsonbDocument is the main object that accesses and queries JSONB packed
500
 * bytes. NOTE: JsonbDocument only allows object container as the top level
501
 * JSONB value. However, you can use the static method "createValue" to get any
502
 * JsonbValue object from the packed bytes.
503
 *
504
 * JsonbDocument object also dereferences to an object container value
505
 * (ObjectVal) once JSONB is loaded.
506
 *
507
 * ** Load **
508
 * JsonbDocument is usable after loading packed bytes (memory location) into
509
 * the object. We only need the header and first few bytes of the payload after
510
 * header to verify the JSONB.
511
 *
512
 * Note: creating an JsonbDocument (through createDocument) does not allocate
513
 * any memory. The document object is an efficient wrapper on the packed bytes
514
 * which is accessed directly.
515
 *
516
 * ** Query **
517
 * Query is through dereferencing into ObjectVal.
518
 */
519
class JsonbDocument {
520
public:
521
    // create an JsonbDocument object from JSONB packed bytes
522
    [[nodiscard]] static Status checkAndCreateDocument(const char* pb, size_t size,
523
                                                       const JsonbDocument** doc);
524
525
    // create an JsonbValue from JSONB packed bytes
526
    static const JsonbValue* createValue(const char* pb, size_t size);
527
528
0
    uint8_t version() const { return header_.ver_; }
529
530
26.4k
    const JsonbValue* getValue() const { return ((const JsonbValue*)payload_); }
531
532
    unsigned int numPackedBytes() const;
533
534
    const ObjectVal* operator->() const;
535
536
private:
537
    /*
538
   * JsonbHeader class defines JSONB header (internal to JsonbDocument).
539
   *
540
   * Currently it only contains version information (1-byte). We may expand the
541
   * header to include checksum of the JSONB binary for more security.
542
   */
543
    struct JsonbHeader {
544
        uint8_t ver_;
545
    } header_;
546
547
    char payload_[0];
548
};
549
550
/*
551
 * JsonbKeyValue class defines JSONB key type, as described below.
552
 *
553
 * key ::=
554
 *   0x00 int8    //1-byte dictionary id
555
 * | int8 (byte*) //int8 (>0) is the size of the key string
556
 *
557
 * value ::= primitive_value | container
558
 *
559
 * JsonbKeyValue can be either an id mapping to the key string in an external
560
 * dictionary, or it is the original key string. Whether to read an id or a
561
 * string is decided by the first byte (size).
562
 *
563
 * Note: a key object must be followed by a value object. Therefore, a key
564
 * object implicitly refers to a key-value pair, and you can get the value
565
 * object right after the key object. The function numPackedBytes hence
566
 * indicates the total size of the key-value pair, so that we will be able go
567
 * to next pair from the key.
568
 *
569
 * ** Dictionary size **
570
 * By default, the dictionary size is 255 (1-byte). Users can define
571
 * "USE_LARGE_DICT" to increase the dictionary size to 655535 (2-byte).
572
 */
573
class JsonbKeyValue {
574
public:
575
    // now we use sMaxKeyId to represent an empty key
576
    static const int sMaxKeyId = 65535;
577
    using keyid_type = uint16_t;
578
579
    static const uint8_t sMaxKeyLen = 64;
580
581
    // size of the key. 0 indicates it is stored as id
582
1.22k
    uint8_t klen() const { return size; }
583
584
    // get the key string. Note the string may not be null terminated.
585
631
    const char* getKeyStr() const { return key.str_; }
586
587
9.22k
    keyid_type getKeyId() const { return key.id_; }
588
589
34.9k
    unsigned int keyPackedBytes() const {
590
34.9k
        return size ? (sizeof(size) + size) : (sizeof(size) + sizeof(keyid_type));
591
34.9k
    }
592
593
17.4k
    const JsonbValue* value() const {
594
17.4k
        return (const JsonbValue*)(((char*)this) + keyPackedBytes());
595
17.4k
    }
596
597
    // size of the total packed bytes (key+value)
598
    unsigned int numPackedBytes() const;
599
600
    uint8_t size;
601
602
    union key_ {
603
        keyid_type id_;
604
        char str_[1];
605
    } key;
606
};
607
608
struct JsonbFindResult {
609
    const JsonbValue* value = nullptr;   // found value
610
    std::unique_ptr<JsonbWriter> writer; // writer to write the value
611
    bool is_wildcard = false;            // whether the path is a wildcard path
612
};
613
614
/*
615
 * JsonbValue is the base class of all JSONB types. It contains only one member
616
 * variable - type info, which can be retrieved by member functions is[Type]()
617
 * or type().
618
 */
619
struct JsonbValue {
620
    static const uint32_t sMaxValueLen = 1 << 24; // 16M
621
622
4.22k
    bool isNull() const { return (type == JsonbType::T_Null); }
623
21
    bool isTrue() const { return (type == JsonbType::T_True); }
624
1
    bool isFalse() const { return (type == JsonbType::T_False); }
625
4
    bool isInt() const { return isInt8() || isInt16() || isInt32() || isInt64() || isInt128(); }
626
4
    bool isInt8() const { return (type == JsonbType::T_Int8); }
627
2
    bool isInt16() const { return (type == JsonbType::T_Int16); }
628
0
    bool isInt32() const { return (type == JsonbType::T_Int32); }
629
3
    bool isInt64() const { return (type == JsonbType::T_Int64); }
630
1
    bool isDouble() const { return (type == JsonbType::T_Double); }
631
1
    bool isFloat() const { return (type == JsonbType::T_Float); }
632
33
    bool isString() const { return (type == JsonbType::T_String); }
633
1.07k
    bool isBinary() const { return (type == JsonbType::T_Binary); }
634
6
    bool isObject() const { return (type == JsonbType::T_Object); }
635
7
    bool isArray() const { return (type == JsonbType::T_Array); }
636
3
    bool isInt128() const { return (type == JsonbType::T_Int128); }
637
4
    bool isDecimal() const {
638
4
        return (type == JsonbType::T_Decimal32 || type == JsonbType::T_Decimal64 ||
639
4
                type == JsonbType::T_Decimal128 || type == JsonbType::T_Decimal256);
640
4
    }
641
1
    bool isDecimal32() const { return (type == JsonbType::T_Decimal32); }
642
1
    bool isDecimal64() const { return (type == JsonbType::T_Decimal64); }
643
1
    bool isDecimal128() const { return (type == JsonbType::T_Decimal128); }
644
1
    bool isDecimal256() const { return (type == JsonbType::T_Decimal256); }
645
646
11
    PrimitiveType get_primitive_type() const { return get_primitive_type_from_json_type(type); }
647
648
0
    const char* typeName() const {
649
0
        switch (type) {
650
0
        case JsonbType::T_Null:
651
0
            return "null";
652
0
        case JsonbType::T_True:
653
0
        case JsonbType::T_False:
654
0
            return "bool";
655
0
        case JsonbType::T_Int8:
656
0
        case JsonbType::T_Int16:
657
0
        case JsonbType::T_Int32:
658
0
            return "int";
659
0
        case JsonbType::T_Int64:
660
0
            return "bigint";
661
0
        case JsonbType::T_Int128:
662
0
            return "largeint";
663
0
        case JsonbType::T_Double:
664
0
            return "double";
665
0
        case JsonbType::T_Float:
666
0
            return "float";
667
0
        case JsonbType::T_String:
668
0
            return "string";
669
0
        case JsonbType::T_Binary:
670
0
            return "binary";
671
0
        case JsonbType::T_Object:
672
0
            return "object";
673
0
        case JsonbType::T_Array:
674
0
            return "array";
675
0
        case JsonbType::T_Decimal32:
676
0
            return "Decimal32";
677
0
        case JsonbType::T_Decimal64:
678
0
            return "Decimal64";
679
0
        case JsonbType::T_Decimal128:
680
0
            return "Decimal128";
681
0
        case JsonbType::T_Decimal256:
682
0
            return "Decimal256";
683
0
        default:
684
0
            return "unknown";
685
0
        }
686
0
    }
687
688
    // size of the total packed bytes
689
    unsigned int numPackedBytes() const;
690
691
    // size of the value in bytes
692
    unsigned int size() const;
693
694
    //Get the number of jsonbvalue elements
695
    int numElements() const;
696
697
    //Whether to include the jsonbvalue rhs
698
    bool contains(const JsonbValue* rhs) const;
699
700
    // find the JSONB value by JsonbPath
701
    JsonbFindResult findValue(JsonbPath& path) const;
702
    friend class JsonbDocument;
703
704
    JsonbType type; // type info
705
706
    char payload[0]; // payload, which is the packed bytes of the value
707
708
    /**
709
    * @brief Unpacks the underlying Jsonb binary content as a pointer to type `T`.
710
    *
711
    * @tparam T A POD (Plain Old Data) type that must satisfy the `JsonbPodType` concept.
712
    *           This ensures that `T` is trivially copyable, standard-layout, and safe to
713
    *           reinterpret from raw bytes without invoking undefined behavior.
714
    *
715
    * @return A pointer to a `const T` object, interpreted from the internal buffer.
716
    *
717
    * @note The caller must ensure that the current JsonbValue actually contains data
718
    *       compatible with type `T`, otherwise the result is undefined.
719
    */
720
    template <JsonbPodType T>
721
51.7k
    const T* unpack() const {
722
51.7k
        static_assert(is_pod_v<T>, "T must be a POD type");
723
51.7k
        return reinterpret_cast<const T*>(payload);
724
51.7k
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_9ObjectValEEEPKT_v
Line
Count
Source
721
19.5k
    const T* unpack() const {
722
19.5k
        static_assert(is_pod_v<T>, "T must be a POD type");
723
19.5k
        return reinterpret_cast<const T*>(payload);
724
19.5k
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_10NumberValTIaEEEEPKT_v
Line
Count
Source
721
665
    const T* unpack() const {
722
665
        static_assert(is_pod_v<T>, "T must be a POD type");
723
665
        return reinterpret_cast<const T*>(payload);
724
665
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_10NumberValTIsEEEEPKT_v
Line
Count
Source
721
105
    const T* unpack() const {
722
105
        static_assert(is_pod_v<T>, "T must be a POD type");
723
105
        return reinterpret_cast<const T*>(payload);
724
105
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_10NumberValTIiEEEEPKT_v
Line
Count
Source
721
3.47k
    const T* unpack() const {
722
3.47k
        static_assert(is_pod_v<T>, "T must be a POD type");
723
3.47k
        return reinterpret_cast<const T*>(payload);
724
3.47k
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_10NumberValTIlEEEEPKT_v
Line
Count
Source
721
1.89k
    const T* unpack() const {
722
1.89k
        static_assert(is_pod_v<T>, "T must be a POD type");
723
1.89k
        return reinterpret_cast<const T*>(payload);
724
1.89k
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_10NumberValTInEEEEPKT_v
Line
Count
Source
721
4.16k
    const T* unpack() const {
722
4.16k
        static_assert(is_pod_v<T>, "T must be a POD type");
723
4.16k
        return reinterpret_cast<const T*>(payload);
724
4.16k
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_14JsonbBinaryValEEEPKT_v
Line
Count
Source
721
19.5k
    const T* unpack() const {
722
19.5k
        static_assert(is_pod_v<T>, "T must be a POD type");
723
19.5k
        return reinterpret_cast<const T*>(payload);
724
19.5k
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_12ContainerValEEEPKT_v
Line
Count
Source
721
1.80k
    const T* unpack() const {
722
1.80k
        static_assert(is_pod_v<T>, "T must be a POD type");
723
1.80k
        return reinterpret_cast<const T*>(payload);
724
1.80k
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_8ArrayValEEEPKT_v
Line
Count
Source
721
99
    const T* unpack() const {
722
99
        static_assert(is_pod_v<T>, "T must be a POD type");
723
99
        return reinterpret_cast<const T*>(payload);
724
99
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_10NumberValTIdEEEEPKT_v
Line
Count
Source
721
168
    const T* unpack() const {
722
168
        static_assert(is_pod_v<T>, "T must be a POD type");
723
168
        return reinterpret_cast<const T*>(payload);
724
168
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_10NumberValTIfEEEEPKT_v
Line
Count
Source
721
25
    const T* unpack() const {
722
25
        static_assert(is_pod_v<T>, "T must be a POD type");
723
25
        return reinterpret_cast<const T*>(payload);
724
25
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_14JsonbStringValEEEPKT_v
Line
Count
Source
721
251
    const T* unpack() const {
722
251
        static_assert(is_pod_v<T>, "T must be a POD type");
723
251
        return reinterpret_cast<const T*>(payload);
724
251
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_15JsonbDecimalValINS_10vectorized7DecimalIiEEEEEEPKT_v
Line
Count
Source
721
13
    const T* unpack() const {
722
13
        static_assert(is_pod_v<T>, "T must be a POD type");
723
13
        return reinterpret_cast<const T*>(payload);
724
13
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_15JsonbDecimalValINS_10vectorized7DecimalIlEEEEEEPKT_v
Line
Count
Source
721
13
    const T* unpack() const {
722
13
        static_assert(is_pod_v<T>, "T must be a POD type");
723
13
        return reinterpret_cast<const T*>(payload);
724
13
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_15JsonbDecimalValINS_10vectorized12Decimal128V3EEEEEPKT_v
Line
Count
Source
721
17
    const T* unpack() const {
722
17
        static_assert(is_pod_v<T>, "T must be a POD type");
723
17
        return reinterpret_cast<const T*>(payload);
724
17
    }
_ZNK5doris10JsonbValue6unpackITkNS_12JsonbPodTypeENS_15JsonbDecimalValINS_10vectorized7DecimalIN4wide7integerILm256EiEEEEEEEEPKT_v
Line
Count
Source
721
13
    const T* unpack() const {
722
13
        static_assert(is_pod_v<T>, "T must be a POD type");
723
13
        return reinterpret_cast<const T*>(payload);
724
13
    }
725
726
    // /**
727
    // * @brief Unpacks the underlying Jsonb binary content as a pointer to type `T`.
728
    // *
729
    // * @tparam T A POD (Plain Old Data) type that must satisfy the `JsonbPodType` concept.
730
    // *           This ensures that `T` is trivially copyable, standard-layout, and safe to
731
    // *           reinterpret from raw bytes without invoking undefined behavior.
732
    // *
733
    // * @return A pointer to a `T` object, interpreted from the internal buffer.
734
    // *
735
    // * @note The caller must ensure that the current JsonbValue actually contains data
736
    // *       compatible with type `T`, otherwise the result is undefined.
737
    // */
738
    // template <JsonbPodType T>
739
    // T* unpack() {
740
    //     static_assert(is_pod_v<T>, "T must be a POD type");
741
    //     return reinterpret_cast<T*>(payload);
742
    // }
743
744
    int128_t int_val() const;
745
};
746
747
// inline ObjectVal* JsonbDocument::operator->() {
748
//     return (((JsonbValue*)payload_)->unpack<ObjectVal>());
749
// }
750
751
19.0k
inline const ObjectVal* JsonbDocument::operator->() const {
752
19.0k
    return (((const JsonbValue*)payload_)->unpack<ObjectVal>());
753
19.0k
}
754
755
/*
756
 * NumerValT is the template class (derived from JsonbValue) of all number
757
 * types (integers and double).
758
 */
759
template <typename T>
760
    requires std::is_integral_v<T> || std::is_floating_point_v<T>
761
struct NumberValT {
762
public:
763
10.5k
    T val() const { return num; }
_ZNK5doris10NumberValTIaE3valEv
Line
Count
Source
763
665
    T val() const { return num; }
_ZNK5doris10NumberValTIsE3valEv
Line
Count
Source
763
105
    T val() const { return num; }
_ZNK5doris10NumberValTIiE3valEv
Line
Count
Source
763
3.47k
    T val() const { return num; }
_ZNK5doris10NumberValTIlE3valEv
Line
Count
Source
763
1.89k
    T val() const { return num; }
_ZNK5doris10NumberValTInE3valEv
Line
Count
Source
763
4.16k
    T val() const { return num; }
_ZNK5doris10NumberValTIdE3valEv
Line
Count
Source
763
168
    T val() const { return num; }
_ZNK5doris10NumberValTIfE3valEv
Line
Count
Source
763
25
    T val() const { return num; }
764
765
    static unsigned int numPackedBytes() { return sizeof(JsonbValue) + sizeof(T); }
766
767
    T num;
768
};
769
770
9
inline int128_t JsonbValue::int_val() const {
771
9
    switch (type) {
772
3
    case JsonbType::T_Int8:
773
3
        return unpack<JsonbInt8Val>()->val();
774
1
    case JsonbType::T_Int16:
775
1
        return unpack<JsonbInt16Val>()->val();
776
0
    case JsonbType::T_Int32:
777
0
        return unpack<JsonbInt32Val>()->val();
778
3
    case JsonbType::T_Int64:
779
3
        return unpack<JsonbInt64Val>()->val();
780
2
    case JsonbType::T_Int128:
781
2
        return unpack<JsonbInt128Val>()->val();
782
0
    default:
783
0
        throw Exception(ErrorCode::INTERNAL_ERROR, "Invalid JSONB value type: {}",
784
0
                        static_cast<int32_t>(type));
785
9
    }
786
9
}
787
788
template <JsonbDecimalType T>
789
struct JsonbDecimalVal {
790
public:
791
    using NativeType = typename T::NativeType;
792
793
    // get the decimal value
794
26
    NativeType val() const {
795
        // to avoid memory alignment issues, we use memcpy to copy the value
796
26
        NativeType tmp;
797
26
        memcpy(&tmp, &value, sizeof(NativeType));
798
26
        return tmp;
799
26
    }
_ZNK5doris15JsonbDecimalValINS_10vectorized7DecimalIiEEE3valEv
Line
Count
Source
794
6
    NativeType val() const {
795
        // to avoid memory alignment issues, we use memcpy to copy the value
796
6
        NativeType tmp;
797
6
        memcpy(&tmp, &value, sizeof(NativeType));
798
6
        return tmp;
799
6
    }
_ZNK5doris15JsonbDecimalValINS_10vectorized7DecimalIlEEE3valEv
Line
Count
Source
794
6
    NativeType val() const {
795
        // to avoid memory alignment issues, we use memcpy to copy the value
796
6
        NativeType tmp;
797
6
        memcpy(&tmp, &value, sizeof(NativeType));
798
6
        return tmp;
799
6
    }
_ZNK5doris15JsonbDecimalValINS_10vectorized12Decimal128V3EE3valEv
Line
Count
Source
794
8
    NativeType val() const {
795
        // to avoid memory alignment issues, we use memcpy to copy the value
796
8
        NativeType tmp;
797
8
        memcpy(&tmp, &value, sizeof(NativeType));
798
8
        return tmp;
799
8
    }
_ZNK5doris15JsonbDecimalValINS_10vectorized7DecimalIN4wide7integerILm256EiEEEEE3valEv
Line
Count
Source
794
6
    NativeType val() const {
795
        // to avoid memory alignment issues, we use memcpy to copy the value
796
6
        NativeType tmp;
797
6
        memcpy(&tmp, &value, sizeof(NativeType));
798
6
        return tmp;
799
6
    }
800
801
29
    static constexpr int numPackedBytes() {
802
29
        return sizeof(JsonbValue) + sizeof(precision) + sizeof(scale) + sizeof(value);
803
29
    }
_ZN5doris15JsonbDecimalValINS_10vectorized7DecimalIiEEE14numPackedBytesEv
Line
Count
Source
801
7
    static constexpr int numPackedBytes() {
802
7
        return sizeof(JsonbValue) + sizeof(precision) + sizeof(scale) + sizeof(value);
803
7
    }
_ZN5doris15JsonbDecimalValINS_10vectorized7DecimalIlEEE14numPackedBytesEv
Line
Count
Source
801
7
    static constexpr int numPackedBytes() {
802
7
        return sizeof(JsonbValue) + sizeof(precision) + sizeof(scale) + sizeof(value);
803
7
    }
_ZN5doris15JsonbDecimalValINS_10vectorized12Decimal128V3EE14numPackedBytesEv
Line
Count
Source
801
9
    static constexpr int numPackedBytes() {
802
9
        return sizeof(JsonbValue) + sizeof(precision) + sizeof(scale) + sizeof(value);
803
9
    }
_ZN5doris15JsonbDecimalValINS_10vectorized7DecimalIN4wide7integerILm256EiEEEEE14numPackedBytesEv
Line
Count
Source
801
6
    static constexpr int numPackedBytes() {
802
6
        return sizeof(JsonbValue) + sizeof(precision) + sizeof(scale) + sizeof(value);
803
6
    }
804
805
    uint32_t precision;
806
    uint32_t scale;
807
    NativeType value;
808
};
809
810
/*
811
 * BlobVal is the base class (derived from JsonbValue) for string and binary
812
 * types. The size indicates the total bytes of the payload.
813
 */
814
struct JsonbBinaryVal {
815
public:
816
    // size of the blob payload only
817
2.11k
    unsigned int getBlobLen() const { return size; }
818
819
    // return the blob as byte array
820
4.51k
    const char* getBlob() const { return payload; }
821
822
    // size of the total packed bytes
823
15.1k
    unsigned int numPackedBytes() const { return sizeof(JsonbValue) + sizeof(size) + size; }
824
    friend class JsonbDocument;
825
826
    uint32_t size;
827
    char payload[0];
828
};
829
830
/*
831
 * String type
832
 * Note: JSONB string may not be a c-string (NULL-terminated)
833
 */
834
struct JsonbStringVal : public JsonbBinaryVal {
835
public:
836
    /*
837
    This function return the actual size of a string. Since for
838
    a string, it can be null-terminated with null paddings or it
839
    can take all the space in the payload without null in the end.
840
    So we need to check it to get the true actual length of a string.
841
  */
842
129
    size_t length() const {
843
        // It's an empty string
844
129
        if (0 == size) {
845
0
            return size;
846
0
        }
847
        // The string stored takes all the spaces in payload
848
129
        if (payload[size - 1] != 0) {
849
129
            return size;
850
129
        }
851
        // It's shorter than the size of payload
852
0
        return strnlen(payload, size);
853
129
    }
854
};
855
856
/*
857
 * ContainerVal is the base class (derived from JsonbValue) for object and
858
 * array types. The size indicates the total bytes of the payload.
859
 */
860
struct ContainerVal {
861
    // size of the container payload only
862
0
    unsigned int getContainerSize() const { return size; }
863
864
    // return the container payload as byte array
865
0
    const char* getPayload() const { return payload; }
866
867
    // size of the total packed bytes
868
1.80k
    unsigned int numPackedBytes() const { return sizeof(JsonbValue) + sizeof(size) + size; }
869
    friend class JsonbDocument;
870
871
    uint32_t size;
872
    char payload[0];
873
};
874
875
/*
876
 * Object type
877
 */
878
struct ObjectVal : public ContainerVal {
879
    using value_type = JsonbKeyValue;
880
    using pointer = value_type*;
881
    using const_pointer = const value_type*;
882
    using const_iterator = JsonbFwdIteratorT<const_pointer, ObjectVal>;
883
884
1
    const_iterator search(const char* key) const {
885
1
        if (!key) {
886
0
            return end();
887
0
        }
888
1
        return search(key, (unsigned int)strlen(key));
889
1
    }
890
891
29
    const_iterator search(const char* key, unsigned int klen) const {
892
29
        if (!key || !klen) {
893
0
            return end();
894
0
        }
895
29
        return internalSearch(key, klen);
896
29
    }
897
898
    // Get number of elements in object
899
8
    int numElem() const {
900
8
        const char* pch = payload;
901
8
        const char* fence = payload + size;
902
903
8
        unsigned int num = 0;
904
40
        while (pch < fence) {
905
32
            auto* pkey = (JsonbKeyValue*)(pch);
906
32
            ++num;
907
32
            pch += pkey->numPackedBytes();
908
32
        }
909
910
8
        assert(pch == fence);
911
912
8
        return num;
913
8
    }
914
915
    // find the JSONB value by a key string (null terminated)
916
1
    const JsonbValue* find(const char* key) const {
917
1
        if (!key) {
918
0
            return nullptr;
919
0
        }
920
1
        return find(key, (unsigned int)strlen(key));
921
1
    }
922
923
    // find the JSONB value by a key string (with length)
924
27
    const JsonbValue* find(const char* key, unsigned int klen) const {
925
27
        const_iterator kv = search(key, klen);
926
27
        if (end() == kv) {
927
2
            return nullptr;
928
2
        }
929
25
        return kv->value();
930
27
    }
931
932
1.60k
    const_iterator begin() const { return const_iterator((pointer)payload); }
933
934
18.4k
    const_iterator end() const { return const_iterator((pointer)(payload + size)); }
935
936
    std::vector<std::pair<StringRef, const JsonbValue*>> get_ordered_key_value_pairs() const;
937
938
private:
939
29
    const_iterator internalSearch(const char* key, unsigned int klen) const {
940
29
        const char* pch = payload;
941
29
        const char* fence = payload + size;
942
943
39
        while (pch < fence) {
944
37
            const auto* pkey = (const JsonbKeyValue*)(pch);
945
37
            if (klen == pkey->klen() && strncmp(key, pkey->getKeyStr(), klen) == 0) {
946
27
                return const_iterator(pkey);
947
27
            }
948
10
            pch += pkey->numPackedBytes();
949
10
        }
950
951
29
        assert(pch == fence);
952
953
2
        return end();
954
2
    }
955
};
956
957
/*
958
 * Array type
959
 */
960
struct ArrayVal : public ContainerVal {
961
    using value_type = JsonbValue;
962
    using pointer = value_type*;
963
    using const_pointer = const value_type*;
964
    using const_iterator = JsonbFwdIteratorT<const_pointer, ArrayVal>;
965
966
    // get the JSONB value at index
967
31
    const JsonbValue* get(int idx) const {
968
31
        if (idx < 0) {
969
0
            return nullptr;
970
0
        }
971
972
31
        const char* pch = payload;
973
31
        const char* fence = payload + size;
974
975
72
        while (pch < fence && idx-- > 0) {
976
41
            pch += ((const JsonbValue*)pch)->numPackedBytes();
977
41
        }
978
31
        if (idx > 0 || pch == fence) {
979
7
            return nullptr;
980
7
        }
981
982
24
        return (const JsonbValue*)pch;
983
31
    }
984
985
    // Get number of elements in array
986
8
    int numElem() const {
987
8
        const char* pch = payload;
988
8
        const char* fence = payload + size;
989
990
8
        unsigned int num = 0;
991
29
        while (pch < fence) {
992
21
            ++num;
993
21
            pch += ((const JsonbValue*)pch)->numPackedBytes();
994
21
        }
995
996
8
        assert(pch == fence);
997
998
8
        return num;
999
8
    }
1000
1001
66
    const_iterator begin() const { return const_iterator((pointer)payload); }
1002
1003
65
    const_iterator end() const { return const_iterator((pointer)(payload + size)); }
1004
};
1005
1006
12
inline const JsonbValue* JsonbDocument::createValue(const char* pb, size_t size) {
1007
12
    if (!pb || size < sizeof(JsonbHeader) + sizeof(JsonbValue)) {
1008
0
        return nullptr;
1009
0
    }
1010
1011
12
    auto* doc = (JsonbDocument*)pb;
1012
12
    if (doc->header_.ver_ != JSONB_VER) {
1013
0
        return nullptr;
1014
0
    }
1015
1016
12
    const auto* val = (const JsonbValue*)doc->payload_;
1017
12
    if (size != sizeof(JsonbHeader) + val->numPackedBytes()) {
1018
0
        return nullptr;
1019
0
    }
1020
1021
12
    return val;
1022
12
}
1023
1024
0
inline unsigned int JsonbDocument::numPackedBytes() const {
1025
0
    return ((const JsonbValue*)payload_)->numPackedBytes() + sizeof(header_);
1026
0
}
1027
1028
17.4k
inline unsigned int JsonbKeyValue::numPackedBytes() const {
1029
17.4k
    unsigned int ks = keyPackedBytes();
1030
17.4k
    const auto* val = (const JsonbValue*)(((char*)this) + ks);
1031
17.4k
    return ks + val->numPackedBytes();
1032
17.4k
}
1033
1034
// Poor man's "virtual" function JsonbValue::numPackedBytes
1035
71.3k
inline unsigned int JsonbValue::numPackedBytes() const {
1036
71.3k
    switch (type) {
1037
2.75k
    case JsonbType::T_Null:
1038
2.82k
    case JsonbType::T_True:
1039
2.87k
    case JsonbType::T_False: {
1040
2.87k
        return sizeof(type);
1041
2.82k
    }
1042
1043
1.66k
    case JsonbType::T_Int8: {
1044
1.66k
        return sizeof(type) + sizeof(int8_t);
1045
2.82k
    }
1046
122
    case JsonbType::T_Int16: {
1047
122
        return sizeof(type) + sizeof(int16_t);
1048
2.82k
    }
1049
3.49k
    case JsonbType::T_Int32: {
1050
3.49k
        return sizeof(type) + sizeof(int32_t);
1051
2.82k
    }
1052
21.5k
    case JsonbType::T_Int64: {
1053
21.5k
        return sizeof(type) + sizeof(int64_t);
1054
2.82k
    }
1055
10.5k
    case JsonbType::T_Double: {
1056
10.5k
        return sizeof(type) + sizeof(double);
1057
2.82k
    }
1058
26
    case JsonbType::T_Float: {
1059
26
        return sizeof(type) + sizeof(float);
1060
2.82k
    }
1061
14.1k
    case JsonbType::T_Int128: {
1062
14.1k
        return sizeof(type) + sizeof(int128_t);
1063
2.82k
    }
1064
10.7k
    case JsonbType::T_String:
1065
15.1k
    case JsonbType::T_Binary: {
1066
15.1k
        return unpack<JsonbBinaryVal>()->numPackedBytes();
1067
10.7k
    }
1068
1069
1.65k
    case JsonbType::T_Object:
1070
1.80k
    case JsonbType::T_Array: {
1071
1.80k
        return unpack<ContainerVal>()->numPackedBytes();
1072
1.65k
    }
1073
7
    case JsonbType::T_Decimal32: {
1074
7
        return JsonbDecimal32::numPackedBytes();
1075
1.65k
    }
1076
7
    case JsonbType::T_Decimal64: {
1077
7
        return JsonbDecimal64::numPackedBytes();
1078
1.65k
    }
1079
9
    case JsonbType::T_Decimal128: {
1080
9
        return JsonbDecimal128::numPackedBytes();
1081
1.65k
    }
1082
6
    case JsonbType::T_Decimal256: {
1083
6
        return JsonbDecimal256::numPackedBytes();
1084
1.65k
    }
1085
0
    case JsonbType::NUM_TYPES:
1086
0
        break;
1087
71.3k
    }
1088
1089
0
    throw Exception(ErrorCode::INTERNAL_ERROR, "Invalid JSONB value type: {}",
1090
0
                    static_cast<int32_t>(type));
1091
71.3k
}
1092
1093
6
inline int JsonbValue::numElements() const {
1094
6
    switch (type) {
1095
0
    case JsonbType::T_Int8:
1096
0
    case JsonbType::T_Int16:
1097
0
    case JsonbType::T_Int32:
1098
0
    case JsonbType::T_Int64:
1099
0
    case JsonbType::T_Double:
1100
0
    case JsonbType::T_Float:
1101
0
    case JsonbType::T_Int128:
1102
1
    case JsonbType::T_String:
1103
1
    case JsonbType::T_Binary:
1104
2
    case JsonbType::T_Null:
1105
2
    case JsonbType::T_True:
1106
2
    case JsonbType::T_False:
1107
2
    case JsonbType::T_Decimal32:
1108
2
    case JsonbType::T_Decimal64:
1109
2
    case JsonbType::T_Decimal128:
1110
2
    case JsonbType::T_Decimal256: {
1111
2
        return 1;
1112
2
    }
1113
0
    case JsonbType::T_Object: {
1114
0
        return unpack<ObjectVal>()->numElem();
1115
2
    }
1116
4
    case JsonbType::T_Array: {
1117
4
        return unpack<ArrayVal>()->numElem();
1118
2
    }
1119
0
    case JsonbType::NUM_TYPES:
1120
0
        break;
1121
6
    }
1122
0
    throw Exception(ErrorCode::INTERNAL_ERROR, "Invalid JSONB value type: {}",
1123
0
                    static_cast<int32_t>(type));
1124
6
}
1125
1126
3
inline bool JsonbValue::contains(const JsonbValue* rhs) const {
1127
3
    switch (type) {
1128
1
    case JsonbType::T_Int8:
1129
1
    case JsonbType::T_Int16:
1130
1
    case JsonbType::T_Int32:
1131
1
    case JsonbType::T_Int64:
1132
1
    case JsonbType::T_Int128: {
1133
1
        return rhs->isInt() && this->int_val() == rhs->int_val();
1134
1
    }
1135
0
    case JsonbType::T_Double:
1136
0
    case JsonbType::T_Float: {
1137
0
        if (!rhs->isDouble() && !rhs->isFloat()) {
1138
0
            return false;
1139
0
        }
1140
0
        double left = isDouble() ? unpack<JsonbDoubleVal>()->val() : unpack<JsonbFloatVal>()->val();
1141
0
        double right = rhs->isDouble() ? rhs->unpack<JsonbDoubleVal>()->val()
1142
0
                                       : rhs->unpack<JsonbFloatVal>()->val();
1143
0
        return left == right;
1144
0
    }
1145
1
    case JsonbType::T_String:
1146
1
    case JsonbType::T_Binary: {
1147
1
        if (rhs->isString() || rhs->isBinary()) {
1148
1
            const auto* str_value1 = unpack<JsonbStringVal>();
1149
1
            const auto* str_value2 = rhs->unpack<JsonbStringVal>();
1150
1
            return str_value1->length() == str_value2->length() &&
1151
1
                   std::memcmp(str_value1->getBlob(), str_value2->getBlob(),
1152
1
                               str_value1->length()) == 0;
1153
1
        }
1154
0
        return false;
1155
1
    }
1156
1
    case JsonbType::T_Array: {
1157
1
        int lhs_num = unpack<ArrayVal>()->numElem();
1158
1
        if (rhs->isArray()) {
1159
0
            int rhs_num = rhs->unpack<ArrayVal>()->numElem();
1160
0
            if (rhs_num > lhs_num) {
1161
0
                return false;
1162
0
            }
1163
0
            int contains_num = 0;
1164
0
            for (int i = 0; i < lhs_num; ++i) {
1165
0
                for (int j = 0; j < rhs_num; ++j) {
1166
0
                    if (unpack<ArrayVal>()->get(i)->contains(rhs->unpack<ArrayVal>()->get(j))) {
1167
0
                        contains_num++;
1168
0
                        break;
1169
0
                    }
1170
0
                }
1171
0
            }
1172
0
            return contains_num == rhs_num;
1173
0
        }
1174
1
        for (int i = 0; i < lhs_num; ++i) {
1175
1
            if (unpack<ArrayVal>()->get(i)->contains(rhs)) {
1176
1
                return true;
1177
1
            }
1178
1
        }
1179
0
        return false;
1180
1
    }
1181
0
    case JsonbType::T_Object: {
1182
0
        if (rhs->isObject()) {
1183
0
            const auto* obj_value1 = unpack<ObjectVal>();
1184
0
            const auto* obj_value2 = rhs->unpack<ObjectVal>();
1185
0
            for (auto it = obj_value2->begin(); it != obj_value2->end(); ++it) {
1186
0
                const JsonbValue* value = obj_value1->find(it->getKeyStr(), it->klen());
1187
0
                if (value == nullptr || !value->contains(it->value())) {
1188
0
                    return false;
1189
0
                }
1190
0
            }
1191
0
            return true;
1192
0
        }
1193
0
        return false;
1194
0
    }
1195
0
    case JsonbType::T_Null: {
1196
0
        return rhs->isNull();
1197
0
    }
1198
0
    case JsonbType::T_True: {
1199
0
        return rhs->isTrue();
1200
0
    }
1201
0
    case JsonbType::T_False: {
1202
0
        return rhs->isFalse();
1203
0
    }
1204
0
    case JsonbType::T_Decimal32: {
1205
0
        if (rhs->isDecimal32()) {
1206
0
            return unpack<JsonbDecimal32>()->val() == rhs->unpack<JsonbDecimal32>()->val() &&
1207
0
                   unpack<JsonbDecimal32>()->precision ==
1208
0
                           rhs->unpack<JsonbDecimal32>()->precision &&
1209
0
                   unpack<JsonbDecimal32>()->scale == rhs->unpack<JsonbDecimal32>()->scale;
1210
0
        }
1211
0
        return false;
1212
0
    }
1213
0
    case JsonbType::T_Decimal64: {
1214
0
        if (rhs->isDecimal64()) {
1215
0
            return unpack<JsonbDecimal64>()->val() == rhs->unpack<JsonbDecimal64>()->val() &&
1216
0
                   unpack<JsonbDecimal64>()->precision ==
1217
0
                           rhs->unpack<JsonbDecimal64>()->precision &&
1218
0
                   unpack<JsonbDecimal64>()->scale == rhs->unpack<JsonbDecimal64>()->scale;
1219
0
        }
1220
0
        return false;
1221
0
    }
1222
0
    case JsonbType::T_Decimal128: {
1223
0
        if (rhs->isDecimal128()) {
1224
0
            return unpack<JsonbDecimal128>()->val() == rhs->unpack<JsonbDecimal128>()->val() &&
1225
0
                   unpack<JsonbDecimal128>()->precision ==
1226
0
                           rhs->unpack<JsonbDecimal128>()->precision &&
1227
0
                   unpack<JsonbDecimal128>()->scale == rhs->unpack<JsonbDecimal128>()->scale;
1228
0
        }
1229
0
        return false;
1230
0
    }
1231
0
    case JsonbType::T_Decimal256: {
1232
0
        if (rhs->isDecimal256()) {
1233
0
            return unpack<JsonbDecimal256>()->val() == rhs->unpack<JsonbDecimal256>()->val() &&
1234
0
                   unpack<JsonbDecimal256>()->precision ==
1235
0
                           rhs->unpack<JsonbDecimal256>()->precision &&
1236
0
                   unpack<JsonbDecimal256>()->scale == rhs->unpack<JsonbDecimal256>()->scale;
1237
0
        }
1238
0
        return false;
1239
0
    }
1240
0
    case JsonbType::NUM_TYPES:
1241
0
        break;
1242
3
    }
1243
1244
0
    throw Exception(ErrorCode::INTERNAL_ERROR, "Invalid JSONB value type: {}",
1245
0
                    static_cast<int32_t>(type));
1246
3
}
1247
1248
96
inline bool JsonbPath::seek(const char* key_path, size_t kp_len) {
1249
96
    while (kp_len > 0 && std::isspace(key_path[kp_len - 1])) {
1250
0
        --kp_len;
1251
0
    }
1252
1253
    //path invalid
1254
96
    if (!key_path || kp_len == 0) {
1255
0
        return false;
1256
0
    }
1257
96
    Stream stream(key_path, kp_len);
1258
96
    stream.skip_whitespace();
1259
96
    if (stream.exhausted() || stream.read() != SCOPE) {
1260
        //path invalid
1261
0
        return false;
1262
0
    }
1263
1264
186
    while (!stream.exhausted()) {
1265
90
        stream.skip_whitespace();
1266
90
        stream.clear_leg_ptr();
1267
90
        stream.clear_leg_len();
1268
1269
90
        if (!JsonbPath::parsePath(&stream, this)) {
1270
            //path invalid
1271
0
            return false;
1272
0
        }
1273
90
    }
1274
96
    return true;
1275
96
}
1276
1277
90
inline bool JsonbPath::parsePath(Stream* stream, JsonbPath* path) {
1278
    // $[0]
1279
90
    if (stream->peek() == BEGIN_ARRAY) {
1280
58
        return parse_array(stream, path);
1281
58
    }
1282
    // $.a or $.[0]
1283
32
    else if (stream->peek() == BEGIN_MEMBER) {
1284
        // advance past the .
1285
32
        stream->skip(1);
1286
1287
32
        if (stream->exhausted()) {
1288
0
            return false;
1289
0
        }
1290
1291
        // $.[0]
1292
32
        if (stream->peek() == BEGIN_ARRAY) {
1293
0
            return parse_array(stream, path);
1294
0
        }
1295
        // $.a
1296
32
        else {
1297
32
            return parse_member(stream, path);
1298
32
        }
1299
32
    } else if (stream->peek() == WILDCARD) {
1300
0
        stream->skip(1);
1301
0
        if (stream->exhausted()) {
1302
0
            return false;
1303
0
        }
1304
1305
        // $**
1306
0
        if (stream->peek() == WILDCARD) {
1307
0
            path->_is_supper_wildcard = true;
1308
0
        }
1309
1310
0
        stream->skip(1);
1311
0
        if (stream->exhausted()) {
1312
0
            return false;
1313
0
        }
1314
1315
0
        if (stream->peek() == BEGIN_ARRAY) {
1316
0
            return parse_array(stream, path);
1317
0
        } else if (stream->peek() == BEGIN_MEMBER) {
1318
            // advance past the .
1319
0
            stream->skip(1);
1320
1321
0
            if (stream->exhausted()) {
1322
0
                return false;
1323
0
            }
1324
1325
            // $.[0]
1326
0
            if (stream->peek() == BEGIN_ARRAY) {
1327
0
                return parse_array(stream, path);
1328
0
            }
1329
            // $.a
1330
0
            else {
1331
0
                return parse_member(stream, path);
1332
0
            }
1333
0
        }
1334
0
        return false;
1335
0
    } else {
1336
0
        return false; //invalid json path
1337
0
    }
1338
90
}
1339
1340
58
inline bool JsonbPath::parse_array(Stream* stream, JsonbPath* path) {
1341
58
    assert(stream->peek() == BEGIN_ARRAY);
1342
58
    stream->skip(1);
1343
58
    if (stream->exhausted()) {
1344
0
        return false;
1345
0
    }
1346
1347
58
    if (stream->peek() == WILDCARD) {
1348
        // Called by function_jsonb.cpp, the variables passed in originate from a mutable block;
1349
        // using const_cast is acceptable.
1350
0
        stream->set_leg_ptr(const_cast<char*>(stream->position()));
1351
0
        stream->add_leg_len();
1352
0
        stream->skip(1);
1353
0
        if (stream->exhausted()) {
1354
0
            return false;
1355
0
        }
1356
1357
0
        if (stream->peek() == END_ARRAY) {
1358
0
            std::unique_ptr<leg_info> leg(
1359
0
                    new leg_info(stream->get_leg_ptr(), stream->get_leg_len(), 0, ARRAY_CODE));
1360
0
            path->add_leg_to_leg_vector(std::move(leg));
1361
0
            stream->skip(1);
1362
0
            path->_is_wildcard = true;
1363
0
            return true;
1364
0
        } else {
1365
0
            return false;
1366
0
        }
1367
0
    }
1368
1369
    // Called by function_jsonb.cpp, the variables passed in originate from a mutable block;
1370
    // using const_cast is acceptable.
1371
58
    stream->set_leg_ptr(const_cast<char*>(stream->position()));
1372
1373
116
    for (; !stream->exhausted() && stream->peek() != END_ARRAY; stream->advance()) {
1374
58
        stream->add_leg_len();
1375
58
    }
1376
1377
58
    if (stream->exhausted() || stream->peek() != END_ARRAY) {
1378
0
        return false;
1379
58
    } else {
1380
58
        stream->skip(1);
1381
58
    }
1382
1383
    //parse array index to int
1384
1385
58
    std::string_view idx_string(stream->get_leg_ptr(), stream->get_leg_len());
1386
58
    int index = 0;
1387
1388
58
    if (stream->get_leg_len() >= 4 &&
1389
58
        std::equal(LAST, LAST + 4, stream->get_leg_ptr(),
1390
0
                   [](char c1, char c2) { return std::tolower(c1) == std::tolower(c2); })) {
1391
0
        auto pos = idx_string.find(MINUS);
1392
1393
0
        if (pos != std::string::npos) {
1394
0
            for (size_t i = 4; i < pos; ++i) {
1395
0
                if (std::isspace(idx_string[i])) {
1396
0
                    continue;
1397
0
                } else {
1398
                    // leading zeroes are not allowed
1399
0
                    LOG(WARNING) << "Non-space char in idx_string: '" << idx_string << "'";
1400
0
                    return false;
1401
0
                }
1402
0
            }
1403
0
            idx_string = idx_string.substr(pos + 1);
1404
0
            idx_string = trim(idx_string);
1405
1406
0
            auto result = std::from_chars(idx_string.data(), idx_string.data() + idx_string.size(),
1407
0
                                          index);
1408
0
            if (result.ec != std::errc()) {
1409
0
                LOG(WARNING) << "Invalid index in JSON path: '" << idx_string << "'";
1410
0
                return false;
1411
0
            }
1412
1413
0
        } else if (stream->get_leg_len() > 4) {
1414
0
            return false;
1415
0
        }
1416
1417
0
        std::unique_ptr<leg_info> leg(new leg_info(nullptr, 0, -index - 1, ARRAY_CODE));
1418
0
        path->add_leg_to_leg_vector(std::move(leg));
1419
1420
0
        return true;
1421
0
    }
1422
1423
58
    auto result = std::from_chars(idx_string.data(), idx_string.data() + idx_string.size(), index);
1424
1425
58
    if (result.ec != std::errc()) {
1426
0
        return false;
1427
0
    }
1428
1429
58
    std::unique_ptr<leg_info> leg(new leg_info(nullptr, 0, index, ARRAY_CODE));
1430
58
    path->add_leg_to_leg_vector(std::move(leg));
1431
1432
58
    return true;
1433
58
}
1434
1435
32
inline bool JsonbPath::parse_member(Stream* stream, JsonbPath* path) {
1436
32
    if (stream->exhausted()) {
1437
0
        return false;
1438
0
    }
1439
1440
32
    if (stream->peek() == WILDCARD) {
1441
        // Called by function_jsonb.cpp, the variables passed in originate from a mutable block;
1442
        // using const_cast is acceptable.
1443
0
        stream->set_leg_ptr(const_cast<char*>(stream->position()));
1444
0
        stream->add_leg_len();
1445
0
        stream->skip(1);
1446
0
        std::unique_ptr<leg_info> leg(
1447
0
                new leg_info(stream->get_leg_ptr(), stream->get_leg_len(), 0, MEMBER_CODE));
1448
0
        path->add_leg_to_leg_vector(std::move(leg));
1449
0
        path->_is_wildcard = true;
1450
0
        return true;
1451
0
    }
1452
1453
    // Called by function_jsonb.cpp, the variables passed in originate from a mutable block;
1454
    // using const_cast is acceptable.
1455
32
    stream->set_leg_ptr(const_cast<char*>(stream->position()));
1456
1457
32
    const char* left_quotation_marks = nullptr;
1458
32
    const char* right_quotation_marks = nullptr;
1459
1460
96
    for (; !stream->exhausted(); stream->advance()) {
1461
        // Only accept space characters quoted by double quotes.
1462
64
        if (std::isspace(stream->peek()) && left_quotation_marks == nullptr) {
1463
0
            return false;
1464
64
        } else if (stream->peek() == ESCAPE) {
1465
0
            stream->add_leg_len();
1466
0
            stream->skip(1);
1467
0
            stream->add_leg_len();
1468
0
            stream->set_has_escapes(true);
1469
0
            if (stream->exhausted()) {
1470
0
                return false;
1471
0
            }
1472
0
            continue;
1473
64
        } else if (stream->peek() == DOUBLE_QUOTE) {
1474
0
            if (left_quotation_marks == nullptr) {
1475
0
                left_quotation_marks = stream->position();
1476
                // Called by function_jsonb.cpp, the variables passed in originate from a mutable block;
1477
                // using const_cast is acceptable.
1478
0
                stream->set_leg_ptr(const_cast<char*>(++left_quotation_marks));
1479
0
                continue;
1480
0
            } else {
1481
0
                right_quotation_marks = stream->position();
1482
0
                stream->skip(1);
1483
0
                break;
1484
0
            }
1485
64
        } else if (stream->peek() == BEGIN_MEMBER || stream->peek() == BEGIN_ARRAY) {
1486
0
            if (left_quotation_marks == nullptr) {
1487
0
                break;
1488
0
            }
1489
0
        }
1490
1491
64
        stream->add_leg_len();
1492
64
    }
1493
1494
32
    if ((left_quotation_marks != nullptr && right_quotation_marks == nullptr) ||
1495
32
        stream->get_leg_ptr() == nullptr || stream->get_leg_len() == 0) {
1496
0
        return false; //invalid json path
1497
0
    }
1498
1499
32
    if (stream->get_has_escapes()) {
1500
0
        stream->remove_escapes();
1501
0
    }
1502
1503
32
    std::unique_ptr<leg_info> leg(
1504
32
            new leg_info(stream->get_leg_ptr(), stream->get_leg_len(), 0, MEMBER_CODE));
1505
32
    path->add_leg_to_leg_vector(std::move(leg));
1506
1507
32
    return true;
1508
32
}
1509
1510
static_assert(is_pod_v<JsonbDocument>, "JsonbDocument must be standard layout and trivial");
1511
static_assert(is_pod_v<JsonbValue>, "JsonbValue must be standard layout and trivial");
1512
static_assert(is_pod_v<JsonbDecimal32>, "JsonbDecimal32 must be standard layout and trivial");
1513
static_assert(is_pod_v<JsonbDecimal64>, "JsonbDecimal64 must be standard layout and trivial");
1514
static_assert(is_pod_v<JsonbDecimal128>, "JsonbDecimal128 must be standard layout and trivial");
1515
static_assert(is_pod_v<JsonbDecimal256>, "JsonbDecimal256 must be standard layout and trivial");
1516
static_assert(is_pod_v<JsonbInt8Val>, "JsonbInt8Val must be standard layout and trivial");
1517
static_assert(is_pod_v<JsonbInt32Val>, "JsonbInt32Val must be standard layout and trivial");
1518
static_assert(is_pod_v<JsonbInt64Val>, "JsonbInt64Val must be standard layout and trivial");
1519
static_assert(is_pod_v<JsonbInt128Val>, "JsonbInt128Val must be standard layout and trivial");
1520
static_assert(is_pod_v<JsonbDoubleVal>, "JsonbDoubleVal must be standard layout and trivial");
1521
static_assert(is_pod_v<JsonbFloatVal>, "JsonbFloatVal must be standard layout and trivial");
1522
static_assert(is_pod_v<JsonbBinaryVal>, "JsonbBinaryVal must be standard layout and trivial");
1523
static_assert(is_pod_v<ContainerVal>, "ContainerVal must be standard layout and trivial");
1524
1525
#define ASSERT_DECIMAL_LAYOUT(type)                \
1526
    static_assert(offsetof(type, precision) == 0); \
1527
    static_assert(offsetof(type, scale) == 4);     \
1528
    static_assert(offsetof(type, value) == 8);
1529
1530
ASSERT_DECIMAL_LAYOUT(JsonbDecimal32)
1531
ASSERT_DECIMAL_LAYOUT(JsonbDecimal64)
1532
ASSERT_DECIMAL_LAYOUT(JsonbDecimal128)
1533
ASSERT_DECIMAL_LAYOUT(JsonbDecimal256)
1534
1535
#define ASSERT_NUMERIC_LAYOUT(type) static_assert(offsetof(type, num) == 0);
1536
1537
ASSERT_NUMERIC_LAYOUT(JsonbInt8Val)
1538
ASSERT_NUMERIC_LAYOUT(JsonbInt32Val)
1539
ASSERT_NUMERIC_LAYOUT(JsonbInt64Val)
1540
ASSERT_NUMERIC_LAYOUT(JsonbInt128Val)
1541
ASSERT_NUMERIC_LAYOUT(JsonbDoubleVal)
1542
1543
static_assert(offsetof(JsonbBinaryVal, size) == 0);
1544
static_assert(offsetof(JsonbBinaryVal, payload) == 4);
1545
1546
static_assert(offsetof(ContainerVal, size) == 0);
1547
static_assert(offsetof(ContainerVal, payload) == 4);
1548
1549
#pragma pack(pop)
1550
#if defined(__clang__)
1551
#pragma clang diagnostic pop
1552
#endif
1553
} // namespace doris
1554
1555
#endif // JSONB_JSONBDOCUMENT_H