Debian Codegraph @

lib/json.cpp

raw symbols SCIP
1 /*
2 Copyright (C) 2025-2026 Sutou Kouhei <[email protected]>
3
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 This library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with this library; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18
19 #include "grn_ctx.h"
20
21 #ifdef GRN_WITH_SIMDJSON
22 # include <cmath>
23 # include <limits>
24 # include <optional>
25 # include <queue>
26 # include <string>
27 # include <variant>
28
29 # include <simdjson.h>
30 #endif
31
32 #ifdef GRN_WITH_JSONCONS
33 # include <jsoncons/json.hpp>
34 # include <jsoncons_ext/jsonpath/jsonpath.hpp>
35 #endif
36
37 #include <cstring>
38 #include <memory>
39 #include <stack>
40 #include <utility>
41 #include <vector>
42
43 // See tools/parsed-json.rb for format details.
44
45 namespace {
46 enum class Flag {
47 kObjectPosition8 = 0b00000000'00000000'00000001,
48 kObjectPosition16 = 0b00000000'00000000'00000010,
49 kObjectPosition32 = 0b00000000'00000000'00000100,
50 kObjectKey = 0b00000000'00000000'00001000,
51 kObjectKeyPosition8 = 0b00000000'00000000'00010000,
52 kObjectKeyPosition16 = 0b00000000'00000000'00100000,
53 kObjectKeyPosition32 = 0b00000000'00000000'01000000,
54 kObjectValueTag16 = 0b00000000'00000000'10000000,
55 kObjectValueTag32 = 0b00000000'00000001'00000000,
56 kArrayPosition8 = 0b00000000'00000010'00000000,
57 kArrayPosition16 = 0b00000000'00000100'00000000,
58 kArrayPosition32 = 0b00000000'00001000'00000000,
59 kArrayTag16 = 0b00000000'00010000'00000000,
60 kArrayTag32 = 0b00000000'00100000'00000000,
61 kStringValue = 0b00000000'01000000'00000000,
62 kStringPosition8 = 0b00000000'10000000'00000000,
63 kStringPosition16 = 0b00000001'00000000'00000000,
64 kStringPosition32 = 0b00000010'00000000'00000000,
65 kInt16 = 0b00000100'00000000'00000000,
66 kInt32 = 0b00001000'00000000'00000000,
67 kInt64 = 0b00010000'00000000'00000000,
68 kDouble = 0b00100000'00000000'00000000,
69 kOffset32 = 0b01000000'00000000'00000000,
70 };
71
72 enum class Type {
73 kObject = 0,
74 kArray = 1,
75 kString = 2,
76 kInteger = 3,
77 kFloat = 4,
78 kConstant = 5,
79 };
80
81 namespace metadata {
82 enum class Float {
83 kPositiveZero = 0,
84 kNegativeZero = 1,
85 };
86
87 enum class Constant {
88 kTrue = 0,
89 kFalse = 1,
90 kNull = 2,
91 };
92 } // namespace metadata
93
94 struct Tag {
95 Type type;
96 bool is_embedded;
97 uint8_t metadata;
98 uint32_t data;
99 };
100
101 static const size_t kRootTagSize = sizeof(uint8_t);
102
103 #ifdef GRN_WITH_SIMDJSON
104 struct TagWriter {
105 virtual void
106 write(Type type, bool is_embedded, uint8_t metadata, uint32_t data) = 0;
107
108 protected:
109 uint32_t
110 pack_tag(Type type, bool is_embedded, uint8_t metadata, uint32_t data)
111 {
112 uint32_t tag = static_cast<uint32_t>(type);
113 if (is_embedded) {
114 tag |= (1 << 3);
115 }
116 tag |= (metadata << 4);
117 tag |= (data << 8);
118 return tag;
119 }
120 };
121
122 struct ContainerTagsWriter : public TagWriter {
123 grn_ctx *ctx_;
124 grn_obj buffer;
125 uint32_t size16;
126 uint32_t size32;
127
128 ContainerTagsWriter(grn_ctx *ctx)
129 : ctx_(ctx),
130 buffer(),
131 size16(0),
132 size32(0)
133 {
134 GRN_BINARY_INIT(&buffer, 0);
135 }
136
137 ~ContainerTagsWriter() { GRN_OBJ_FIN(ctx_, &buffer); }
138
139 void
140 write(Type type, bool is_embedded, uint8_t metadata, uint32_t data) override
141 {
142 auto tag = pack_tag(type, is_embedded, metadata, data);
143 if (size32 > 0 || data > 255) {
144 GRN_UINT32_PUT(ctx_, &buffer, tag);
145 size32 += sizeof(uint32_t);
146 } else {
147 GRN_UINT16_PUT(ctx_, &buffer, tag);
148 size16 += sizeof(uint16_t);
149 }
150 }
151 };
152
153 struct RootTagWriter : public TagWriter {
154 grn_ctx *ctx_;
155 grn_obj *buffer_;
156
157 RootTagWriter(grn_ctx *ctx, grn_obj *buffer) : ctx_(ctx), buffer_(buffer) {}
158
159 ~RootTagWriter() = default;
160
161 void
162 write(Type type, bool is_embedded, uint8_t metadata, uint32_t data) override
163 {
164 assert(data == 0); // Root tag's data must be zero
165 auto tag = pack_tag(type, is_embedded, metadata, 0);
166 GRN_UINT8_PUT(ctx_, buffer_, tag);
167 }
168 };
169
170 struct PositionsWriter {
171 grn_ctx *ctx_;
172 grn_obj buffer;
173 uint32_t size8;
174 uint32_t size16;
175 uint32_t size32;
176 uint32_t index_;
177 uint32_t last_position_;
178
179 PositionsWriter(grn_ctx *ctx)
180 : ctx_(ctx),
181 buffer(),
182 size8(0),
183 size16(0),
184 size32(0),
185 index_(0),
186 last_position_(0)
187 {
188 GRN_BINARY_INIT(&buffer, 0);
189 }
190
191 ~PositionsWriter() { GRN_OBJ_FIN(ctx_, &buffer); }
192
193 uint32_t
194 write(uint32_t size)
195 {
196 auto index = index_;
197 index_++;
198 auto position = last_position_ + size;
199 if (size32 > 0 || position > 65535) {
200 GRN_UINT32_PUT(ctx_, &buffer, position);
201 size32 += sizeof(uint32_t);
202 } else if (size16 > 0 || position > 255) {
203 GRN_UINT16_PUT(ctx_, &buffer, position);
204 size16 += sizeof(uint16_t);
205 } else {
206 GRN_UINT8_PUT(ctx_, &buffer, position);
207 size8 += sizeof(uint8_t);
208 }
209 last_position_ = position;
210 return index;
211 }
212 };
213
214 struct JSONValue {
215 grn_json_value_type type;
216 using Data = std::variant<int64_t,
217 double,
218 std::string_view,
219 std::string,
220 std::vector<JSONValue>>;
221 Data data;
222 };
223
224 class JSONParser {
225 public:
226 JSONParser(grn_ctx *ctx, grn_obj *input, grn_obj *output)
227 : ctx_(ctx),
228 input_(input),
229 output_(output),
230 root_tag_writer_(ctx_, output),
231 object_positions_writer_(ctx_),
232 object_keys_(),
233 object_key_positions_writer_(ctx_),
234 object_value_tags_writer_(ctx_),
235 array_positions_writer_(ctx_),
236 array_tags_writer_(ctx_),
237 string_values_(),
238 string_positions_writer_(ctx_),
239 int16_values_(),
240 int32_values_(),
241 int64_values_(),
242 double_values_()
243 {
244 GRN_TEXT_INIT(&object_keys_, 0);
245 GRN_TEXT_INIT(&string_values_, 0);
246 GRN_INT16_INIT(&int16_values_, 0);
247 GRN_INT32_INIT(&int32_values_, 0);
248 GRN_INT64_INIT(&int64_values_, 0);
249 GRN_FLOAT_INIT(&double_values_, 0);
250 }
251
252 ~JSONParser()
253 {
254 GRN_OBJ_FIN(ctx_, &object_keys_);
255 GRN_OBJ_FIN(ctx_, &string_values_);
256 GRN_OBJ_FIN(ctx_, &int16_values_);
257 GRN_OBJ_FIN(ctx_, &int32_values_);
258 GRN_OBJ_FIN(ctx_, &int64_values_);
259 GRN_OBJ_FIN(ctx_, &double_values_);
260 }
261
262 void
263 parse()
264 {
265 const char *tag = "[json-parser][parse]";
266 auto ctx = ctx_;
267
268 auto rc = grn_bulk_reserve(ctx_, input_, simdjson::SIMDJSON_PADDING);
269 if (rc != GRN_SUCCESS) {
270 return;
271 }
272
273 simdjson::ondemand::parser parser;
274 simdjson::ondemand::document document;
275 auto error_code = parser
276 .iterate(GRN_TEXT_VALUE(input_),
277 GRN_TEXT_LEN(input_),
278 GRN_BULK_WSIZE(input_))
279 .get(document);
280 if (error_code != simdjson::SUCCESS) {
281 ERR(GRN_INVALID_ARGUMENT,
282 "%s failed to parse: %s",
283 tag,
284 simdjson::error_message(error_code));
285 return;
286 }
287
288 parse_document(document);
289 }
290
291 private:
292 using json_type = simdjson::ondemand::json_type;
293
294 grn_ctx *ctx_;
295 grn_obj *input_;
296 grn_obj *output_;
297 RootTagWriter root_tag_writer_;
298 PositionsWriter object_positions_writer_;
299 grn_obj object_keys_;
300 PositionsWriter object_key_positions_writer_;
301 ContainerTagsWriter object_value_tags_writer_;
302 PositionsWriter array_positions_writer_;
303 ContainerTagsWriter array_tags_writer_;
304 grn_obj string_values_;
305 PositionsWriter string_positions_writer_;
306 grn_obj int16_values_;
307 grn_obj int32_values_;
308 grn_obj int64_values_;
309 grn_obj double_values_;
310
311 bool
312 is_root(TagWriter *tag_writer)
313 {
314 return tag_writer == &root_tag_writer_;
315 }
316
317 void
318 append_tags_buffer_offsets(uint32_t &flags,
319 uint32_t &offset,
320 std::vector<uint32_t> &buffer_offsets,
321 ContainerTagsWriter *writer,
322 Flag flag16,
323 Flag flag32)
324 {
325 if (writer->size16 > 0) {
326 flags |= static_cast<uint32_t>(flag16);
327 buffer_offsets.push_back(offset);
328 offset += writer->size16;
329 }
330 if (writer->size32 > 0) {
331 flags |= static_cast<uint32_t>(flag32);
332 buffer_offsets.push_back(offset);
333 offset += writer->size32;
334 }
335 }
336
337 void
338 append_positions_buffer_offsets(uint32_t &flags,
339 uint32_t &offset,
340 std::vector<uint32_t> &buffer_offsets,
341 PositionsWriter *writer,
342 Flag flag8,
343 Flag flag16,
344 Flag flag32)
345 {
346 if (writer->size8 > 0) {
347 flags |= static_cast<uint32_t>(flag8);
348 buffer_offsets.push_back(offset);
349 offset += writer->size8;
350 }
351 if (writer->size16 > 0) {
352 flags |= static_cast<uint32_t>(flag16);
353 buffer_offsets.push_back(offset);
354 offset += writer->size16;
355 }
356 if (writer->size32 > 0) {
357 flags |= static_cast<uint32_t>(flag32);
358 buffer_offsets.push_back(offset);
359 offset += writer->size32;
360 }
361 }
362
363 void
364 write_footer()
365 {
366 uint32_t flags = 0;
367 uint32_t offset = sizeof(uint32_t);
368 std::vector<grn_obj *> outputs;
369 std::vector<uint32_t> buffer_offsets;
370
371 if (GRN_TEXT_LEN(&(object_positions_writer_.buffer)) > 0) {
372 outputs.push_back(&(object_positions_writer_.buffer));
373 append_positions_buffer_offsets(flags,
374 offset,
375 buffer_offsets,
376 &object_positions_writer_,
377 Flag::kObjectPosition8,
378 Flag::kObjectPosition16,
379 Flag::kObjectPosition32);
380 }
381
382 if (GRN_TEXT_LEN(&object_keys_) > 0) {
383 outputs.push_back(&object_keys_);
384 flags |= static_cast<uint32_t>(Flag::kObjectKey);
385 buffer_offsets.push_back(offset);
386 offset += GRN_TEXT_LEN(&object_keys_);
387 }
388 if (GRN_TEXT_LEN(&(object_key_positions_writer_.buffer)) > 0) {
389 outputs.push_back(&(object_key_positions_writer_.buffer));
390 append_positions_buffer_offsets(flags,
391 offset,
392 buffer_offsets,
393 &object_key_positions_writer_,
394 Flag::kObjectKeyPosition8,
395 Flag::kObjectKeyPosition16,
396 Flag::kObjectKeyPosition32);
397 }
398
399 if (GRN_TEXT_LEN(&(object_value_tags_writer_.buffer)) > 0) {
400 outputs.push_back(&(object_value_tags_writer_.buffer));
401 append_tags_buffer_offsets(flags,
402 offset,
403 buffer_offsets,
404 &object_value_tags_writer_,
405 Flag::kObjectValueTag16,
406 Flag::kObjectValueTag32);
407 }
408
409 if (GRN_TEXT_LEN(&(array_positions_writer_.buffer)) > 0) {
410 outputs.push_back(&(array_positions_writer_.buffer));
411 append_positions_buffer_offsets(flags,
412 offset,
413 buffer_offsets,
414 &array_positions_writer_,
415 Flag::kArrayPosition8,
416 Flag::kArrayPosition16,
417 Flag::kArrayPosition32);
418 }
419 if (GRN_TEXT_LEN(&(array_tags_writer_.buffer)) > 0) {
420 outputs.push_back(&(array_tags_writer_.buffer));
421 append_tags_buffer_offsets(flags,
422 offset,
423 buffer_offsets,
424 &array_tags_writer_,
425 Flag::kArrayTag16,
426 Flag::kArrayTag32);
427 }
428
429 if (GRN_TEXT_LEN(&string_values_) > 0) {
430 outputs.push_back(&string_values_);
431 flags |= static_cast<uint32_t>(Flag::kStringValue);
432 buffer_offsets.push_back(offset);
433 offset += GRN_TEXT_LEN(&string_values_);
434 }
435 if (GRN_TEXT_LEN(&(string_positions_writer_.buffer)) > 0) {
436 outputs.push_back(&(string_positions_writer_.buffer));
437 append_positions_buffer_offsets(flags,
438 offset,
439 buffer_offsets,
440 &string_positions_writer_,
441 Flag::kStringPosition8,
442 Flag::kStringPosition16,
443 Flag::kStringPosition32);
444 }
445
446 if (GRN_TEXT_LEN(&int16_values_) > 0) {
447 outputs.push_back(&int16_values_);
448 flags |= static_cast<uint32_t>(Flag::kInt16);
449 buffer_offsets.push_back(offset);
450 offset += GRN_TEXT_LEN(&int16_values_);
451 }
452
453 if (GRN_TEXT_LEN(&int32_values_) > 0) {
454 outputs.push_back(&int32_values_);
455 flags |= static_cast<uint32_t>(Flag::kInt32);
456 buffer_offsets.push_back(offset);
457 offset += GRN_TEXT_LEN(&int32_values_);
458 }
459
460 if (GRN_TEXT_LEN(&int64_values_) > 0) {
461 outputs.push_back(&int64_values_);
462 flags |= static_cast<uint32_t>(Flag::kInt64);
463 buffer_offsets.push_back(offset);
464 offset += GRN_TEXT_LEN(&int64_values_);
465 }
466
467 if (GRN_TEXT_LEN(&double_values_) > 0) {
468 outputs.push_back(&double_values_);
469 flags |= static_cast<uint32_t>(Flag::kDouble);
470 buffer_offsets.push_back(offset);
471 offset += GRN_TEXT_LEN(&double_values_);
472 }
473
474 if (!buffer_offsets.empty() &&
475 buffer_offsets.back() > std::numeric_limits<uint16_t>::max()) {
476 flags |= static_cast<uint32_t>(Flag::kOffset32);
477 }
478
479 GRN_UINT8_PUT(ctx_, output_, (flags >> 16));
480 GRN_UINT8_PUT(ctx_, output_, ((flags >> 8) & 0xff));
481 GRN_UINT8_PUT(ctx_, output_, (flags & 0xff));
482 for (auto output : outputs) {
483 GRN_TEXT_PUT(ctx_,
484 output_,
485 GRN_TEXT_VALUE(output),
486 GRN_TEXT_LEN(output));
487 }
488 if (flags & static_cast<uint32_t>(Flag::kOffset32)) {
489 for (auto offset : buffer_offsets) {
490 GRN_UINT32_PUT(ctx_, output_, offset);
491 }
492 } else {
493 for (auto offset : buffer_offsets) {
494 GRN_UINT16_PUT(ctx_, output_, offset);
495 }
496 }
497 }
498
499 bool
500 parse_document(simdjson::ondemand::document &document)
501 {
502 const char *tag = "[json-parser][parse][document]";
503 auto ctx = ctx_;
504
505 json_type type;
506 auto error_code = document.type().get(type);
507 if (error_code != simdjson::SUCCESS) {
508 ERR(GRN_INVALID_ARGUMENT,
509 "%s failed to get root value type: %s",
510 tag,
511 simdjson::error_message(error_code));
512 return true;
513 }
514 switch (type) {
515 case json_type::object:
516 case json_type::array:
517 {
518 simdjson::ondemand::value value;
519 error_code = document.get_value().get(value);
520 if (error_code != simdjson::SUCCESS) {
521 ERR(GRN_INVALID_ARGUMENT,
522 "%s failed to get root value: %s",
523 tag,
524 simdjson::error_message(error_code));
525 return false;
526 }
527 auto container_value = extract_container(value);
528 if (!container_value) {
529 return false;
530 }
531 write_container(&root_tag_writer_, *container_value);
532 write_footer();
533 }
534 return true;
535 case json_type::number:
536 {
537 auto value = extract_number(document);
538 if (!value) {
539 return false;
540 }
541 write_number(&root_tag_writer_, *value);
542 return true;
543 }
544 case json_type::string:
545 {
546 auto value = extract_string(document);
547 if (!value) {
548 return false;
549 }
550 write_string(&root_tag_writer_, *value);
551 return true;
552 }
553 case json_type::boolean:
554 {
555 auto value = extract_boolean(document);
556 if (!value) {
557 return false;
558 }
559 write_boolean(&root_tag_writer_, *value);
560 return true;
561 }
562 case json_type::null:
563 {
564 auto value = extract_null(document);
565 if (!value) {
566 return false;
567 }
568 write_null(&root_tag_writer_);
569 return true;
570 }
571 default:
572 ERR(GRN_INVALID_ARGUMENT, "%s failed to get root value", tag);
573 return false;
574 }
575 }
576
577 std::optional<JSONValue>
578 extract_value(simdjson::ondemand::value &value)
579 {
580 const char *tag = "[json-parser][parse][value]";
581 auto ctx = ctx_;
582
583 json_type type;
584 auto error_code = value.type().get(type);
585 if (error_code != simdjson::SUCCESS) {
586 ERR(GRN_INVALID_ARGUMENT,
587 "%s failed to get value type: %s",
588 tag,
589 simdjson::error_message(error_code));
590 return std::nullopt;
591 }
592 switch (type) {
593 case json_type::object:
594 case json_type::array:
595 return extract_container(value);
596 case json_type::number:
597 return extract_number(value);
598 case json_type::string:
599 {
600 auto string_value = extract_string(value);
601 if (!string_value) {
602 return std::nullopt;
603 }
604 return JSONValue{GRN_JSON_VALUE_STRING, *string_value};
605 }
606 case json_type::boolean:
607 {
608 auto boolean_value = extract_boolean(value);
609 if (!boolean_value) {
610 return std::nullopt;
611 }
612 if (*boolean_value) {
613 return JSONValue{GRN_JSON_VALUE_TRUE, {}};
614 } else {
615 return JSONValue{GRN_JSON_VALUE_FALSE, {}};
616 }
617 }
618 case json_type::null:
619 {
620 if (!extract_null(value)) {
621 return std::nullopt;
622 }
623 return JSONValue{GRN_JSON_VALUE_NULL, {}};
624 }
625 default:
626 ERR(GRN_INVALID_ARGUMENT, "%s failed to get value", tag);
627 return std::nullopt;
628 }
629 }
630
631 void
632 write_container(TagWriter *tag_writer, JSONValue &value)
633 {
634 const char *tag = "[json-parser][write][container]";
635 auto ctx = ctx_;
636
637 std::queue<JSONValue *> values;
638 std::queue<TagWriter *> tag_writers;
639 values.push(&value);
640 tag_writers.push(tag_writer);
641 while (!values.empty()) {
642 auto current_value = values.front();
643 values.pop();
644 auto current_tag_writer = tag_writers.front();
645 tag_writers.pop();
646
647 switch (current_value->type) {
648 case GRN_JSON_VALUE_OBJECT:
649 {
650 auto &items = std::get<std::vector<JSONValue>>(current_value->data);
651 auto index = object_positions_writer_.write(items.size() / 2);
652 current_tag_writer->write(Type::kObject, false, 0, index);
653 for (size_t i = 0; i < items.size(); i += 2) {
654 auto &key = std::get<std::string>(items[i].data);
655 auto &value = items[i + 1];
656
657 object_key_positions_writer_.write(key.size());
658 GRN_TEXT_PUT(ctx_, &object_keys_, key.data(), key.size());
659
660 values.push(&value);
661 tag_writers.push(&object_value_tags_writer_);
662 }
663 }
664 break;
665 case GRN_JSON_VALUE_ARRAY:
666 {
667 auto &elements =
668 std::get<std::vector<JSONValue>>(current_value->data);
669 auto index = array_positions_writer_.write(elements.size());
670 current_tag_writer->write(Type::kArray, false, 0, index);
671 for (auto &element : elements) {
672 values.push(&element);
673 tag_writers.push(&array_tags_writer_);
674 }
675 }
676 break;
677 case GRN_JSON_VALUE_INT64:
678 write_int64(current_tag_writer,
679 std::get<int64_t>(current_value->data));
680 break;
681 case GRN_JSON_VALUE_FLOAT:
682 write_double(current_tag_writer,
683 std::get<double>(current_value->data));
684 break;
685 case GRN_JSON_VALUE_STRING:
686 write_string(current_tag_writer,
687 std::get<std::string_view>(current_value->data));
688 break;
689 case GRN_JSON_VALUE_TRUE:
690 write_boolean(current_tag_writer, true);
691 break;
692 case GRN_JSON_VALUE_FALSE:
693 write_boolean(current_tag_writer, false);
694 break;
695 case GRN_JSON_VALUE_NULL:
696 write_null(current_tag_writer);
697 break;
698 default:
699 ERR(GRN_INVALID_ARGUMENT,
700 "%s invalid value type: %u",
701 tag,
702 static_cast<unsigned int>(current_value->type));
703 return;
704 }
705 }
706 }
707
708 std::optional<JSONValue>
709 extract_container(simdjson::ondemand::value &value)
710 {
711 const char *tag = "[json-parser][extract][container]";
712 auto ctx = ctx_;
713
714 json_type type;
715 auto error_code = value.type().get(type);
716 if (error_code != simdjson::SUCCESS) {
717 ERR(GRN_INVALID_ARGUMENT,
718 "%s failed to get value type: %s",
719 tag,
720 simdjson::error_message(error_code));
721 return std::nullopt;
722 }
723
724 switch (type) {
725 case json_type::object:
726 {
727 simdjson::ondemand::object object;
728 error_code = value.get_object().get(object);
729 if (error_code != simdjson::SUCCESS) {
730 ERR(GRN_INVALID_ARGUMENT,
731 "%s failed to get object: %s",
732 tag,
733 simdjson::error_message(error_code));
734 return std::nullopt;
735 }
736 std::vector<JSONValue> items;
737 for (auto field : object) {
738 std::string_view key;
739 error_code = field.unescaped_key().get(key);
740 if (error_code != simdjson::SUCCESS) {
741 ERR(GRN_INVALID_ARGUMENT,
742 "%s failed to get object key: %s",
743 tag,
744 simdjson::error_message(error_code));
745 return std::nullopt;
746 }
747 // We need to copy key here because key is valid only in
748 // this iteration.
749 items.push_back(JSONValue{GRN_JSON_VALUE_STRING, std::string(key)});
750
751 simdjson::ondemand::value value;
752 error_code = field.value().get(value);
753 if (error_code != simdjson::SUCCESS) {
754 ERR(GRN_INVALID_ARGUMENT,
755 "%s failed to get object value: %s",
756 tag,
757 simdjson::error_message(error_code));
758 return std::nullopt;
759 }
760 auto json_value = extract_value(value);
761 if (!json_value) {
762 return std::nullopt;
763 }
764 items.push_back(*json_value);
765 }
766 return JSONValue{GRN_JSON_VALUE_OBJECT, std::move(items)};
767 }
768 case json_type::array:
769 {
770 simdjson::ondemand::array array;
771 error_code = value.get_array().get(array);
772 if (error_code != simdjson::SUCCESS) {
773 ERR(GRN_INVALID_ARGUMENT,
774 "%s failed to get array: %s",
775 tag,
776 simdjson::error_message(error_code));
777 return std::nullopt;
778 }
779 std::vector<JSONValue> elements;
780 for (auto element_result : array) {
781 simdjson::ondemand::value element;
782 error_code = element_result.get(element);
783 if (error_code != simdjson::SUCCESS) {
784 ERR(GRN_INVALID_ARGUMENT,
785 "%s failed to get array element: %s",
786 tag,
787 simdjson::error_message(error_code));
788 return std::nullopt;
789 }
790 auto json_value = extract_value(element);
791 if (!json_value) {
792 return std::nullopt;
793 }
794 elements.push_back(*json_value);
795 }
796 return JSONValue{GRN_JSON_VALUE_ARRAY, std::move(elements)};
797 }
798 case json_type::number:
799 return extract_number(value);
800 case json_type::string:
801 {
802 auto string_value = extract_string(value);
803 if (!string_value) {
804 return std::nullopt;
805 }
806 return JSONValue{GRN_JSON_VALUE_STRING, *string_value};
807 }
808 case json_type::boolean:
809 {
810 auto boolean_value = extract_boolean(value);
811 if (!boolean_value) {
812 return std::nullopt;
813 }
814 if (*boolean_value) {
815 return JSONValue{GRN_JSON_VALUE_TRUE, {}};
816 } else {
817 return JSONValue{GRN_JSON_VALUE_FALSE, {}};
818 }
819 }
820 case json_type::null:
821 if (!extract_null(value)) {
822 return std::nullopt;
823 }
824 return JSONValue{GRN_JSON_VALUE_NULL, {}};
825 default:
826 ERR(GRN_INVALID_ARGUMENT,
827 "%s invalid value type: %u",
828 tag,
829 static_cast<unsigned int>(type));
830 return std::nullopt;
831 }
832 }
833
834 void
835 write_double(TagWriter *tag_writer, double value)
836 {
837 if (std::fpclassify(value) == FP_ZERO) {
838 uint8_t metadata =
839 std::signbit(value)
840 ? static_cast<uint8_t>(metadata::Float::kNegativeZero)
841 : static_cast<uint8_t>(metadata::Float::kPositiveZero);
842 tag_writer->write(Type::kFloat, true, metadata, 0);
843 } else {
844 grn_obj *output;
845 if (is_root(tag_writer)) {
846 output = output_;
847 } else {
848 output = &double_values_;
849 }
850 uint32_t offset = GRN_TEXT_LEN(output);
851 tag_writer->write(Type::kFloat, false, 0, offset);
852 GRN_FLOAT_PUT(ctx_, output, value);
853 }
854 }
855
856 template <typename ValueType>
857 std::optional<double>
858 extract_double(ValueType &value)
859 {
860 const char *tag = "[json-parser][extract][double]";
861 auto ctx = ctx_;
862
863 double double_value;
864 auto error_code = value.get_double().get(double_value);
865 if (error_code != simdjson::SUCCESS) {
866 ERR(GRN_INVALID_ARGUMENT,
867 "%s failed to get floating-point number: %s",
868 tag,
869 simdjson::error_message(error_code));
870 return std::nullopt;
871 }
872 return double_value;
873 }
874
875 void
876 write_int64(TagWriter *tag_writer, int64_t value)
877 {
878 uint8_t n_bytes;
879 if (std::numeric_limits<int8_t>::min() <= value &&
880 value <= std::numeric_limits<int8_t>::max()) {
881 n_bytes = 1;
882 } else if (std::numeric_limits<int16_t>::min() <= value &&
883 value <= std::numeric_limits<int16_t>::max()) {
884 n_bytes = 2;
885 } else if (std::numeric_limits<int32_t>::min() <= value &&
886 value <= std::numeric_limits<int32_t>::max()) {
887 n_bytes = 4;
888 } else {
889 n_bytes = 8;
890 }
891
892 // We can't embed an integer into the root tag.
893 if (!is_root(tag_writer)) {
894 auto container_tags_writer =
895 dynamic_cast<ContainerTagsWriter *>(tag_writer);
896 const auto is_tag32 = (container_tags_writer->size32 > 0);
897 bool is_embeddable;
898 if (is_tag32) {
899 is_embeddable = (-(1 << 15) <= value && value <= ((1 << 23) - 1));
900 } else {
901 is_embeddable = (n_bytes == 1);
902 }
903 if (is_embeddable) {
904 if (!is_tag32 && value < 0) {
905 value += 256;
906 }
907 tag_writer->write(Type::kInteger, true, n_bytes, value);
908 return;
909 }
910 }
911
912 grn_obj *output;
913 if (tag_writer == &root_tag_writer_) {
914 output = output_;
915 } else {
916 if (n_bytes == 2) {
917 output = &int16_values_;
918 } else if (n_bytes == 4) {
919 output = &int32_values_;
920 } else {
921 output = &int64_values_;
922 }
923 }
924 uint32_t offset = GRN_TEXT_LEN(output);
925 tag_writer->write(Type::kInteger, false, n_bytes, offset);
926 if (n_bytes == 1) {
927 GRN_INT8_PUT(ctx_, output, value);
928 } else if (n_bytes == 2) {
929 GRN_INT16_PUT(ctx_, output, value);
930 } else if (n_bytes == 4) {
931 GRN_INT32_PUT(ctx_, output, value);
932 } else {
933 GRN_INT64_PUT(ctx_, output, value);
934 }
935 }
936
937 template <typename ValueType>
938 std::optional<JSONValue>
939 extract_int64(ValueType &value)
940 {
941 auto ctx = ctx_;
942 const char *tag = "[json-parser][extract][int64]";
943
944 int64_t int64_value;
945 auto error_code = value.get_int64().get(int64_value);
946 if (error_code != simdjson::SUCCESS) {
947 # ifndef BIGINT_NUMBER
948 {
949 auto double_value = extract_double(value);
950 if (!double_value) {
951 return std::nullopt;
952 }
953 return JSONValue{GRN_JSON_VALUE_FLOAT, *double_value};
954 }
955 # endif
956 ERR(GRN_INVALID_ARGUMENT,
957 "%s failed to get int64 number: %s",
958 tag,
959 simdjson::error_message(error_code));
960 return std::nullopt;
961 }
962 return JSONValue{GRN_JSON_VALUE_INT64, int64_value};
963 }
964
965 void
966 write_number(TagWriter *tag_writer, JSONValue &value)
967 {
968 if (value.type == GRN_JSON_VALUE_FLOAT) {
969 write_double(tag_writer, std::get<double>(value.data));
970 } else {
971 write_int64(tag_writer, std::get<int64_t>(value.data));
972 }
973 }
974
975 template <typename ValueType>
976 std::optional<JSONValue>
977 extract_number(ValueType &value)
978 {
979 using number_type = simdjson::ondemand::number_type;
980 const char *tag = "[json-parser][extract][number]";
981 auto ctx = ctx_;
982
983 number_type type;
984 auto error_code = value.get_number_type().get(type);
985 if (error_code != simdjson::SUCCESS) {
986 ERR(GRN_INVALID_ARGUMENT,
987 "%s failed to get number type: %s",
988 tag,
989 simdjson::error_message(error_code));
990 return std::nullopt;
991 }
992
993 switch (type) {
994 case number_type::floating_point_number:
995 # ifdef BIGINT_NUMBER
996 case number_type::big_integer: // simdjson 3.7.1 or later has this.
997 # endif
998 {
999 auto double_value = extract_double(value);
1000 if (!double_value) {
1001 return std::nullopt;
1002 }
1003 return JSONValue{GRN_JSON_VALUE_FLOAT, *double_value};
1004 }
1005 case number_type::unsigned_integer:
1006 // simdjson < 3.1.0 detects -9223372036854775808 as unsigned
1007 // integer: https://github.com/simdjson/simdjson/pull/1819
1008 if constexpr (simdjson::SIMDJSON_VERSION_MAJOR < 3 ||
1009 (simdjson::SIMDJSON_VERSION_MAJOR == 3 &&
1010 simdjson::SIMDJSON_VERSION_MINOR < 1)) {
1011 // Try parsing this as an int64 value. parse_int64() falls
1012 // back to parse_double() when this is not an int64 value.
1013 return extract_int64(value);
1014 }
1015 {
1016 auto double_value = extract_double(value);
1017 if (!double_value) {
1018 return std::nullopt;
1019 }
1020 return JSONValue{GRN_JSON_VALUE_FLOAT, *double_value};
1021 }
1022 case number_type::signed_integer:
1023 return extract_int64(value);
1024 default:
1025 ERR(GRN_INVALID_ARGUMENT,
1026 "%s unsupported number type: %d",
1027 tag,
1028 static_cast<int32_t>(type));
1029 return std::nullopt;
1030 }
1031 }
1032
1033 void
1034 write_string(TagWriter *tag_writer, std::string_view value)
1035 {
1036 // We can't embed a string into the root tag.
1037 if (!is_root(tag_writer)) {
1038 auto container_tags_writer =
1039 dynamic_cast<ContainerTagsWriter *>(tag_writer);
1040 const auto is_tag32 = (container_tags_writer->size32 > 0);
1041 const size_t max_embeddable_size = is_tag32 ? 3 : 1;
1042 const auto is_embeddable = (value.size() <= max_embeddable_size);
1043 if (is_embeddable) {
1044 uint32_t data = 0;
1045 std::memcpy(&data, value.data(), value.size());
1046 tag_writer->write(Type::kString, true, value.length(), data);
1047 return;
1048 }
1049 }
1050
1051 grn_obj *output;
1052 uint32_t index;
1053 if (is_root(tag_writer)) {
1054 output = output_;
1055 index = 0;
1056 } else {
1057 output = &string_values_;
1058 index = string_positions_writer_.write(value.size());
1059 }
1060 tag_writer->write(Type::kString, false, 0, index);
1061 GRN_TEXT_PUT(ctx_, output, value.data(), value.size());
1062 }
1063
1064 template <typename ValueType>
1065 std::optional<std::string_view>
1066 extract_string(ValueType &value)
1067 {
1068 const char *tag = "[json-parser][extract][string]";
1069 auto ctx = ctx_;
1070
1071 std::string_view string_value;
1072 auto error_code = value.get_string().get(string_value);
1073 if (error_code != simdjson::SUCCESS) {
1074 ERR(GRN_INVALID_ARGUMENT,
1075 "%s failed to get value: %s",
1076 tag,
1077 simdjson::error_message(error_code));
1078 return std::nullopt;
1079 }
1080 return string_value;
1081 }
1082
1083 void
1084 write_boolean(TagWriter *tag_writer, bool value)
1085 {
1086 uint8_t metadata = value
1087 ? static_cast<uint8_t>(metadata::Constant::kTrue)
1088 : static_cast<uint8_t>(metadata::Constant::kFalse);
1089 tag_writer->write(Type::kConstant, true, metadata, 0);
1090 }
1091
1092 template <typename ValueType>
1093 std::optional<bool>
1094 extract_boolean(ValueType &value)
1095 {
1096 const char *tag = "[json-parser][extract][boolean]";
1097 auto ctx = ctx_;
1098
1099 bool bool_value;
1100 auto error_code = value.get_bool().get(bool_value);
1101 if (error_code != simdjson::SUCCESS) {
1102 ERR(GRN_INVALID_ARGUMENT,
1103 "%s failed to get value: %s",
1104 tag,
1105 simdjson::error_message(error_code));
1106 return std::nullopt;
1107 }
1108 return bool_value;
1109 }
1110
1111 void
1112 write_null(TagWriter *tag_writer)
1113 {
1114 uint8_t metadata = static_cast<uint8_t>(metadata::Constant::kNull);
1115 tag_writer->write(Type::kConstant, true, metadata, 0);
1116 }
1117
1118 template <typename ValueType>
1119 std::optional<bool>
1120 extract_null(ValueType &value)
1121 {
1122 const char *tag = "[json-parser][extract][null]";
1123 auto ctx = ctx_;
1124
1125 bool is_null;
1126 if constexpr (simdjson::SIMDJSON_VERSION_MAJOR >= 4 ||
1127 (simdjson::SIMDJSON_VERSION_MAJOR == 3 &&
1128 simdjson::SIMDJSON_VERSION_MINOR >= 1)) {
1129 auto error_code = value.is_null().get(is_null);
1130 if (error_code != simdjson::SUCCESS) {
1131 ERR(GRN_INVALID_ARGUMENT,
1132 "%s failed to determine null: %s",
1133 tag,
1134 simdjson::error_message(error_code));
1135 return std::nullopt;
1136 }
1137 } else {
1138 is_null = value.is_null();
1139 }
1140 if (!is_null) {
1141 ERR(GRN_INVALID_ARGUMENT, "%s not null", tag);
1142 return std::nullopt;
1143 }
1144 return true;
1145 }
1146 };
1147 #endif
1148
1149 class JSONDataReader {
1150 public:
1151 JSONDataReader(grn_obj *json) : json_(json) {}
1152 ~JSONDataReader() = default;
1153
1154 protected:
1155 grn_obj *json_;
1156
1157 template <typename ValueType>
1158 ValueType
1159 read_data(uint32_t offset)
1160 {
1161 return *reinterpret_cast<const ValueType *>(GRN_JSON_VALUE(json_) +
1162 offset);
1163 }
1164 };
1165
1166 class VariableSizeTagResolver : JSONDataReader {
1167 public:
1168 VariableSizeTagResolver(grn_obj *json,
1169 uint32_t offset16,
1170 uint32_t n16,
1171 uint32_t offset32)
1172 : JSONDataReader(json),
1173 offset16_(offset16),
1174 n16_(n16),
1175 offset32_(offset32)
1176 {
1177 }
1178 ~VariableSizeTagResolver() = default;
1179
1180 uint32_t
1181 resolve(uint32_t i)
1182 {
1183 if (i < n16_) {
1184 auto offset = offset16_ + (sizeof(uint16_t) * i);
1185 return read_data<uint16_t>(offset);
1186 } else {
1187 auto offset = offset32_ + (sizeof(uint32_t) * (i - n16_));
1188 return read_data<uint32_t>(offset);
1189 }
1190 }
1191
1192 private:
1193 uint32_t offset16_;
1194 uint32_t n16_;
1195 uint32_t offset32_;
1196 };
1197
1198 class VariableSizePositionResolver : JSONDataReader {
1199 public:
1200 VariableSizePositionResolver(grn_obj *json,
1201 uint32_t offset8,
1202 uint32_t n8,
1203 uint32_t offset16,
1204 uint32_t n16,
1205 uint32_t offset32)
1206 : JSONDataReader(json),
1207 offset8_(offset8),
1208 n8_(n8),
1209 offset16_(offset16),
1210 n16_(n16),
1211 offset32_(offset32)
1212 {
1213 }
1214 ~VariableSizePositionResolver() = default;
1215
1216 std::pair<uint32_t, uint32_t>
1217 resolve(uint32_t i)
1218 {
1219 uint32_t start = 0;
1220 uint32_t next_start = 0;
1221 if (i < n8_) {
1222 auto offset = offset8_ + (sizeof(uint8_t) * i);
1223 if (i == 0) {
1224 start = 0;
1225 next_start = read_data<uint8_t>(offset);
1226 } else {
1227 auto previous_offset = offset - sizeof(uint8_t);
1228 start = read_data<uint8_t>(previous_offset);
1229 next_start = read_data<uint8_t>(offset);
1230 }
1231 } else if (i < (n8_ + n16_)) {
1232 auto offset = offset16_ + (sizeof(uint16_t) * (i - n8_));
1233 if (i == 0) {
1234 start = 0;
1235 next_start = read_data<uint16_t>(offset);
1236 } else if (i == n8_) {
1237 auto last_offset8_offset = offset8_ + (sizeof(uint8_t) * (n8_ - 1));
1238 start = read_data<uint8_t>(last_offset8_offset);
1239 next_start = read_data<uint16_t>(offset);
1240 } else {
1241 auto previous_offset = offset - sizeof(uint16_t);
1242 start = read_data<uint16_t>(previous_offset);
1243 next_start = read_data<uint16_t>(offset);
1244 }
1245 } else {
1246 auto offset = offset32_ + (sizeof(uint32_t) * (i - n8_ - n16_));
1247 if (i == 0) {
1248 start = 0;
1249 next_start = read_data<uint32_t>(offset);
1250 } else if (i == (n8_ + n16_)) {
1251 if (n16_ == 0) {
1252 if (n8_ == 0) {
1253 start = 0;
1254 } else {
1255 auto last_offset8_offset =
1256 offset8_ + (sizeof(uint8_t) * (n8_ - 1));
1257 start = read_data<uint8_t>(last_offset8_offset);
1258 }
1259 } else {
1260 auto last_offset16_offset =
1261 offset16_ + (sizeof(uint16_t) * (n16_ - 1));
1262 start = read_data<uint16_t>(last_offset16_offset);
1263 }
1264 next_start = read_data<uint32_t>(offset);
1265 } else {
1266 auto previous_offset = offset - sizeof(uint32_t);
1267 start = read_data<uint32_t>(previous_offset);
1268 next_start = read_data<uint32_t>(offset);
1269 }
1270 }
1271 return {start, next_start};
1272 }
1273
1274 private:
1275 uint32_t offset8_;
1276 uint32_t n8_;
1277 uint32_t offset16_;
1278 uint32_t n16_;
1279 uint32_t offset32_;
1280 };
1281
1282 class JSONReader : JSONDataReader {
1283 public:
1284 JSONReader(grn_ctx *ctx, grn_obj *json)
1285 : JSONDataReader(json),
1286 ctx_(ctx),
1287 flags_(0),
1288 object_position_resolver_(),
1289 object_keys_offset_(0),
1290 object_key_position_resolver_(),
1291 object_value_tag_resolver_(),
1292 array_position_resolver_(),
1293 array_tag_resolver_(),
1294 string_values_offset_(0),
1295 string_position_resolver_(),
1296 int16_values_offset_(0),
1297 int32_values_offset_(0),
1298 int64_values_offset_(0),
1299 double_values_offset_(0),
1300 states_(),
1301 current_type_(GRN_JSON_VALUE_UNKNOWN),
1302 current_value_(nullptr),
1303 current_size_(0),
1304 null_value_(),
1305 bool_value_(),
1306 int64_value_(),
1307 float_value_(),
1308 embedded_string_buffer_(),
1309 string_value_()
1310 {
1311 // Root tag exists.
1312 if (GRN_JSON_LEN(json_) >= sizeof(uint8_t)) {
1313 states_.emplace(GRN_JSON_VALUE_UNKNOWN, 0, 0);
1314 }
1315 GRN_VOID_INIT(&null_value_);
1316 GRN_BOOL_INIT(&bool_value_, 0);
1317 GRN_INT64_INIT(&int64_value_, 0);
1318 GRN_FLOAT_INIT(&float_value_, 0);
1319 GRN_TEXT_INIT(&string_value_, GRN_OBJ_DO_SHALLOW_COPY);
1320 }
1321
1322 ~JSONReader()
1323 {
1324 GRN_OBJ_FIN(ctx_, &null_value_);
1325 GRN_OBJ_FIN(ctx_, &bool_value_);
1326 GRN_OBJ_FIN(ctx_, &int64_value_);
1327 GRN_OBJ_FIN(ctx_, &float_value_);
1328 GRN_OBJ_FIN(ctx_, &string_value_);
1329 };
1330
1331 grn_rc
1332 next()
1333 {
1334 const char *log_tag = "[json-reader][next]";
1335 auto ctx = ctx_;
1336
1337 if (states_.empty()) {
1338 return GRN_END_OF_DATA;
1339 }
1340 auto &state = states_.top();
1341 if (state.type == GRN_JSON_VALUE_UNKNOWN) {
1342 const bool is_root = true;
1343 states_.pop();
1344 auto tag = unpack_tag(read_data<uint8_t>(0));
1345 return next_value(tag, is_root);
1346 } else if (state.type == GRN_JSON_VALUE_OBJECT) {
1347 const auto index = state.index;
1348 const auto is_key = state.is_key;
1349 if (is_key) {
1350 state.is_key = false;
1351 } else {
1352 if (index == state.last_index) {
1353 states_.pop();
1354 } else {
1355 state.index++;
1356 state.is_key = true;
1357 }
1358 }
1359
1360 if (is_key) {
1361 auto resolved = object_key_position_resolver_->resolve(index);
1362 auto start = resolved.first;
1363 auto next_start = resolved.second;
1364 auto size = next_start - start;
1365 GRN_TEXT_SET(ctx_,
1366 &string_value_,
1367 GRN_JSON_VALUE(json_) + object_keys_offset_ + start,
1368 size);
1369 current_type_ = GRN_JSON_VALUE_STRING;
1370 current_value_ = &string_value_;
1371 current_size_ = 0;
1372 return ctx->rc;
1373 } else {
1374 auto raw_tag = object_value_tag_resolver_->resolve(index);
1375 auto tag = unpack_tag(raw_tag);
1376 return next_value(tag, false);
1377 }
1378 } else if (state.type == GRN_JSON_VALUE_ARRAY) {
1379 auto raw_tag = array_tag_resolver_->resolve(state.index);
1380 if (state.index == state.last_index) {
1381 states_.pop();
1382 } else {
1383 state.index++;
1384 }
1385 auto tag = unpack_tag(raw_tag);
1386 return next_value(tag, false);
1387 } else {
1388 ERR(GRN_FUNCTION_NOT_IMPLEMENTED,
1389 "%s unsupported value type: %s(%u)",
1390 log_tag,
1391 grn_json_value_type_to_string(state.type),
1392 static_cast<uint32_t>(state.type));
1393 return ctx_->rc;
1394 }
1395 }
1396
1397 grn_json_value_type
1398 type()
1399 {
1400 return current_type_;
1401 }
1402
1403 grn_obj *
1404 value()
1405 {
1406 return current_value_;
1407 }
1408
1409 size_t
1410 size()
1411 {
1412 return current_size_;
1413 }
1414
1415 private:
1416 struct State {
1417 grn_json_value_type type;
1418 uint32_t index;
1419 uint32_t last_index;
1420 bool is_key; // This is only for GRN_JSON_VALUE_OBJECT
1421
1422 State(grn_json_value_type type,
1423 uint32_t index,
1424 uint32_t last_index,
1425 bool is_key = false)
1426 : type(type),
1427 index(index),
1428 last_index(last_index),
1429 is_key(is_key)
1430 {
1431 }
1432 };
1433
1434 grn_ctx *ctx_;
1435 uint32_t flags_;
1436 std::unique_ptr<VariableSizePositionResolver> object_position_resolver_;
1437 uint32_t object_keys_offset_;
1438 std::unique_ptr<VariableSizePositionResolver> object_key_position_resolver_;
1439 std::unique_ptr<VariableSizeTagResolver> object_value_tag_resolver_;
1440 std::unique_ptr<VariableSizePositionResolver> array_position_resolver_;
1441 std::unique_ptr<VariableSizeTagResolver> array_tag_resolver_;
1442 uint32_t string_values_offset_;
1443 std::unique_ptr<VariableSizePositionResolver> string_position_resolver_;
1444 uint32_t int16_values_offset_;
1445 uint32_t int32_values_offset_;
1446 uint32_t int64_values_offset_;
1447 uint32_t double_values_offset_;
1448 std::stack<State> states_;
1449 grn_json_value_type current_type_;
1450 grn_obj *current_value_;
1451 size_t current_size_;
1452 grn_obj null_value_;
1453 grn_obj bool_value_;
1454 grn_obj int64_value_;
1455 grn_obj float_value_;
1456 char embedded_string_buffer_[3];
1457 grn_obj string_value_;
1458
1459 Tag
1460 unpack_tag(uint32_t raw_tag)
1461 {
1462 Tag tag;
1463 tag.type = static_cast<Type>(raw_tag & 0b111);
1464 tag.is_embedded = (raw_tag & (0b1000));
1465 tag.metadata = ((raw_tag >> 4) & (0b00001111));
1466 tag.data = (raw_tag >> 8);
1467 return tag;
1468 }
1469
1470 std::unique_ptr<VariableSizeTagResolver>
1471 create_variable_size_tag_resolver(
1472 uint32_t &i,
1473 const std::vector<uint32_t> &buffer_offsets,
1474 Flag flag16,
1475 Flag flag32)
1476 {
1477 uint32_t offset16 = 0;
1478 uint32_t n16 = 0;
1479 if (flags_ & static_cast<uint32_t>(flag16)) {
1480 offset16 = buffer_offsets[i];
1481 n16 = (buffer_offsets[i + 1] - buffer_offsets[i]) / sizeof(uint16_t);
1482 i++;
1483 }
1484
1485 uint32_t offset32 = 0;
1486 if (flags_ & static_cast<uint32_t>(flag32)) {
1487 offset32 = buffer_offsets[i];
1488 i++;
1489 }
1490
1491 return std::make_unique<VariableSizeTagResolver>(json_,
1492 offset16,
1493 n16,
1494 offset32);
1495 }
1496
1497 std::unique_ptr<VariableSizePositionResolver>
1498 create_variable_size_position_resolver(
1499 uint32_t &i,
1500 const std::vector<uint32_t> &buffer_offsets,
1501 Flag flag8,
1502 Flag flag16,
1503 Flag flag32)
1504 {
1505 uint32_t offset8 = 0;
1506 uint32_t n8 = 0;
1507 if (flags_ & static_cast<uint32_t>(flag8)) {
1508 offset8 = buffer_offsets[i];
1509 n8 = (buffer_offsets[i + 1] - buffer_offsets[i]) / sizeof(uint8_t);
1510 i++;
1511 }
1512
1513 uint32_t offset16 = 0;
1514 uint32_t n16 = 0;
1515 if (flags_ & static_cast<uint32_t>(flag16)) {
1516 offset16 = buffer_offsets[i];
1517 n16 = (buffer_offsets[i + 1] - buffer_offsets[i]) / sizeof(uint16_t);
1518 i++;
1519 }
1520
1521 uint32_t offset32 = 0;
1522 if (flags_ & static_cast<uint32_t>(flag32)) {
1523 offset32 = buffer_offsets[i];
1524 i++;
1525 }
1526
1527 return std::make_unique<VariableSizePositionResolver>(json_,
1528 offset8,
1529 n8,
1530 offset16,
1531 n16,
1532 offset32);
1533 }
1534
1535 grn_rc
1536 read_footer()
1537 {
1538 uint32_t flags_offset = kRootTagSize;
1539 flags_ |= read_data<uint8_t>(flags_offset) << 16;
1540 flags_ |= read_data<uint8_t>(flags_offset + sizeof(uint8_t)) << 8;
1541 flags_ |= read_data<uint8_t>(flags_offset + sizeof(uint8_t) * 2);
1542
1543 uint32_t n_buffer_offsets = 0;
1544 if (flags_ & static_cast<uint32_t>(Flag::kObjectPosition8)) {
1545 n_buffer_offsets++;
1546 }
1547 if (flags_ & static_cast<uint32_t>(Flag::kObjectPosition16)) {
1548 n_buffer_offsets++;
1549 }
1550 if (flags_ & static_cast<uint32_t>(Flag::kObjectPosition32)) {
1551 n_buffer_offsets++;
1552 }
1553 if (flags_ & static_cast<uint32_t>(Flag::kObjectKey)) {
1554 n_buffer_offsets++;
1555 }
1556 if (flags_ & static_cast<uint32_t>(Flag::kObjectKeyPosition8)) {
1557 n_buffer_offsets++;
1558 }
1559 if (flags_ & static_cast<uint32_t>(Flag::kObjectKeyPosition16)) {
1560 n_buffer_offsets++;
1561 }
1562 if (flags_ & static_cast<uint32_t>(Flag::kObjectKeyPosition32)) {
1563 n_buffer_offsets++;
1564 }
1565 if (flags_ & static_cast<uint32_t>(Flag::kObjectValueTag16)) {
1566 n_buffer_offsets++;
1567 }
1568 if (flags_ & static_cast<uint32_t>(Flag::kObjectValueTag32)) {
1569 n_buffer_offsets++;
1570 }
1571 if (flags_ & static_cast<uint32_t>(Flag::kArrayPosition8)) {
1572 n_buffer_offsets++;
1573 }
1574 if (flags_ & static_cast<uint32_t>(Flag::kArrayPosition16)) {
1575 n_buffer_offsets++;
1576 }
1577 if (flags_ & static_cast<uint32_t>(Flag::kArrayPosition32)) {
1578 n_buffer_offsets++;
1579 }
1580 if (flags_ & static_cast<uint32_t>(Flag::kArrayTag16)) {
1581 n_buffer_offsets++;
1582 }
1583 if (flags_ & static_cast<uint32_t>(Flag::kArrayTag32)) {
1584 n_buffer_offsets++;
1585 }
1586 if (flags_ & static_cast<uint32_t>(Flag::kStringValue)) {
1587 n_buffer_offsets++;
1588 }
1589 if (flags_ & static_cast<uint32_t>(Flag::kStringPosition8)) {
1590 n_buffer_offsets++;
1591 }
1592 if (flags_ & static_cast<uint32_t>(Flag::kStringPosition16)) {
1593 n_buffer_offsets++;
1594 }
1595 if (flags_ & static_cast<uint32_t>(Flag::kStringPosition32)) {
1596 n_buffer_offsets++;
1597 }
1598 if (flags_ & static_cast<uint32_t>(Flag::kInt16)) {
1599 n_buffer_offsets++;
1600 }
1601 if (flags_ & static_cast<uint32_t>(Flag::kInt32)) {
1602 n_buffer_offsets++;
1603 }
1604 if (flags_ & static_cast<uint32_t>(Flag::kInt64)) {
1605 n_buffer_offsets++;
1606 }
1607 if (flags_ & static_cast<uint32_t>(Flag::kDouble)) {
1608 n_buffer_offsets++;
1609 }
1610
1611 std::vector<uint32_t> buffer_offsets;
1612 if (flags_ & static_cast<uint32_t>(Flag::kOffset32)) {
1613 uint32_t offset =
1614 GRN_JSON_LEN(json_) - (sizeof(uint32_t) * n_buffer_offsets);
1615 for (uint32_t i = 0; i < n_buffer_offsets; ++i) {
1616 buffer_offsets.push_back(read_data<uint32_t>(offset));
1617 offset += sizeof(uint32_t);
1618 }
1619 } else {
1620 uint32_t offset =
1621 GRN_JSON_LEN(json_) - (sizeof(uint16_t) * n_buffer_offsets);
1622 for (uint32_t i = 0; i < n_buffer_offsets; ++i) {
1623 buffer_offsets.push_back(read_data<uint16_t>(offset));
1624 offset += sizeof(uint16_t);
1625 }
1626 }
1627 buffer_offsets.push_back(GRN_JSON_LEN(json_));
1628
1629 uint32_t i = 0;
1630 object_position_resolver_ =
1631 create_variable_size_position_resolver(i,
1632 buffer_offsets,
1633 Flag::kObjectPosition8,
1634 Flag::kObjectPosition16,
1635 Flag::kObjectPosition32);
1636 if (flags_ & static_cast<uint32_t>(Flag::kObjectKey)) {
1637 object_keys_offset_ = buffer_offsets[i];
1638 i++;
1639 }
1640 object_key_position_resolver_ =
1641 create_variable_size_position_resolver(i,
1642 buffer_offsets,
1643 Flag::kObjectKeyPosition8,
1644 Flag::kObjectKeyPosition16,
1645 Flag::kObjectKeyPosition32);
1646 object_value_tag_resolver_ =
1647 create_variable_size_tag_resolver(i,
1648 buffer_offsets,
1649 Flag::kObjectValueTag16,
1650 Flag::kObjectValueTag32);
1651 array_position_resolver_ =
1652 create_variable_size_position_resolver(i,
1653 buffer_offsets,
1654 Flag::kArrayPosition8,
1655 Flag::kArrayPosition16,
1656 Flag::kArrayPosition32);
1657 array_tag_resolver_ =
1658 create_variable_size_tag_resolver(i,
1659 buffer_offsets,
1660 Flag::kArrayTag16,
1661 Flag::kArrayTag32);
1662 if (flags_ & static_cast<uint32_t>(Flag::kStringValue)) {
1663 string_values_offset_ = buffer_offsets[i];
1664 i++;
1665 }
1666 string_position_resolver_ =
1667 create_variable_size_position_resolver(i,
1668 buffer_offsets,
1669 Flag::kStringPosition8,
1670 Flag::kStringPosition16,
1671 Flag::kStringPosition32);
1672 if (flags_ & static_cast<uint32_t>(Flag::kInt16)) {
1673 int16_values_offset_ = buffer_offsets[i];
1674 i++;
1675 }
1676 if (flags_ & static_cast<uint32_t>(Flag::kInt32)) {
1677 int32_values_offset_ = buffer_offsets[i];
1678 i++;
1679 }
1680 if (flags_ & static_cast<uint32_t>(Flag::kInt64)) {
1681 int64_values_offset_ = buffer_offsets[i];
1682 i++;
1683 }
1684 if (flags_ & static_cast<uint32_t>(Flag::kDouble)) {
1685 double_values_offset_ = buffer_offsets[i];
1686 i++;
1687 }
1688 return GRN_SUCCESS;
1689 }
1690
1691 grn_rc
1692 next_value(const Tag &tag, bool is_root)
1693 {
1694 const char *log_tag = "[json-reader][next][value]";
1695 auto ctx = ctx_;
1696
1697 if (tag.type == Type::kConstant) {
1698 return next_constant(tag);
1699 }
1700
1701 if (is_root && (tag.type == Type::kArray || tag.type == Type::kObject)) {
1702 auto rc = read_footer();
1703 if (rc != GRN_SUCCESS) {
1704 return rc;
1705 }
1706 }
1707
1708 switch (tag.type) {
1709 case Type::kObject:
1710 return next_object(tag, is_root);
1711 case Type::kArray:
1712 return next_array(tag, is_root);
1713 case Type::kInteger:
1714 return next_integer(tag, is_root);
1715 case Type::kFloat:
1716 return next_float(tag, is_root);
1717 case Type::kString:
1718 return next_string(tag, is_root);
1719 default:
1720 ERR(GRN_FUNCTION_NOT_IMPLEMENTED,
1721 "%s unsupported root value type",
1722 log_tag);
1723 return ctx->rc;
1724 }
1725 }
1726
1727 grn_rc
1728 next_object(const Tag &tag, bool is_root)
1729 {
1730 auto index = tag.data;
1731 auto resolved = object_position_resolver_->resolve(index);
1732 auto start = resolved.first;
1733 auto next_start = resolved.second;
1734 current_type_ = GRN_JSON_VALUE_OBJECT;
1735 current_value_ = nullptr;
1736 current_size_ = next_start - start;
1737 if (current_size_ > 0) {
1738 states_.emplace(GRN_JSON_VALUE_OBJECT, start, next_start - 1, true);
1739 }
1740 return GRN_SUCCESS;
1741 }
1742
1743 grn_rc
1744 next_array(const Tag &tag, bool is_root)
1745 {
1746 auto index = tag.data;
1747 auto resolved = array_position_resolver_->resolve(index);
1748 auto start = resolved.first;
1749 auto next_start = resolved.second;
1750 current_type_ = GRN_JSON_VALUE_ARRAY;
1751 current_value_ = nullptr;
1752 current_size_ = next_start - start;
1753 if (current_size_ > 0) {
1754 states_.emplace(GRN_JSON_VALUE_ARRAY, start, next_start - 1);
1755 }
1756 return GRN_SUCCESS;
1757 }
1758
1759 grn_rc
1760 next_float(const Tag &tag, bool is_root)
1761 {
1762 const char *log_tag = "[json-reader][next][float]";
1763 auto ctx = ctx_;
1764
1765 if (tag.is_embedded) {
1766 switch (static_cast<metadata::Float>(tag.metadata)) {
1767 case metadata::Float::kPositiveZero:
1768 GRN_FLOAT_SET(ctx_, &float_value_, 0.0);
1769 break;
1770 case metadata::Float::kNegativeZero:
1771 GRN_FLOAT_SET(ctx_, &float_value_, -0.0);
1772 break;
1773 default:
1774 ERR(GRN_INVALID_ARGUMENT,
1775 "%s unknown embedded float: %u",
1776 log_tag,
1777 tag.metadata);
1778 return ctx->rc;
1779 }
1780 current_type_ = GRN_JSON_VALUE_FLOAT;
1781 current_value_ = &float_value_;
1782 current_size_ = 0;
1783 } else {
1784 double value;
1785 if (is_root) {
1786 uint32_t offset = kRootTagSize;
1787 size_t size = GRN_JSON_LEN(json_) - offset;
1788 if (size != sizeof(double)) {
1789 ERR(GRN_INVALID_ARGUMENT,
1790 "%s data size mismatch: expected:%" GRN_FMT_SIZE
1791 " actual:%" GRN_FMT_SIZE,
1792 log_tag,
1793 sizeof(double),
1794 size);
1795 return ctx->rc;
1796 }
1797 value = read_data<double>(offset);
1798 } else {
1799 uint32_t offset = tag.data;
1800 value = read_data<double>(double_values_offset_ + offset);
1801 }
1802 current_type_ = GRN_JSON_VALUE_FLOAT;
1803 GRN_FLOAT_SET(ctx_, &float_value_, value);
1804 current_value_ = &float_value_;
1805 current_size_ = 0;
1806 }
1807 return ctx->rc;
1808 }
1809
1810 grn_rc
1811 next_integer(const Tag &tag, bool is_root)
1812 {
1813 const char *log_tag = "[json-reader][next][integer]";
1814 auto ctx = ctx_;
1815
1816 uint8_t n_bytes = tag.metadata;
1817 int64_t value;
1818 if (is_root) {
1819 uint32_t offset = kRootTagSize;
1820 size_t size = GRN_JSON_LEN(json_) - offset;
1821 if (size != n_bytes) {
1822 ERR(GRN_INVALID_ARGUMENT,
1823 "%s data size mismatch: expected:%u actual:%" GRN_FMT_SIZE,
1824 log_tag,
1825 n_bytes,
1826 size);
1827 return ctx->rc;
1828 }
1829 if (n_bytes == 1) {
1830 value = read_data<int8_t>(offset);
1831 } else if (n_bytes == 2) {
1832 value = read_data<int16_t>(offset);
1833 } else if (n_bytes == 4) {
1834 value = read_data<int32_t>(offset);
1835 } else {
1836 value = read_data<int64_t>(offset);
1837 }
1838 } else {
1839 if (tag.is_embedded) {
1840 if (n_bytes == 1) {
1841 value = static_cast<int8_t>(tag.data);
1842 } else if (n_bytes == 2) {
1843 value = static_cast<int16_t>(tag.data);
1844 } else {
1845 // Embedded 4 bytes data is always signed and between
1846 // -(2 ** 15) and (2 ** 23 - 1).
1847 value = tag.data;
1848 }
1849 } else {
1850 uint32_t offset = tag.data;
1851 if (n_bytes == 2) {
1852 value = read_data<int16_t>(int16_values_offset_ + offset);
1853 } else if (n_bytes == 4) {
1854 value = read_data<int32_t>(int32_values_offset_ + offset);
1855 } else {
1856 value = read_data<int64_t>(int64_values_offset_ + offset);
1857 }
1858 }
1859 }
1860 current_type_ = GRN_JSON_VALUE_INT64;
1861 GRN_INT64_SET(ctx_, &int64_value_, value);
1862 current_value_ = &int64_value_;
1863 current_size_ = 0;
1864 return ctx->rc;
1865 }
1866
1867 grn_rc
1868 next_string(const Tag &tag, bool is_root)
1869 {
1870 auto ctx = ctx_;
1871
1872 if (is_root) {
1873 uint32_t offset = kRootTagSize;
1874 size_t size = GRN_JSON_LEN(json_) - offset;
1875 GRN_TEXT_SET(ctx_,
1876 &string_value_,
1877 GRN_JSON_VALUE(json_) + offset,
1878 size);
1879 } else {
1880 if (tag.is_embedded) {
1881 GRN_BULK_REWIND(&string_value_);
1882 const size_t size = tag.metadata;
1883 std::memcpy(embedded_string_buffer_, &(tag.data), size);
1884 GRN_TEXT_SET(ctx_, &string_value_, embedded_string_buffer_, size);
1885 } else {
1886 const auto index = tag.data;
1887 auto resolved = string_position_resolver_->resolve(index);
1888 auto start = resolved.first;
1889 auto next_start = resolved.second;
1890 auto size = next_start - start;
1891 GRN_TEXT_SET(ctx_,
1892 &string_value_,
1893 GRN_JSON_VALUE(json_) + string_values_offset_ + start,
1894 size);
1895 }
1896 }
1897 current_type_ = GRN_JSON_VALUE_STRING;
1898 current_value_ = &string_value_;
1899 current_size_ = 0;
1900 return ctx->rc;
1901 }
1902
1903 grn_rc
1904 next_constant(const Tag &tag)
1905 {
1906 const char *log_tag = "[json-reader][next][constant]";
1907 auto ctx = ctx_;
1908
1909 current_size_ = 0;
1910 auto constant_metadata = static_cast<metadata::Constant>(tag.metadata);
1911 switch (constant_metadata) {
1912 case metadata::Constant::kTrue:
1913 current_type_ = GRN_JSON_VALUE_TRUE;
1914 GRN_BOOL_SET(ctx_, &bool_value_, true);
1915 current_value_ = &bool_value_;
1916 current_size_ = 0;
1917 break;
1918 case metadata::Constant::kFalse:
1919 current_type_ = GRN_JSON_VALUE_FALSE;
1920 GRN_BOOL_SET(ctx_, &bool_value_, false);
1921 current_value_ = &bool_value_;
1922 current_size_ = 0;
1923 break;
1924 case metadata::Constant::kNull:
1925 current_type_ = GRN_JSON_VALUE_NULL;
1926 current_value_ = &null_value_;
1927 break;
1928 default:
1929 ERR(GRN_INVALID_ARGUMENT,
1930 "%s invalid constant metadata: %u",
1931 log_tag,
1932 tag.metadata);
1933 return ctx->rc;
1934 }
1935 return ctx->rc;
1936 }
1937 };
1938
1939 class JSONStringifier {
1940 public:
1941 JSONStringifier(grn_ctx *ctx, grn_obj *json, grn_obj *buffer)
1942 : ctx_(ctx),
1943 json_(json),
1944 buffer_(buffer)
1945 {
1946 }
1947 ~JSONStringifier() = default;
1948
1949 void
1950 stringify()
1951 {
1952 JSONReader reader(ctx_, json_);
1953 while (true) {
1954 if (!stringify_value(reader)) {
1955 break;
1956 }
1957 }
1958 }
1959
1960 private:
1961 grn_ctx *ctx_;
1962 grn_obj *json_;
1963 grn_obj *buffer_;
1964
1965 bool
1966 stringify_value(JSONReader &reader)
1967 {
1968 const char *tag = "[json][to-string]";
1969
1970 auto rc = reader.next();
1971 if (rc == GRN_END_OF_DATA) {
1972 return false;
1973 }
1974 if (rc != GRN_SUCCESS) {
1975 return false;
1976 }
1977 switch (reader.type()) {
1978 case GRN_JSON_VALUE_NULL:
1979 GRN_TEXT_PUTS(ctx_, buffer_, "null");
1980 return true;
1981 case GRN_JSON_VALUE_FALSE:
1982 GRN_TEXT_PUTS(ctx_, buffer_, "false");
1983 return true;
1984 case GRN_JSON_VALUE_TRUE:
1985 GRN_TEXT_PUTS(ctx_, buffer_, "true");
1986 return true;
1987 case GRN_JSON_VALUE_INT64:
1988 grn_text_otoj(ctx_, buffer_, reader.value(), nullptr);
1989 return true;
1990 case GRN_JSON_VALUE_FLOAT:
1991 grn_text_otoj(ctx_, buffer_, reader.value(), nullptr);
1992 return true;
1993 case GRN_JSON_VALUE_STRING:
1994 grn_text_otoj(ctx_, buffer_, reader.value(), nullptr);
1995 return true;
1996 case GRN_JSON_VALUE_ARRAY:
1997 {
1998 GRN_TEXT_PUTS(ctx_, buffer_, "[");
1999 size_t n = reader.size();
2000 for (size_t i = 0; i < n; ++i) {
2001 if (i != 0) {
2002 GRN_TEXT_PUTS(ctx_, buffer_, ",");
2003 }
2004 if (!stringify_value(reader)) {
2005 return false;
2006 }
2007 }
2008 GRN_TEXT_PUTS(ctx_, buffer_, "]");
2009 return true;
2010 }
2011 case GRN_JSON_VALUE_OBJECT:
2012 {
2013 GRN_TEXT_PUTS(ctx_, buffer_, "{");
2014 size_t n = reader.size();
2015 for (size_t i = 0; i < n; ++i) {
2016 if (i != 0) {
2017 GRN_TEXT_PUTS(ctx_, buffer_, ",");
2018 }
2019 if (!stringify_value(reader)) {
2020 return false;
2021 }
2022 GRN_TEXT_PUTS(ctx_, buffer_, ":");
2023 if (!stringify_value(reader)) {
2024 return false;
2025 }
2026 }
2027 GRN_TEXT_PUTS(ctx_, buffer_, "}");
2028 return true;
2029 }
2030 default:
2031 {
2032 auto ctx = ctx_;
2033 ERR(GRN_INVALID_ARGUMENT, "%s invalid JSON", tag);
2034 return false;
2035 }
2036 }
2037 }
2038 };
2039
2040 #ifdef GRN_WITH_JSONCONS
2041 using json_path_expression =
2042 jsoncons::jsonpath::jsonpath_expression<jsoncons::json>;
2043
2044 class JSONExtractor {
2045 public:
2046 JSONExtractor(grn_ctx *ctx,
2047 grn_obj *json,
2048 json_path_expression *expr,
2049 grn_obj *values)
2050 : ctx_(ctx),
2051 json_(json),
2052 expr_(expr),
2053 values_(values)
2054 {
2055 }
2056 ~JSONExtractor() = default;
2057
2058 void
2059 extract()
2060 {
2061 JSONReader reader(ctx_, json_);
2062 auto rc = reader.next();
2063 if (rc != GRN_SUCCESS) {
2064 return;
2065 }
2066
2067 auto jsoncons_json = convert(reader);
2068 expr_->select(jsoncons_json,
2069 [this](const jsoncons::jsonpath::path_node &path,
2070 const jsoncons::json &value) { push_value(value); });
2071 }
2072
2073 private:
2074 grn_ctx *ctx_;
2075 grn_obj *json_;
2076 json_path_expression *expr_;
2077 grn_obj *values_;
2078
2079 jsoncons::json
2080 convert(JSONReader &reader)
2081 {
2082 switch (reader.type()) {
2083 case GRN_JSON_VALUE_NULL:
2084 return jsoncons::json::null();
2085 case GRN_JSON_VALUE_FALSE:
2086 return jsoncons::json(false, jsoncons::semantic_tag::none);
2087 case GRN_JSON_VALUE_TRUE:
2088 return jsoncons::json(true, jsoncons::semantic_tag::none);
2089 case GRN_JSON_VALUE_INT64:
2090 return jsoncons::json(GRN_INT64_VALUE(reader.value()));
2091 case GRN_JSON_VALUE_FLOAT:
2092 return jsoncons::json(GRN_FLOAT_VALUE(reader.value()));
2093 case GRN_JSON_VALUE_STRING:
2094 return jsoncons::json(std::string_view(GRN_TEXT_VALUE(reader.value()),
2095 GRN_TEXT_LEN(reader.value())));
2096 case GRN_JSON_VALUE_ARRAY:
2097 {
2098 jsoncons::json array(jsoncons::json_array_arg);
2099 size_t n = reader.size();
2100 for (size_t i = 0; i < n; ++i) {
2101 if (reader.next() != GRN_SUCCESS) {
2102 break;
2103 }
2104 array.push_back(convert(reader));
2105 }
2106 return array;
2107 }
2108 case GRN_JSON_VALUE_OBJECT:
2109 {
2110 jsoncons::json object;
2111 size_t n = reader.size();
2112 for (size_t i = 0; i < n; ++i) {
2113 if (reader.next() != GRN_SUCCESS) {
2114 break;
2115 }
2116 std::string key(GRN_TEXT_VALUE(reader.value()),
2117 GRN_TEXT_LEN(reader.value()));
2118 if (reader.next() != GRN_SUCCESS) {
2119 break;
2120 }
2121 auto value = convert(reader);
2122 object.insert_or_assign(key, value);
2123 }
2124 return object;
2125 }
2126 default:
2127 return jsoncons::json::null();
2128 }
2129 }
2130
2131 void
2132 push_value(const jsoncons::json &value)
2133 {
2134 // Scalars are only supported for now.
2135 if (value.is_bool()) {
2136 auto bool_value = value.as_bool();
2137 grn_vector_add_element_float(
2138 ctx_,
2139 values_,
2140 reinterpret_cast<const char *>(&bool_value),
2141 sizeof(bool_value),
2142 0.0,
2143 GRN_DB_BOOL);
2144 } else if (value.is_int64()) {
2145 auto int64 = value.as_integer<int64_t>();
2146 grn_vector_add_element_float(ctx_,
2147 values_,
2148 reinterpret_cast<const char *>(&int64),
2149 sizeof(int64),
2150 0.0,
2151 GRN_DB_INT64);
2152 } else if (value.is_double()) {
2153 auto double_value = value.as_double();
2154 grn_vector_add_element_float(
2155 ctx_,
2156 values_,
2157 reinterpret_cast<const char *>(&double_value),
2158 sizeof(double_value),
2159 0.0,
2160 GRN_DB_FLOAT);
2161 } else if (value.is_string()) {
2162 auto string_view = value.as_string_view();
2163 grn_vector_add_element_float(ctx_,
2164 values_,
2165 string_view.data(),
2166 string_view.size(),
2167 0.0,
2168 GRN_DB_TEXT);
2169 }
2170 }
2171 };
2172 #endif
2173
2174 } // namespace
2175
2176 extern "C" {
2177 struct _grn_json_parser {
2178 #ifdef GRN_WITH_SIMDJSON
2179 JSONParser *parser;
2180 #else
2181 void *parser;
2182 #endif
2183 };
2184
2185 grn_json_parser *
2186 grn_json_parser_open(grn_ctx *ctx, grn_obj *input, grn_obj *output)
2187 {
2188 GRN_API_ENTER;
2189 grn_json_parser *parser = nullptr;
2190 #ifdef GRN_WITH_SIMDJSON
2191 parser = static_cast<grn_json_parser *>(GRN_MALLOC(sizeof(grn_json_parser)));
2192 if (!parser) {
2193 GRN_API_RETURN(nullptr);
2194 }
2195 parser->parser = new JSONParser(ctx, input, output);
2196 #else
2197 const char *tag = "[json-parser][open]";
2198 ERR(GRN_FUNCTION_NOT_IMPLEMENTED, "%s simdjson isn't enabled", tag);
2199 #endif
2200 GRN_API_RETURN(parser);
2201 }
2202
2203 grn_rc
2204 grn_json_parser_close(grn_ctx *ctx, grn_json_parser *parser)
2205 {
2206 GRN_API_ENTER;
2207 #ifdef GRN_WITH_SIMDJSON
2208 if (parser) {
2209 delete parser->parser;
2210 GRN_FREE(parser);
2211 }
2212 #endif
2213 GRN_API_RETURN(ctx->rc);
2214 }
2215
2216 grn_rc
2217 grn_json_parser_parse(grn_ctx *ctx, grn_json_parser *parser)
2218 {
2219 GRN_API_ENTER;
2220 #ifdef GRN_WITH_SIMDJSON
2221 parser->parser->parse();
2222 #else
2223 const char *tag = "[json-parser][parse]";
2224 ERR(GRN_FUNCTION_NOT_IMPLEMENTED, "%s simdjson isn't enabled", tag);
2225 #endif
2226 GRN_API_RETURN(ctx->rc);
2227 }
2228
2229 struct _grn_json_reader {
2230 JSONReader *reader;
2231 };
2232
2233 grn_json_reader *
2234 grn_json_reader_open(grn_ctx *ctx, grn_obj *json)
2235 {
2236 GRN_API_ENTER;
2237 auto reader =
2238 static_cast<grn_json_reader *>(GRN_MALLOC(sizeof(grn_json_reader)));
2239 if (!reader) {
2240 GRN_API_RETURN(nullptr);
2241 }
2242 reader->reader = new JSONReader(ctx, json);
2243 GRN_API_RETURN(reader);
2244 }
2245
2246 grn_rc
2247 grn_json_reader_close(grn_ctx *ctx, grn_json_reader *reader)
2248 {
2249 GRN_API_ENTER;
2250 if (reader) {
2251 delete reader->reader;
2252 GRN_FREE(reader);
2253 }
2254 GRN_API_RETURN(ctx->rc);
2255 }
2256
2257 grn_rc
2258 grn_json_reader_next(grn_ctx *ctx, grn_json_reader *reader)
2259 {
2260 GRN_API_ENTER;
2261 reader->reader->next();
2262 GRN_API_RETURN(ctx->rc);
2263 }
2264
2265 grn_json_value_type
2266 grn_json_reader_get_type(grn_ctx *ctx, grn_json_reader *reader)
2267 {
2268 GRN_API_ENTER;
2269 grn_json_value_type type = reader->reader->type();
2270 GRN_API_RETURN(type);
2271 }
2272
2273 grn_obj *
2274 grn_json_reader_get_value(grn_ctx *ctx, grn_json_reader *reader)
2275 {
2276 GRN_API_ENTER;
2277 grn_obj *value = reader->reader->value();
2278 GRN_API_RETURN(value);
2279 }
2280
2281 size_t
2282 grn_json_reader_get_size(grn_ctx *ctx, grn_json_reader *reader)
2283 {
2284 GRN_API_ENTER;
2285 size_t size = reader->reader->size();
2286 GRN_API_RETURN(size);
2287 }
2288
2289 const char *
2290 grn_json_value_type_to_string(grn_json_value_type type)
2291 {
2292 switch (type) {
2293 case GRN_JSON_VALUE_NULL:
2294 return "null";
2295 case GRN_JSON_VALUE_FALSE:
2296 return "false";
2297 case GRN_JSON_VALUE_TRUE:
2298 return "true";
2299 case GRN_JSON_VALUE_INT64:
2300 return "int64";
2301 case GRN_JSON_VALUE_FLOAT:
2302 return "float";
2303 case GRN_JSON_VALUE_STRING:
2304 return "string";
2305 case GRN_JSON_VALUE_ARRAY:
2306 return "array";
2307 case GRN_JSON_VALUE_OBJECT:
2308 return "object";
2309 default:
2310 return "unknown";
2311 }
2312 }
2313
2314 grn_rc
2315 grn_json_to_string(grn_ctx *ctx, grn_obj *json, grn_obj *buffer)
2316 {
2317 GRN_API_ENTER;
2318 JSONStringifier stringifier(ctx, json, buffer);
2319 stringifier.stringify();
2320 GRN_API_RETURN(ctx->rc);
2321 }
2322
2323 struct _grn_json_path {
2324 #ifdef GRN_WITH_JSONCONS
2325 json_path_expression *expr;
2326 #else
2327 void *expr;
2328 #endif
2329 };
2330
2331 grn_json_path *
2332 grn_json_path_open(grn_ctx *ctx, const char *raw_path, int64_t raw_path_length)
2333 {
2334 GRN_API_ENTER;
2335 const char *tag = "[json-path][open]";
2336 #ifdef GRN_WITH_JSONCONS
2337 auto path = static_cast<grn_json_path *>(GRN_MALLOC(sizeof(grn_json_path)));
2338 if (!path) {
2339 GRN_API_RETURN(nullptr);
2340 }
2341 if (raw_path_length < 0) {
2342 raw_path_length = strlen(raw_path);
2343 }
2344 try {
2345 path->expr = new json_path_expression(
2346 jsoncons::jsonpath::make_expression<jsoncons::json>(
2347 std::string_view(raw_path, raw_path_length)));
2348 } catch (const jsoncons::json_exception &error) {
2349 ERR(GRN_INVALID_ARGUMENT,
2350 "%s invalid JSONPath: %s: <%.*s>",
2351 tag,
2352 error.what(),
2353 static_cast<int>(raw_path_length),
2354 raw_path);
2355 GRN_FREE(path);
2356 path = nullptr;
2357 }
2358 GRN_API_RETURN(path);
2359 #else
2360 ERR(GRN_FUNCTION_NOT_IMPLEMENTED, "%s jsoncons isn't enabled", tag);
2361 GRN_API_RETURN(NULL);
2362 #endif
2363 }
2364
2365 grn_rc
2366 grn_json_path_close(grn_ctx *ctx, grn_json_path *path)
2367 {
2368 GRN_API_ENTER;
2369 #ifdef GRN_WITH_JSONCONS
2370 if (path) {
2371 delete path->expr;
2372 GRN_FREE(path);
2373 }
2374 #else
2375 const char *tag = "[json-path][close]";
2376 ERR(GRN_FUNCTION_NOT_IMPLEMENTED, "%s jsoncons isn't enabled", tag);
2377 #endif
2378 GRN_API_RETURN(ctx->rc);
2379 }
2380
2381 grn_rc
2382 grn_json_extract(grn_ctx *ctx,
2383 grn_obj *json,
2384 grn_json_path *path,
2385 grn_obj *values)
2386 {
2387 GRN_API_ENTER;
2388 #ifdef GRN_WITH_JSONCONS
2389 JSONExtractor extractor(ctx, json, path->expr, values);
2390 extractor.extract();
2391 #else
2392 const char *tag = "[json][extract]";
2393 ERR(GRN_FUNCTION_NOT_IMPLEMENTED, "%s jsoncons isn't enabled", tag);
2394 #endif
2395 GRN_API_RETURN(ctx->rc);
2396 }
2397 }