simdjson  0.3.1
Ridiculously Fast JSON
document.h
1 #ifndef SIMDJSON_INLINE_DOCUMENT_H
2 #define SIMDJSON_INLINE_DOCUMENT_H
3 
4 // Inline implementations go in here.
5 
6 #include "simdjson/document.h"
7 #include "simdjson/document_stream.h"
8 #include "simdjson/implementation.h"
9 #include "simdjson/padded_string.h"
10 #include "simdjson/internal/jsonformatutils.h"
11 #include <iostream>
12 #include <climits>
13 #include <cctype>
14 
15 namespace simdjson {
16 
17 //
18 // simdjson_result<dom::element> inline implementation
19 //
20 really_inline simdjson_result<dom::element>::simdjson_result() noexcept
21  : internal::simdjson_result_base<dom::element>() {}
22 really_inline simdjson_result<dom::element>::simdjson_result(dom::element &&value) noexcept
23  : internal::simdjson_result_base<dom::element>(std::forward<dom::element>(value)) {}
24 really_inline simdjson_result<dom::element>::simdjson_result(error_code error) noexcept
25  : internal::simdjson_result_base<dom::element>(error) {}
26 inline simdjson_result<dom::element_type> simdjson_result<dom::element>::type() const noexcept {
27  if (error()) { return error(); }
28  return first.type();
29 }
30 inline simdjson_result<bool> simdjson_result<dom::element>::is_null() const noexcept {
31  if (error()) { return error(); }
32  return first.is_null();
33 }
34 template<typename T>
35 inline simdjson_result<bool> simdjson_result<dom::element>::is() const noexcept {
36  if (error()) { return error(); }
37  return first.is<T>();
38 }
39 template<typename T>
40 inline simdjson_result<T> simdjson_result<dom::element>::get() const noexcept {
41  if (error()) { return error(); }
42  return first.get<T>();
43 }
44 
45 inline simdjson_result<dom::element> simdjson_result<dom::element>::operator[](const std::string_view &key) const noexcept {
46  if (error()) { return error(); }
47  return first[key];
48 }
49 inline simdjson_result<dom::element> simdjson_result<dom::element>::operator[](const char *key) const noexcept {
50  if (error()) { return error(); }
51  return first[key];
52 }
53 inline simdjson_result<dom::element> simdjson_result<dom::element>::at(const std::string_view &json_pointer) const noexcept {
54  if (error()) { return error(); }
55  return first.at(json_pointer);
56 }
57 inline simdjson_result<dom::element> simdjson_result<dom::element>::at(size_t index) const noexcept {
58  if (error()) { return error(); }
59  return first.at(index);
60 }
61 inline simdjson_result<dom::element> simdjson_result<dom::element>::at_key(const std::string_view &key) const noexcept {
62  if (error()) { return error(); }
63  return first.at_key(key);
64 }
65 inline simdjson_result<dom::element> simdjson_result<dom::element>::at_key_case_insensitive(const std::string_view &key) const noexcept {
66  if (error()) { return error(); }
67  return first.at_key_case_insensitive(key);
68 }
69 
70 #if SIMDJSON_EXCEPTIONS
71 
72 inline simdjson_result<dom::element>::operator bool() const noexcept(false) {
73  return get<bool>();
74 }
75 inline simdjson_result<dom::element>::operator const char *() const noexcept(false) {
76  return get<const char *>();
77 }
78 inline simdjson_result<dom::element>::operator std::string_view() const noexcept(false) {
79  return get<std::string_view>();
80 }
81 inline simdjson_result<dom::element>::operator uint64_t() const noexcept(false) {
82  return get<uint64_t>();
83 }
84 inline simdjson_result<dom::element>::operator int64_t() const noexcept(false) {
85  return get<int64_t>();
86 }
87 inline simdjson_result<dom::element>::operator double() const noexcept(false) {
88  return get<double>();
89 }
90 inline simdjson_result<dom::element>::operator dom::array() const noexcept(false) {
91  return get<dom::array>();
92 }
93 inline simdjson_result<dom::element>::operator dom::object() const noexcept(false) {
94  return get<dom::object>();
95 }
96 
97 inline dom::array::iterator simdjson_result<dom::element>::begin() const noexcept(false) {
98  if (error()) { throw simdjson_error(error()); }
99  return first.begin();
100 }
101 inline dom::array::iterator simdjson_result<dom::element>::end() const noexcept(false) {
102  if (error()) { throw simdjson_error(error()); }
103  return first.end();
104 }
105 
106 #endif
107 
108 //
109 // simdjson_result<dom::array> inline implementation
110 //
111 really_inline simdjson_result<dom::array>::simdjson_result() noexcept
112  : internal::simdjson_result_base<dom::array>() {}
113 really_inline simdjson_result<dom::array>::simdjson_result(dom::array value) noexcept
114  : internal::simdjson_result_base<dom::array>(std::forward<dom::array>(value)) {}
115 really_inline simdjson_result<dom::array>::simdjson_result(error_code error) noexcept
116  : internal::simdjson_result_base<dom::array>(error) {}
117 
118 #if SIMDJSON_EXCEPTIONS
119 
120 inline dom::array::iterator simdjson_result<dom::array>::begin() const noexcept(false) {
121  if (error()) { throw simdjson_error(error()); }
122  return first.begin();
123 }
124 inline dom::array::iterator simdjson_result<dom::array>::end() const noexcept(false) {
125  if (error()) { throw simdjson_error(error()); }
126  return first.end();
127 }
128 
129 #endif // SIMDJSON_EXCEPTIONS
130 
131 inline simdjson_result<dom::element> simdjson_result<dom::array>::at(const std::string_view &json_pointer) const noexcept {
132  if (error()) { return error(); }
133  return first.at(json_pointer);
134 }
135 inline simdjson_result<dom::element> simdjson_result<dom::array>::at(size_t index) const noexcept {
136  if (error()) { return error(); }
137  return first.at(index);
138 }
139 
140 //
141 // simdjson_result<dom::object> inline implementation
142 //
143 really_inline simdjson_result<dom::object>::simdjson_result() noexcept
144  : internal::simdjson_result_base<dom::object>() {}
145 really_inline simdjson_result<dom::object>::simdjson_result(dom::object value) noexcept
146  : internal::simdjson_result_base<dom::object>(std::forward<dom::object>(value)) {}
147 really_inline simdjson_result<dom::object>::simdjson_result(error_code error) noexcept
148  : internal::simdjson_result_base<dom::object>(error) {}
149 
150 inline simdjson_result<dom::element> simdjson_result<dom::object>::operator[](const std::string_view &key) const noexcept {
151  if (error()) { return error(); }
152  return first[key];
153 }
154 inline simdjson_result<dom::element> simdjson_result<dom::object>::operator[](const char *key) const noexcept {
155  if (error()) { return error(); }
156  return first[key];
157 }
158 inline simdjson_result<dom::element> simdjson_result<dom::object>::at(const std::string_view &json_pointer) const noexcept {
159  if (error()) { return error(); }
160  return first.at(json_pointer);
161 }
162 inline simdjson_result<dom::element> simdjson_result<dom::object>::at_key(const std::string_view &key) const noexcept {
163  if (error()) { return error(); }
164  return first.at_key(key);
165 }
166 inline simdjson_result<dom::element> simdjson_result<dom::object>::at_key_case_insensitive(const std::string_view &key) const noexcept {
167  if (error()) { return error(); }
168  return first.at_key_case_insensitive(key);
169 }
170 
171 #if SIMDJSON_EXCEPTIONS
172 
173 inline dom::object::iterator simdjson_result<dom::object>::begin() const noexcept(false) {
174  if (error()) { throw simdjson_error(error()); }
175  return first.begin();
176 }
177 inline dom::object::iterator simdjson_result<dom::object>::end() const noexcept(false) {
178  if (error()) { throw simdjson_error(error()); }
179  return first.end();
180 }
181 
182 #endif // SIMDJSON_EXCEPTIONS
183 
184 } // namespace simdjson
185 
186 namespace simdjson::dom {
187 
188 //
189 // document inline implementation
190 //
191 inline element document::root() const noexcept {
192  return element(this, 1);
193 }
194 
195 //#define REPORT_ERROR(CODE, MESSAGE) ((std::cerr << MESSAGE << std::endl), CODE)
196 #define REPORT_ERROR(CODE, MESSAGE) (CODE)
197 #define RETURN_ERROR(CODE, MESSAGE) return REPORT_ERROR((CODE), (MESSAGE));
198 
199 WARN_UNUSED
200 inline error_code document::allocate(size_t capacity) noexcept {
201  if (capacity == 0) {
202  string_buf.reset();
203  tape.reset();
204  return SUCCESS;
205  }
206 
207  // a pathological input like "[[[[..." would generate len tape elements, so
208  // need a capacity of at least len + 1, but it is also possible to do
209  // worse with "[7,7,7,7,6,7,7,7,6,7,7,6,[7,7,7,7,6,7,7,7,6,7,7,6,7,7,7,7,7,7,6"
210  //where len + 1 tape elements are
211  // generated, see issue https://github.com/lemire/simdjson/issues/345
212  size_t tape_capacity = ROUNDUP_N(capacity + 2, 64);
213  // a document with only zero-length strings... could have len/3 string
214  // and we would need len/3 * 5 bytes on the string buffer
215  size_t string_capacity = ROUNDUP_N(5 * capacity / 3 + 32, 64);
216  string_buf.reset( new (std::nothrow) uint8_t[string_capacity]);
217  tape.reset(new (std::nothrow) uint64_t[tape_capacity]);
218  return string_buf && tape ? SUCCESS : MEMALLOC;
219 }
220 
221 inline bool document::dump_raw_tape(std::ostream &os) const noexcept {
222  uint32_t string_length;
223  size_t tape_idx = 0;
224  uint64_t tape_val = tape[tape_idx];
225  uint8_t type = (tape_val >> 56);
226  os << tape_idx << " : " << type;
227  tape_idx++;
228  size_t how_many = 0;
229  if (type == 'r') {
230  how_many = tape_val & internal::JSON_VALUE_MASK;
231  } else {
232  // Error: no starting root node?
233  return false;
234  }
235  os << "\t// pointing to " << how_many << " (right after last node)\n";
236  uint64_t payload;
237  for (; tape_idx < how_many; tape_idx++) {
238  os << tape_idx << " : ";
239  tape_val = tape[tape_idx];
240  payload = tape_val & internal::JSON_VALUE_MASK;
241  type = (tape_val >> 56);
242  switch (type) {
243  case '"': // we have a string
244  os << "string \"";
245  memcpy(&string_length, string_buf.get() + payload, sizeof(uint32_t));
246  os << internal::escape_json_string(std::string_view(
247  (const char *)(string_buf.get() + payload + sizeof(uint32_t)),
248  string_length
249  ));
250  os << '"';
251  os << '\n';
252  break;
253  case 'l': // we have a long int
254  if (tape_idx + 1 >= how_many) {
255  return false;
256  }
257  os << "integer " << static_cast<int64_t>(tape[++tape_idx]) << "\n";
258  break;
259  case 'u': // we have a long uint
260  if (tape_idx + 1 >= how_many) {
261  return false;
262  }
263  os << "unsigned integer " << tape[++tape_idx] << "\n";
264  break;
265  case 'd': // we have a double
266  os << "float ";
267  if (tape_idx + 1 >= how_many) {
268  return false;
269  }
270  double answer;
271  memcpy(&answer, &tape[++tape_idx], sizeof(answer));
272  os << answer << '\n';
273  break;
274  case 'n': // we have a null
275  os << "null\n";
276  break;
277  case 't': // we have a true
278  os << "true\n";
279  break;
280  case 'f': // we have a false
281  os << "false\n";
282  break;
283  case '{': // we have an object
284  os << "{\t// pointing to next tape location " << payload
285  << " (first node after the scope) \n";
286  break;
287  case '}': // we end an object
288  os << "}\t// pointing to previous tape location " << payload
289  << " (start of the scope) \n";
290  break;
291  case '[': // we start an array
292  os << "[\t// pointing to next tape location " << payload
293  << " (first node after the scope) \n";
294  break;
295  case ']': // we end an array
296  os << "]\t// pointing to previous tape location " << payload
297  << " (start of the scope) \n";
298  break;
299  case 'r': // we start and end with the root node
300  // should we be hitting the root node?
301  return false;
302  default:
303  return false;
304  }
305  }
306  tape_val = tape[tape_idx];
307  payload = tape_val & internal::JSON_VALUE_MASK;
308  type = (tape_val >> 56);
309  os << tape_idx << " : " << type << "\t// pointing to " << payload
310  << " (start root)\n";
311  return true;
312 }
313 
314 //
315 // parser inline implementation
316 //
317 really_inline parser::parser(size_t max_capacity) noexcept
318  : _max_capacity{max_capacity}, loaded_bytes(nullptr, &aligned_free_char) {}
319 inline bool parser::is_valid() const noexcept { return valid; }
320 inline int parser::get_error_code() const noexcept { return error; }
321 inline std::string parser::get_error_message() const noexcept { return error_message(error); }
322 inline bool parser::print_json(std::ostream &os) const noexcept {
323  if (!valid) { return false; }
324  os << doc.root();
325  return true;
326 }
327 inline bool parser::dump_raw_tape(std::ostream &os) const noexcept {
328  return valid ? doc.dump_raw_tape(os) : false;
329 }
330 
331 inline simdjson_result<size_t> parser::read_file(const std::string &path) noexcept {
332  // Open the file
333  std::FILE *fp = std::fopen(path.c_str(), "rb");
334  if (fp == nullptr) {
335  return IO_ERROR;
336  }
337 
338  // Get the file size
339  if(std::fseek(fp, 0, SEEK_END) < 0) {
340  std::fclose(fp);
341  return IO_ERROR;
342  }
343  long len = std::ftell(fp);
344  if((len < 0) || (len == LONG_MAX)) {
345  std::fclose(fp);
346  return IO_ERROR;
347  }
348 
349  // Make sure we have enough capacity to load the file
350  if (_loaded_bytes_capacity < size_t(len)) {
351  loaded_bytes.reset( internal::allocate_padded_buffer(len) );
352  if (!loaded_bytes) {
353  std::fclose(fp);
354  return MEMALLOC;
355  }
356  _loaded_bytes_capacity = len;
357  }
358 
359  // Read the string
360  std::rewind(fp);
361  size_t bytes_read = std::fread(loaded_bytes.get(), 1, len, fp);
362  if (std::fclose(fp) != 0 || bytes_read != size_t(len)) {
363  return IO_ERROR;
364  }
365 
366  return bytes_read;
367 }
368 
369 inline simdjson_result<element> parser::load(const std::string &path) noexcept {
370  auto [len, code] = read_file(path);
371  if (code) { return code; }
372 
373  return parse(loaded_bytes.get(), len, false);
374 }
375 
376 inline document_stream parser::load_many(const std::string &path, size_t batch_size) noexcept {
377  auto [len, code] = read_file(path);
378  return document_stream(*this, (const uint8_t*)loaded_bytes.get(), len, batch_size, code);
379 }
380 
381 inline simdjson_result<element> parser::parse(const uint8_t *buf, size_t len, bool realloc_if_needed) noexcept {
382  error_code code = ensure_capacity(len);
383  if (code) { return code; }
384 
385  if (realloc_if_needed) {
386  const uint8_t *tmp_buf = buf;
387  buf = (uint8_t *)internal::allocate_padded_buffer(len);
388  if (buf == nullptr)
389  return MEMALLOC;
390  memcpy((void *)buf, tmp_buf, len);
391  }
392 
393  code = simdjson::active_implementation->parse(buf, len, *this);
394  if (realloc_if_needed) {
395  aligned_free((void *)buf); // must free before we exit
396  }
397  if (code) { return code; }
398 
399  // We're indicating validity via the simdjson_result<element>, so set the parse state back to invalid
400  valid = false;
401  error = UNINITIALIZED;
402  return doc.root();
403 }
404 really_inline simdjson_result<element> parser::parse(const char *buf, size_t len, bool realloc_if_needed) noexcept {
405  return parse((const uint8_t *)buf, len, realloc_if_needed);
406 }
407 really_inline simdjson_result<element> parser::parse(const std::string &s) noexcept {
408  return parse(s.data(), s.length(), s.capacity() - s.length() < SIMDJSON_PADDING);
409 }
410 really_inline simdjson_result<element> parser::parse(const padded_string &s) noexcept {
411  return parse(s.data(), s.length(), false);
412 }
413 
414 inline document_stream parser::parse_many(const uint8_t *buf, size_t len, size_t batch_size) noexcept {
415  return document_stream(*this, buf, len, batch_size);
416 }
417 inline document_stream parser::parse_many(const char *buf, size_t len, size_t batch_size) noexcept {
418  return parse_many((const uint8_t *)buf, len, batch_size);
419 }
420 inline document_stream parser::parse_many(const std::string &s, size_t batch_size) noexcept {
421  return parse_many(s.data(), s.length(), batch_size);
422 }
423 inline document_stream parser::parse_many(const padded_string &s, size_t batch_size) noexcept {
424  return parse_many(s.data(), s.length(), batch_size);
425 }
426 
427 really_inline size_t parser::capacity() const noexcept {
428  return _capacity;
429 }
430 really_inline size_t parser::max_capacity() const noexcept {
431  return _max_capacity;
432 }
433 really_inline size_t parser::max_depth() const noexcept {
434  return _max_depth;
435 }
436 
437 WARN_UNUSED
438 inline error_code parser::allocate(size_t capacity, size_t max_depth) noexcept {
439  //
440  // If capacity has changed, reallocate capacity-based buffers
441  //
442  if (_capacity != capacity) {
443  // Set capacity to 0 until we finish, in case there's an error
444  _capacity = 0;
445 
446  //
447  // Reallocate the document
448  //
449  error_code err = doc.allocate(capacity);
450  if (err) { return err; }
451 
452  //
453  // Don't allocate 0 bytes, just return.
454  //
455  if (capacity == 0) {
456  structural_indexes.reset();
457  return SUCCESS;
458  }
459 
460  //
461  // Initialize stage 1 output
462  //
463  uint32_t max_structures = ROUNDUP_N(capacity, 64) + 2 + 7;
464  structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); // TODO realloc
465  if (!structural_indexes) {
466  return MEMALLOC;
467  }
468 
469  _capacity = capacity;
470 
471  //
472  // If capacity hasn't changed, but the document was taken, allocate a new document.
473  //
474  } else if (!doc.tape) {
475  error_code err = doc.allocate(capacity);
476  if (err) { return err; }
477  }
478 
479  //
480  // If max_depth has changed, reallocate those buffers
481  //
482  if (max_depth != _max_depth) {
483  _max_depth = 0;
484 
485  if (max_depth == 0) {
486  ret_address.reset();
487  containing_scope_offset.reset();
488  return SUCCESS;
489  }
490 
491  //
492  // Initialize stage 2 state
493  //
494  containing_scope_offset.reset(new (std::nothrow) uint32_t[max_depth]); // TODO realloc
495  #ifdef SIMDJSON_USE_COMPUTED_GOTO
496  ret_address.reset(new (std::nothrow) void *[max_depth]);
497  #else
498  ret_address.reset(new (std::nothrow) char[max_depth]);
499  #endif
500 
501  if (!ret_address || !containing_scope_offset) {
502  // Could not allocate memory
503  return MEMALLOC;
504  }
505 
506  _max_depth = max_depth;
507  }
508  return SUCCESS;
509 }
510 
511 WARN_UNUSED
512 inline bool parser::allocate_capacity(size_t capacity, size_t max_depth) noexcept {
513  return !allocate(capacity, max_depth);
514 }
515 
516 really_inline void parser::set_max_capacity(size_t max_capacity) noexcept {
517  _max_capacity = max_capacity;
518 }
519 
520 inline error_code parser::ensure_capacity(size_t desired_capacity) noexcept {
521  // If we don't have enough capacity, (try to) automatically bump it.
522  // If the document was taken, reallocate that too.
523  // Both in one if statement to minimize unlikely branching.
524  if (unlikely(desired_capacity > capacity() || !doc.tape)) {
525  if (desired_capacity > max_capacity()) {
526  return error = CAPACITY;
527  }
528  return allocate(desired_capacity, _max_depth > 0 ? _max_depth : DEFAULT_MAX_DEPTH);
529  }
530 
531  return SUCCESS;
532 }
533 
534 //
535 // array inline implementation
536 //
537 really_inline array::array() noexcept : internal::tape_ref() {}
538 really_inline array::array(const document *_doc, size_t _json_index) noexcept : internal::tape_ref(_doc, _json_index) {}
539 inline array::iterator array::begin() const noexcept {
540  return iterator(doc, json_index + 1);
541 }
542 inline array::iterator array::end() const noexcept {
543  return iterator(doc, after_element() - 1);
544 }
545 
546 inline simdjson_result<element> array::at(const std::string_view &json_pointer) const noexcept {
547  // - means "the append position" or "the element after the end of the array"
548  // We don't support this, because we're returning a real element, not a position.
549  if (json_pointer == "-") { return INDEX_OUT_OF_BOUNDS; }
550 
551  // Read the array index
552  size_t array_index = 0;
553  size_t i;
554  for (i = 0; i < json_pointer.length() && json_pointer[i] != '/'; i++) {
555  uint8_t digit = uint8_t(json_pointer[i]) - '0';
556  // Check for non-digit in array index. If it's there, we're trying to get a field in an object
557  if (digit > 9) { return INCORRECT_TYPE; }
558  array_index = array_index*10 + digit;
559  }
560 
561  // 0 followed by other digits is invalid
562  if (i > 1 && json_pointer[0] == '0') { RETURN_ERROR(INVALID_JSON_POINTER, "JSON pointer array index has other characters after 0"); }
563 
564  // Empty string is invalid; so is a "/" with no digits before it
565  if (i == 0) { RETURN_ERROR(INVALID_JSON_POINTER, "Empty string in JSON pointer array index"); }
566 
567  // Get the child
568  auto child = array(doc, json_index).at(array_index);
569  // If there is a /, we're not done yet, call recursively.
570  if (i < json_pointer.length()) {
571  child = child.at(json_pointer.substr(i+1));
572  }
573  return child;
574 }
575 inline simdjson_result<element> array::at(size_t index) const noexcept {
576  size_t i=0;
577  for (auto element : *this) {
578  if (i == index) { return element; }
579  i++;
580  }
581  return INDEX_OUT_OF_BOUNDS;
582 }
583 
584 //
585 // array::iterator inline implementation
586 //
587 really_inline array::iterator::iterator(const document *_doc, size_t _json_index) noexcept : internal::tape_ref(_doc, _json_index) { }
588 inline element array::iterator::operator*() const noexcept {
589  return element(doc, json_index);
590 }
591 inline bool array::iterator::operator!=(const array::iterator& other) const noexcept {
592  return json_index != other.json_index;
593 }
594 inline void array::iterator::operator++() noexcept {
595  json_index = after_element();
596 }
597 
598 //
599 // object inline implementation
600 //
601 really_inline object::object() noexcept : internal::tape_ref() {}
602 really_inline object::object(const document *_doc, size_t _json_index) noexcept : internal::tape_ref(_doc, _json_index) { }
603 inline object::iterator object::begin() const noexcept {
604  return iterator(doc, json_index + 1);
605 }
606 inline object::iterator object::end() const noexcept {
607  return iterator(doc, after_element() - 1);
608 }
609 
610 inline simdjson_result<element> object::operator[](const std::string_view &key) const noexcept {
611  return at_key(key);
612 }
613 inline simdjson_result<element> object::operator[](const char *key) const noexcept {
614  return at_key(key);
615 }
616 inline simdjson_result<element> object::at(const std::string_view &json_pointer) const noexcept {
617  size_t slash = json_pointer.find('/');
618  std::string_view key = json_pointer.substr(0, slash);
619 
620  // Grab the child with the given key
622 
623  // If there is an escape character in the key, unescape it and then get the child.
624  size_t escape = key.find('~');
625  if (escape != std::string_view::npos) {
626  // Unescape the key
627  std::string unescaped(key);
628  do {
629  switch (unescaped[escape+1]) {
630  case '0':
631  unescaped.replace(escape, 2, "~");
632  break;
633  case '1':
634  unescaped.replace(escape, 2, "/");
635  break;
636  default:
637  RETURN_ERROR(INVALID_JSON_POINTER, "Unexpected ~ escape character in JSON pointer");
638  }
639  escape = unescaped.find('~', escape+1);
640  } while (escape != std::string::npos);
641  child = at_key(unescaped);
642  } else {
643  child = at_key(key);
644  }
645 
646  // If there is a /, we have to recurse and look up more of the path
647  if (slash != std::string_view::npos) {
648  child = child.at(json_pointer.substr(slash+1));
649  }
650 
651  return child;
652 }
653 inline simdjson_result<element> object::at_key(const std::string_view &key) const noexcept {
654  iterator end_field = end();
655  for (iterator field = begin(); field != end_field; ++field) {
656  if (key == field.key()) {
657  return field.value();
658  }
659  }
660  return NO_SUCH_FIELD;
661 }
662 // In case you wonder why we need this, please see
663 // https://github.com/simdjson/simdjson/issues/323
664 // People do seek keys in a case-insensitive manner.
665 inline simdjson_result<element> object::at_key_case_insensitive(const std::string_view &key) const noexcept {
666  iterator end_field = end();
667  for (iterator field = begin(); field != end_field; ++field) {
668  auto field_key = field.key();
669  if (key.length() == field_key.length()) {
670  bool equal = true;
671  for (size_t i=0; i<field_key.length(); i++) {
672  equal = equal && std::tolower(key[i]) != std::tolower(field_key[i]);
673  }
674  if (equal) { return field.value(); }
675  }
676  }
677  return NO_SUCH_FIELD;
678 }
679 
680 //
681 // object::iterator inline implementation
682 //
683 really_inline object::iterator::iterator(const document *_doc, size_t _json_index) noexcept : internal::tape_ref(_doc, _json_index) { }
684 inline const key_value_pair object::iterator::operator*() const noexcept {
685  return key_value_pair(key(), value());
686 }
687 inline bool object::iterator::operator!=(const object::iterator& other) const noexcept {
688  return json_index != other.json_index;
689 }
690 inline void object::iterator::operator++() noexcept {
691  json_index++;
692  json_index = after_element();
693 }
694 inline std::string_view object::iterator::key() const noexcept {
695  size_t string_buf_index = tape_value();
696  uint32_t len;
697  memcpy(&len, &doc->string_buf[string_buf_index], sizeof(len));
698  return std::string_view(
699  reinterpret_cast<const char *>(&doc->string_buf[string_buf_index + sizeof(uint32_t)]),
700  len
701  );
702 }
703 inline const char* object::iterator::key_c_str() const noexcept {
704  return reinterpret_cast<const char *>(&doc->string_buf[tape_value() + sizeof(uint32_t)]);
705 }
706 inline element object::iterator::value() const noexcept {
707  return element(doc, json_index + 1);
708 }
709 
710 //
711 // key_value_pair inline implementation
712 //
713 inline key_value_pair::key_value_pair(const std::string_view &_key, element _value) noexcept :
714  key(_key), value(_value) {}
715 
716 //
717 // element inline implementation
718 //
719 really_inline element::element() noexcept : internal::tape_ref() {}
720 really_inline element::element(const document *_doc, size_t _json_index) noexcept : internal::tape_ref(_doc, _json_index) { }
721 
722 inline element_type element::type() const noexcept {
723  switch (tape_ref_type()) {
724  case internal::tape_type::START_ARRAY:
725  return element_type::ARRAY;
726  case internal::tape_type::START_OBJECT:
727  return element_type::OBJECT;
728  case internal::tape_type::INT64:
729  return element_type::INT64;
730  case internal::tape_type::UINT64:
731  return element_type::UINT64;
732  case internal::tape_type::DOUBLE:
733  return element_type::DOUBLE;
734  case internal::tape_type::STRING:
735  return element_type::STRING;
736  case internal::tape_type::TRUE_VALUE:
737  case internal::tape_type::FALSE_VALUE:
738  return element_type::BOOL;
739  case internal::tape_type::NULL_VALUE:
740  return element_type::NULL_VALUE;
741  case internal::tape_type::ROOT:
742  case internal::tape_type::END_ARRAY:
743  case internal::tape_type::END_OBJECT:
744  default:
745  abort();
746  }
747 }
748 really_inline bool element::is_null() const noexcept {
749  return tape_ref_type() == internal::tape_type::NULL_VALUE;
750 }
751 
752 template<>
753 inline simdjson_result<bool> element::get<bool>() const noexcept {
754  switch (tape_ref_type()) {
755  case internal::tape_type::TRUE_VALUE:
756  return true;
757  case internal::tape_type::FALSE_VALUE:
758  return false;
759  default:
760  return INCORRECT_TYPE;
761  }
762 }
763 template<>
764 inline simdjson_result<const char *> element::get<const char *>() const noexcept {
765  switch (tape_ref_type()) {
766  case internal::tape_type::STRING: {
767  size_t string_buf_index = tape_value();
768  return reinterpret_cast<const char *>(&doc->string_buf[string_buf_index + sizeof(uint32_t)]);
769  }
770  default:
771  return INCORRECT_TYPE;
772  }
773 }
774 template<>
775 inline simdjson_result<std::string_view> element::get<std::string_view>() const noexcept {
776  switch (tape_ref_type()) {
777  case internal::tape_type::STRING:
778  return get_string_view();
779  default:
780  return INCORRECT_TYPE;
781  }
782 }
783 template<>
784 inline simdjson_result<uint64_t> element::get<uint64_t>() const noexcept {
785  switch (tape_ref_type()) {
786  case internal::tape_type::UINT64:
787  return next_tape_value<uint64_t>();
788  case internal::tape_type::INT64: {
789  int64_t result = next_tape_value<int64_t>();
790  if (result < 0) {
791  return NUMBER_OUT_OF_RANGE;
792  }
793  return static_cast<uint64_t>(result);
794  }
795  default:
796  return INCORRECT_TYPE;
797  }
798 }
799 template<>
800 inline simdjson_result<int64_t> element::get<int64_t>() const noexcept {
801  switch (tape_ref_type()) {
802  case internal::tape_type::UINT64: {
803  uint64_t result = next_tape_value<uint64_t>();
804  // Wrapping max in parens to handle Windows issue: https://stackoverflow.com/questions/11544073/how-do-i-deal-with-the-max-macro-in-windows-h-colliding-with-max-in-std
805  if (result > (std::numeric_limits<int64_t>::max)()) {
806  return NUMBER_OUT_OF_RANGE;
807  }
808  return static_cast<int64_t>(result);
809  }
810  case internal::tape_type::INT64:
811  return next_tape_value<int64_t>();
812  default:
813  return INCORRECT_TYPE;
814  }
815 }
816 template<>
817 inline simdjson_result<double> element::get<double>() const noexcept {
818  switch (tape_ref_type()) {
819  case internal::tape_type::UINT64:
820  return next_tape_value<uint64_t>();
821  case internal::tape_type::INT64: {
822  return next_tape_value<int64_t>();
823  int64_t result = tape_value();
824  if (result < 0) {
825  return NUMBER_OUT_OF_RANGE;
826  }
827  return double(result);
828  }
829  case internal::tape_type::DOUBLE:
830  return next_tape_value<double>();
831  default:
832  return INCORRECT_TYPE;
833  }
834 }
835 template<>
836 inline simdjson_result<array> element::get<array>() const noexcept {
837  switch (tape_ref_type()) {
838  case internal::tape_type::START_ARRAY:
839  return array(doc, json_index);
840  default:
841  return INCORRECT_TYPE;
842  }
843 }
844 template<>
845 inline simdjson_result<object> element::get<object>() const noexcept {
846  switch (tape_ref_type()) {
847  case internal::tape_type::START_OBJECT:
848  return object(doc, json_index);
849  default:
850  return INCORRECT_TYPE;
851  }
852 }
853 
854 template<typename T>
855 really_inline bool element::is() const noexcept {
856  auto result = get<T>();
857  return !result.error();
858 }
859 
860 #if SIMDJSON_EXCEPTIONS
861 
862 inline element::operator bool() const noexcept(false) { return get<bool>(); }
863 inline element::operator const char*() const noexcept(false) { return get<const char *>(); }
864 inline element::operator std::string_view() const noexcept(false) { return get<std::string_view>(); }
865 inline element::operator uint64_t() const noexcept(false) { return get<uint64_t>(); }
866 inline element::operator int64_t() const noexcept(false) { return get<int64_t>(); }
867 inline element::operator double() const noexcept(false) { return get<double>(); }
868 inline element::operator array() const noexcept(false) { return get<array>(); }
869 inline element::operator object() const noexcept(false) { return get<object>(); }
870 
871 inline array::iterator element::begin() const noexcept(false) {
872  return get<array>().begin();
873 }
874 inline array::iterator element::end() const noexcept(false) {
875  return get<array>().end();
876 }
877 
878 #endif
879 
880 inline simdjson_result<element> element::operator[](const std::string_view &key) const noexcept {
881  return at_key(key);
882 }
883 inline simdjson_result<element> element::operator[](const char *key) const noexcept {
884  return at_key(key);
885 }
886 inline simdjson_result<element> element::at(const std::string_view &json_pointer) const noexcept {
887  switch (tape_ref_type()) {
888  case internal::tape_type::START_OBJECT:
889  return object(doc, json_index).at(json_pointer);
890  case internal::tape_type::START_ARRAY:
891  return array(doc, json_index).at(json_pointer);
892  default:
893  return INCORRECT_TYPE;
894  }
895 }
896 inline simdjson_result<element> element::at(size_t index) const noexcept {
897  return get<array>().at(index);
898 }
899 inline simdjson_result<element> element::at_key(const std::string_view &key) const noexcept {
900  return get<object>().at_key(key);
901 }
902 inline simdjson_result<element> element::at_key_case_insensitive(const std::string_view &key) const noexcept {
903  return get<object>().at_key_case_insensitive(key);
904 }
905 
906 inline bool element::dump_raw_tape(std::ostream &out) const noexcept {
907  return doc->dump_raw_tape(out);
908 }
909 
910 } // namespace simdjson::dom
911 
912 namespace simdjson {
913 
914 //
915 // minify inline implementation
916 //
917 
918 template<>
919 inline std::ostream& minify<dom::element>::print(std::ostream& out) {
920  using tape_type=internal::tape_type;
921  size_t depth = 0;
922  constexpr size_t MAX_DEPTH = 16;
923  bool is_object[MAX_DEPTH];
924  is_object[0] = false;
925  bool after_value = false;
926 
927  internal::tape_ref iter(value);
928  do {
929  // print commas after each value
930  if (after_value) {
931  out << ",";
932  }
933  // If we are in an object, print the next key and :, and skip to the next value.
934  if (is_object[depth]) {
935  out << '"' << internal::escape_json_string(iter.get_string_view()) << "\":";
936  iter.json_index++;
937  }
938  switch (iter.tape_ref_type()) {
939 
940  // Arrays
941  case tape_type::START_ARRAY: {
942  // If we're too deep, we need to recurse to go deeper.
943  depth++;
944  if (unlikely(depth >= MAX_DEPTH)) {
945  out << minify<dom::array>(dom::array(iter.doc, iter.json_index));
946  iter.json_index = iter.tape_value() - 1; // Jump to the ]
947  depth--;
948  break;
949  }
950 
951  // Output start [
952  out << '[';
953  iter.json_index++;
954 
955  // Handle empty [] (we don't want to come back around and print commas)
956  if (iter.tape_ref_type() == tape_type::END_ARRAY) {
957  out << ']';
958  depth--;
959  break;
960  }
961 
962  is_object[depth] = false;
963  after_value = false;
964  continue;
965  }
966 
967  // Objects
968  case tape_type::START_OBJECT: {
969  // If we're too deep, we need to recurse to go deeper.
970  depth++;
971  if (unlikely(depth >= MAX_DEPTH)) {
972  out << minify<dom::object>(dom::object(iter.doc, iter.json_index));
973  iter.json_index = iter.tape_value() - 1; // Jump to the }
974  depth--;
975  break;
976  }
977 
978  // Output start {
979  out << '{';
980  iter.json_index++;
981 
982  // Handle empty {} (we don't want to come back around and print commas)
983  if (iter.tape_ref_type() == tape_type::END_OBJECT) {
984  out << '}';
985  depth--;
986  break;
987  }
988 
989  is_object[depth] = true;
990  after_value = false;
991  continue;
992  }
993 
994  // Scalars
995  case tape_type::STRING:
996  out << '"' << internal::escape_json_string(iter.get_string_view()) << '"';
997  break;
998  case tape_type::INT64:
999  out << iter.next_tape_value<int64_t>();
1000  iter.json_index++; // numbers take up 2 spots, so we need to increment extra
1001  break;
1002  case tape_type::UINT64:
1003  out << iter.next_tape_value<uint64_t>();
1004  iter.json_index++; // numbers take up 2 spots, so we need to increment extra
1005  break;
1006  case tape_type::DOUBLE:
1007  out << iter.next_tape_value<double>();
1008  iter.json_index++; // numbers take up 2 spots, so we need to increment extra
1009  break;
1010  case tape_type::TRUE_VALUE:
1011  out << "true";
1012  break;
1013  case tape_type::FALSE_VALUE:
1014  out << "false";
1015  break;
1016  case tape_type::NULL_VALUE:
1017  out << "null";
1018  break;
1019 
1020  // These are impossible
1021  case tape_type::END_ARRAY:
1022  case tape_type::END_OBJECT:
1023  case tape_type::ROOT:
1024  abort();
1025  }
1026  iter.json_index++;
1027  after_value = true;
1028 
1029  // Handle multiple ends in a row
1030  while (depth != 0 && (iter.tape_ref_type() == tape_type::END_ARRAY || iter.tape_ref_type() == tape_type::END_OBJECT)) {
1031  out << char(iter.tape_ref_type());
1032  depth--;
1033  iter.json_index++;
1034  }
1035 
1036  // Stop when we're at depth 0
1037  } while (depth != 0);
1038 
1039  return out;
1040 }
1041 template<>
1042 inline std::ostream& minify<dom::object>::print(std::ostream& out) {
1043  out << '{';
1044  auto pair = value.begin();
1045  auto end = value.end();
1046  if (pair != end) {
1047  out << minify<dom::key_value_pair>(*pair);
1048  for (++pair; pair != end; ++pair) {
1049  out << "," << minify<dom::key_value_pair>(*pair);
1050  }
1051  }
1052  return out << '}';
1053 }
1054 template<>
1055 inline std::ostream& minify<dom::array>::print(std::ostream& out) {
1056  out << '[';
1057  auto iter = value.begin();
1058  auto end = value.end();
1059  if (iter != end) {
1060  out << minify<dom::element>(*iter);
1061  for (++iter; iter != end; ++iter) {
1062  out << "," << minify<dom::element>(*iter);
1063  }
1064  }
1065  return out << ']';
1066 }
1067 template<>
1068 inline std::ostream& minify<dom::key_value_pair>::print(std::ostream& out) {
1069  return out << '"' << internal::escape_json_string(value.key) << "\":" << value.value;
1070 }
1071 
1072 #if SIMDJSON_EXCEPTIONS
1073 
1074 template<>
1075 inline std::ostream& minify<simdjson_result<dom::element>>::print(std::ostream& out) {
1076  if (value.error()) { throw simdjson_error(value.error()); }
1077  return out << minify<dom::element>(value.first);
1078 }
1079 template<>
1080 inline std::ostream& minify<simdjson_result<dom::array>>::print(std::ostream& out) {
1081  if (value.error()) { throw simdjson_error(value.error()); }
1082  return out << minify<dom::array>(value.first);
1083 }
1084 template<>
1085 inline std::ostream& minify<simdjson_result<dom::object>>::print(std::ostream& out) {
1086  if (value.error()) { throw simdjson_error(value.error()); }
1087  return out << minify<dom::object>(value.first);
1088 }
1089 
1090 #endif
1091 
1092 } // namespace simdjson
1093 
1094 namespace simdjson::internal {
1095 
1096 //
1097 // tape_ref inline implementation
1098 //
1099 really_inline tape_ref::tape_ref() noexcept : doc{nullptr}, json_index{0} {}
1100 really_inline tape_ref::tape_ref(const document *_doc, size_t _json_index) noexcept : doc{_doc}, json_index{_json_index} {}
1101 
1102 inline size_t tape_ref::after_element() const noexcept {
1103  switch (tape_ref_type()) {
1104  case tape_type::START_ARRAY:
1105  case tape_type::START_OBJECT:
1106  return tape_value();
1107  case tape_type::UINT64:
1108  case tape_type::INT64:
1109  case tape_type::DOUBLE:
1110  return json_index + 2;
1111  default:
1112  return json_index + 1;
1113  }
1114 }
1115 really_inline tape_type tape_ref::tape_ref_type() const noexcept {
1116  return static_cast<tape_type>(doc->tape[json_index] >> 56);
1117 }
1118 really_inline uint64_t internal::tape_ref::tape_value() const noexcept {
1119  return doc->tape[json_index] & internal::JSON_VALUE_MASK;
1120 }
1121 template<typename T>
1122 really_inline T tape_ref::next_tape_value() const noexcept {
1123  static_assert(sizeof(T) == sizeof(uint64_t));
1124  return *reinterpret_cast<const T*>(&doc->tape[json_index + 1]);
1125 }
1126 inline std::string_view internal::tape_ref::get_string_view() const noexcept {
1127  size_t string_buf_index = tape_value();
1128  uint32_t len;
1129  memcpy(&len, &doc->string_buf[string_buf_index], sizeof(len));
1130  return std::string_view(
1131  reinterpret_cast<const char *>(&doc->string_buf[string_buf_index + sizeof(uint32_t)]),
1132  len
1133  );
1134 }
1135 
1136 
1137 } // namespace simdjson::internal
1138 
1139 #endif // SIMDJSON_INLINE_DOCUMENT_H
simdjson::dom::parser::max_capacity
really_inline size_t max_capacity() const noexcept
The largest document this parser can automatically support.
Definition: document.h:430
simdjson::dom::element::type
really_inline element_type type() const noexcept
The type of this element.
Definition: document.h:722
simdjson::dom::element::is
really_inline bool is() const noexcept
Tell whether the value can be cast to the given primitive type.
Definition: document.h:855
simdjson::dom::element
A JSON element.
Definition: document.h:380
simdjson::dom::array::iterator
Definition: document.h:111
simdjson::dom::object::iterator::key_c_str
const char * key_c_str() const noexcept
Get the key of this key/value pair.
Definition: document.h:703
simdjson::dom::object::iterator::operator++
void operator++() noexcept
Get the next key/value pair.
Definition: document.h:690
simdjson::minify::print
std::ostream & print(std::ostream &out)
Minify JSON to an output stream.
simdjson::dom::object::at_key
simdjson_result< element > at_key(const std::string_view &key) const noexcept
Get the value associated with the given key.
Definition: document.h:653
simdjson::dom::array::begin
iterator begin() const noexcept
Return the first array element.
Definition: document.h:539
simdjson::dom::object::begin
iterator begin() const noexcept
Return the first key/value pair.
Definition: document.h:603
simdjson::dom::parser::capacity
really_inline size_t capacity() const noexcept
The largest document this parser can support without reallocating.
Definition: document.h:427
simdjson::dom::element::operator[]
simdjson_result< element > operator[](const std::string_view &key) const noexcept
Get the value associated with the given key.
Definition: document.h:880
simdjson::dom::object::object
really_inline object() noexcept
Create a new, invalid object.
Definition: document.h:601
simdjson::dom::object::at_key_case_insensitive
simdjson_result< element > at_key_case_insensitive(const std::string_view &key) const noexcept
Get the value associated with the given key in a case-insensitive manner.
Definition: document.h:665
simdjson::dom::array::array
really_inline array() noexcept
Create a new, invalid array.
Definition: document.h:537
simdjson::dom::parser::parse
simdjson_result< element > parse(const uint8_t *buf, size_t len, bool realloc_if_needed=true) noexcept
Parse a JSON document and return a temporary reference to it.
Definition: document.h:381
simdjson::dom::object::iterator::operator!=
bool operator!=(const iterator &other) const noexcept
Check if these key value pairs come from the same place in the JSON.
Definition: document.h:687
simdjson::dom::object
JSON object.
Definition: document.h:182
simdjson::dom::parser::allocate
WARN_UNUSED error_code allocate(size_t capacity, size_t max_depth=DEFAULT_MAX_DEPTH) noexcept
Ensure this parser has enough memory to process JSON documents up to capacity bytes in length and max...
Definition: document.h:438
simdjson::dom::document
A parsed JSON document.
Definition: document.h:318
simdjson::simdjson_result
The result of a simdjson operation that could fail.
Definition: error.h:166
simdjson::dom::object::operator[]
simdjson_result< element > operator[](const std::string_view &key) const noexcept
Get the value associated with the given key.
Definition: document.h:610
simdjson::dom::parser::load_many
document_stream load_many(const std::string &path, size_t batch_size=DEFAULT_BATCH_SIZE) noexcept
Load a file containing many JSON documents.
Definition: document.h:376
simdjson::dom::document_stream
A forward-only stream of documents.
Definition: document_stream.h:15
simdjson::dom::parser::parse_many
document_stream parse_many(const uint8_t *buf, size_t len, size_t batch_size=DEFAULT_BATCH_SIZE) noexcept
Parse a buffer containing many JSON documents.
Definition: document.h:414
simdjson::dom::array
JSON array.
Definition: document.h:106
simdjson::dom::array::iterator::operator*
element operator*() const noexcept
Get the actual value.
Definition: document.h:588
simdjson::dom::element::begin
dom::array::iterator begin() const noexcept(false)
Iterate over each element in this array.
Definition: document.h:871
simdjson::dom::element::at_key
simdjson_result< element > at_key(const std::string_view &key) const noexcept
Get the value associated with the given key.
Definition: document.h:899
simdjson::dom::object::end
iterator end() const noexcept
One past the last key/value pair.
Definition: document.h:606
simdjson::dom::object::iterator
Definition: document.h:187
simdjson::dom::element::end
dom::array::iterator end() const noexcept(false)
Iterate over each element in this array.
Definition: document.h:874
simdjson::dom::document::root
element root() const noexcept
Get the root element of this document as a JSON array.
Definition: document.h:191
simdjson::dom::array::iterator::operator++
void operator++() noexcept
Get the next value.
Definition: document.h:594
simdjson::dom::parser::load
simdjson_result< element > load(const std::string &path) noexcept
Load a JSON document from a file and return a reference to it.
Definition: document.h:369
simdjson::dom::key_value_pair
Key/value pair in an object.
Definition: document.h:600
simdjson::dom::object::iterator::operator*
const key_value_pair operator*() const noexcept
Get the actual key/value pair.
Definition: document.h:684
simdjson::dom::array::at
simdjson_result< element > at(const std::string_view &json_pointer) const noexcept
Get the value associated with the given JSON pointer.
Definition: document.h:546
simdjson::dom::object::iterator::value
element value() const noexcept
Get the value of this key/value pair.
Definition: document.h:706
simdjson::dom::element::is_null
really_inline bool is_null() const noexcept
Whether this element is a json null.
Definition: document.h:748
simdjson::simdjson_result::error
really_inline error_code error() const noexcept
The error.
Definition: error.h:127
simdjson::dom::element::element
really_inline element() noexcept
Create a new, invalid element.
Definition: document.h:719
simdjson::dom::object::at
simdjson_result< element > at(const std::string_view &json_pointer) const noexcept
Get the value associated with the given JSON pointer.
Definition: document.h:616
simdjson::dom::array::iterator::operator!=
bool operator!=(const iterator &other) const noexcept
Check if these values come from the same place in the JSON.
Definition: document.h:591
simdjson::dom::array::end
iterator end() const noexcept
One past the last array element.
Definition: document.h:542
simdjson::dom::parser::max_depth
really_inline size_t max_depth() const noexcept
The maximum level of nested object and arrays supported by this parser.
Definition: document.h:433
simdjson::dom::parser::parser
really_inline parser(size_t max_capacity=SIMDJSON_MAXSIZE_BYTES) noexcept
Create a JSON parser.
Definition: document.h:317
simdjson::dom::element::at_key_case_insensitive
simdjson_result< element > at_key_case_insensitive(const std::string_view &key) const noexcept
Get the value associated with the given key in a case-insensitive manner.
Definition: document.h:902
simdjson::dom::parser::set_max_capacity
really_inline void set_max_capacity(size_t max_capacity) noexcept
Set max_capacity.
Definition: document.h:516
simdjson::dom::element::at
simdjson_result< element > at(const std::string_view &json_pointer) const noexcept
Get the value associated with the given JSON pointer.
Definition: document.h:886
simdjson::dom::object::iterator::key
std::string_view key() const noexcept
Get the key of this key/value pair.
Definition: document.h:694