Coverage Report

Created: 2025-10-13 20:49

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