GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
json.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_CORE_FORMATS_JSON_HPP
5#define GREM_CORE_FORMATS_JSON_HPP
6
8
9#include <GREM/core/Error.hpp>
26#include <GREM/core/time.hpp>
27
28#include <charconv> // std::to_chars_result, std::from_chars_result std::to_chars, std::from_chars
29#include <cmath> // std::isnan, std::isinf, std::signbit
30#include <compare> // std::partial_ordering, std::compare_partial_order_fallback
31#include <cstddef> // std::nullptr_t
32#include <cstdlib> // std::strtoull, std::strtod
33#include <initializer_list> // std::initializer_list
34#include <ios> // std::ios_base
35#include <istream> // std::istream
36#include <iterator> // std::begin, std::end, std::...streambuf_iterator
37#include <memory> // std::allocator, std::allocator_traits
38#include <memory_resource> // std::pmr::polymorphic_allocator
39#include <new> // std::launder
40#include <ostream> // std::ostream
41#include <sstream> // std::istringstream, std::basic_istringstream, std::ostringstream, std::basic_ostringstream
42#include <stdexcept> // std::out_of_range
43#include <streambuf> // std::streambuf
44#include <string> // std::...string, std::char_traits
45#include <system_error> // std::errc
46#include <tuple> // std::forward_as_tuple
47#include <type_traits> // std::remove_..._t
48#include <utility> // std::move, std::forward, std::piecewise_construct, std::in_place_type
49
50namespace grem::json {
51
52namespace detail {
53
54struct NoSerializerOverride {};
55struct NoDeserializerOverride {};
56
57} // namespace detail
58
59template <template <typename> typename Allocator>
60class ObjectBase; // Forward declaration.
61
62template <template <typename> typename Allocator, typename Predicate>
63typename ObjectBase<Allocator>::size_type erase_if(ObjectBase<Allocator>& container, Predicate predicate); // Forward declaration.
64
65template <template <typename> typename Allocator>
66class ArrayBase; // Forward declaration.
67
68template <template <typename> typename Allocator, typename U>
69typename ArrayBase<Allocator>::size_type erase(ArrayBase<Allocator>& container, const U& value); // Forward declaration.
70
71template <template <typename> typename Allocator, typename Predicate>
72typename ArrayBase<Allocator>::size_type erase_if(ArrayBase<Allocator>& container, Predicate predicate); // Forward declaration.
73
82 size_t lineNumber = 1;
83
88 size_t columnNumber = 1;
89
97 [[nodiscard]] constexpr bool operator==(const SourceLocation& other) const = default;
98};
99
109
115
116 Error(const auto& message, const SourceLocation& source)
117 : grem::Error(message)
118 , lineNumber(source.lineNumber)
119 , columnNumber(source.columnNumber) {}
120
121 void writeMessage(String& output) const override {
122 if (lineNumber != 0) {
123 output.append(toString(lineNumber));
124 output.push_back(':');
125 if (columnNumber != 0) {
126 output.append(toString(columnNumber));
127 output.push_back(':');
128 }
129 output.push_back(' ');
130 }
131 output.append(what());
132 }
133
134 [[nodiscard]] bool messageAttachesToPrecedingFilepath() const noexcept override {
135 return lineNumber != 0;
136 }
137
138 [[nodiscard]] SourceLocation getSource() const noexcept {
139 return {.lineNumber = lineNumber, .columnNumber = columnNumber};
140 }
141};
142
210
215
216// Forward declaration.
217template <template <typename> typename Allocator>
218class VariantBase;
219
220// Forward declaration.
221template <template <typename> typename Allocator>
222class ValueBase;
223
228
232using Boolean = bool;
233
239template <template <typename> typename Allocator>
241
246
250using Number = double;
251
257template <template <typename> typename Allocator>
259public:
265 using allocator_type = Allocator<value_type>;
274
275 ObjectBase() noexcept;
276 explicit ObjectBase(const allocator_type& allocator) noexcept;
278
279 template <input_iterator InputIterator, sentinel_for<InputIterator> Sentinel>
280 ObjectBase(InputIterator first, Sentinel last, const allocator_type& allocator = allocator_type());
281 ObjectBase(std::initializer_list<value_type> ilist, const allocator_type& allocator = allocator_type());
282
283 ObjectBase(const ObjectBase& other, const allocator_type& allocator);
284 ObjectBase(const ObjectBase& other);
285 ObjectBase(ObjectBase&& other, const allocator_type& allocator) noexcept; // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
286 ObjectBase(ObjectBase&& other) noexcept;
287
288 ObjectBase& operator=(const ObjectBase& other);
289 ObjectBase& operator=(ObjectBase&& other) noexcept(
290 std::allocator_traits<
291 allocator_type>::propagate_on_container_move_assignment::value || // NOLINT(cppcoreguidelines-noexcept-move-operations, performance-noexcept-move-constructor)
292 std::allocator_traits<allocator_type>::is_always_equal::value);
293 ObjectBase& operator=(std::initializer_list<value_type> ilist);
294
295 [[nodiscard]] allocator_type get_allocator() const noexcept;
296
297 [[nodiscard]] mapped_type& at(StringView key);
298 [[nodiscard]] const mapped_type& at(StringView key) const;
299 [[nodiscard]] mapped_type& operator[](const key_type& k);
300 [[nodiscard]] mapped_type& operator[](key_type&& k);
301
302 [[nodiscard]] iterator begin() noexcept;
303 [[nodiscard]] const_iterator begin() const noexcept;
304 [[nodiscard]] const_iterator cbegin() const noexcept;
305 [[nodiscard]] iterator end() noexcept;
306 [[nodiscard]] const_iterator end() const noexcept;
307 [[nodiscard]] const_iterator cend() const noexcept;
308 [[nodiscard]] reverse_iterator rbegin() noexcept;
309 [[nodiscard]] const_reverse_iterator rbegin() const noexcept;
310 [[nodiscard]] const_reverse_iterator crbegin() const noexcept;
311 [[nodiscard]] reverse_iterator rend() noexcept;
312 [[nodiscard]] const_reverse_iterator rend() const noexcept;
313 [[nodiscard]] const_reverse_iterator crend() const noexcept;
314
315 [[nodiscard]] bool empty() const noexcept;
316 [[nodiscard]] size_type size() const noexcept;
317 [[nodiscard]] size_type max_size() const noexcept;
318 [[nodiscard]] size_type capacity() const noexcept;
319
320 void clear() noexcept;
321 void reserve(size_type newCapacity);
322
323 template <typename P>
324 Pair<iterator, bool> insert(P&& value);
325
326 template <typename P>
328
329 template <input_iterator InputIterator, sentinel_for<InputIterator> Sentinel>
330 void insert(InputIterator first, Sentinel last);
331 void insert(std::initializer_list<value_type> ilist);
332 template <typename R>
333 void insert_range(R&& r);
334
335 template <typename... Args>
336 Pair<iterator, bool> emplace(Args&&... args);
337
338 template <typename... Args>
339 iterator emplace_hint(const_iterator hint, Args&&... args);
340
341 template <typename... Args>
342 Pair<iterator, bool> try_emplace(const key_type& k, Args&&... args);
343
344 template <typename... Args>
345 Pair<iterator, bool> try_emplace(key_type&& k, Args&&... args);
346
347 template <typename... Args>
348 iterator try_emplace(const_iterator, const key_type& k, Args&&... args);
349
350 template <typename... Args>
352
355
356 void swap(ObjectBase& other) noexcept;
357
358 [[nodiscard]] size_type count(StringView key) const noexcept;
359 [[nodiscard]] bool contains(StringView key) const noexcept;
360 [[nodiscard]] iterator find(StringView key) noexcept;
361 [[nodiscard]] const_iterator find(StringView key) const noexcept;
362 [[nodiscard]] Pair<iterator, iterator> equal_range(StringView key) noexcept;
363 [[nodiscard]] Pair<const_iterator, const_iterator> equal_range(StringView key) const noexcept;
364 [[nodiscard]] iterator lower_bound(StringView key) noexcept;
365 [[nodiscard]] const_iterator lower_bound(StringView key) const noexcept;
366 [[nodiscard]] iterator upper_bound(StringView key) noexcept;
367 [[nodiscard]] const_iterator upper_bound(StringView key) const noexcept;
368
369 [[nodiscard]] bool operator==(const ObjectBase& other) const noexcept;
370 [[nodiscard]] std::partial_ordering operator<=>(const ObjectBase& other) const noexcept;
371
372 template <typename Predicate>
373 friend size_type erase_if(ObjectBase& container, Predicate predicate);
374
375private:
376 struct Compare {
377 [[nodiscard]] bool operator()(const value_type& a, const value_type& b) const noexcept;
378 [[nodiscard]] bool operator()(const value_type& a, StringView b) const noexcept;
379 [[nodiscard]] bool operator()(StringView a, const value_type& b) const noexcept;
380 [[nodiscard]] bool operator()(StringView a, StringView b) const noexcept;
381 };
382
383 ArrayList<value_type, allocator_type> membersSortedByName;
384};
385
390
396template <template <typename> typename Allocator>
398public:
402 using allocator_type = Allocator<value_type>;
411
412 ArrayBase() noexcept;
413 explicit ArrayBase(const allocator_type& allocator) noexcept;
415
416 template <input_iterator InputIterator, sentinel_for<InputIterator> Sentinel>
417 ArrayBase(InputIterator first, Sentinel last, const allocator_type& allocator = allocator_type());
418 ArrayBase(size_type count, const value_type& value, const allocator_type& allocator = allocator_type());
419 ArrayBase(std::initializer_list<value_type> ilist, const allocator_type& allocator = allocator_type());
420
421 ArrayBase(const ArrayBase& other, const allocator_type& allocator);
422 ArrayBase(const ArrayBase& other);
423 ArrayBase(ArrayBase&& other, const allocator_type& allocator) noexcept; // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
424 ArrayBase(ArrayBase&& other) noexcept;
425
426 ArrayBase& operator=(const ArrayBase& other);
427 ArrayBase& operator=(ArrayBase&& other) noexcept(
428 std::allocator_traits<
429 allocator_type>::propagate_on_container_move_assignment::value || // NOLINT(cppcoreguidelines-noexcept-move-operations, performance-noexcept-move-constructor)
430 std::allocator_traits<allocator_type>::is_always_equal::value);
431 ArrayBase& operator=(std::initializer_list<value_type> ilist);
432
433 void swap(ArrayBase& other) noexcept;
434
435 [[nodiscard]] allocator_type get_allocator() const noexcept;
436
437 [[nodiscard]] pointer data() noexcept;
438 [[nodiscard]] const_pointer data() const noexcept;
439 [[nodiscard]] size_type size() const noexcept;
440 [[nodiscard]] size_type max_size() const noexcept;
441 [[nodiscard]] size_type capacity() const noexcept;
442 [[nodiscard]] bool empty() const noexcept;
443
444 [[nodiscard]] iterator begin() noexcept;
445 [[nodiscard]] const_iterator begin() const noexcept;
446 [[nodiscard]] const_iterator cbegin() const noexcept;
447 [[nodiscard]] iterator end() noexcept;
448 [[nodiscard]] const_iterator end() const noexcept;
449 [[nodiscard]] const_iterator cend() const noexcept;
450 [[nodiscard]] reverse_iterator rbegin() noexcept;
451 [[nodiscard]] const_reverse_iterator rbegin() const noexcept;
452 [[nodiscard]] const_reverse_iterator crbegin() const noexcept;
453 [[nodiscard]] reverse_iterator rend() noexcept;
454 [[nodiscard]] const_reverse_iterator rend() const noexcept;
455 [[nodiscard]] const_reverse_iterator crend() const noexcept;
456
457 [[nodiscard]] reference front();
458 [[nodiscard]] const_reference front() const;
459 [[nodiscard]] reference back();
460 [[nodiscard]] const_reference back() const;
461 [[nodiscard]] reference at(size_type pos);
462 [[nodiscard]] const_reference at(size_type pos) const;
463 [[nodiscard]] reference operator[](size_type pos);
464 [[nodiscard]] const_reference operator[](size_type pos) const;
465
466 [[nodiscard]] bool operator==(const ArrayBase& other) const;
467 [[nodiscard]] std::partial_ordering operator<=>(const ArrayBase& other) const noexcept;
468
469 template <typename U>
470 friend size_type erase(ArrayBase& container, const U& value);
471
472 template <typename Predicate>
473 friend size_type erase_if(ArrayBase& container, Predicate predicate);
474
475 void clear() noexcept;
476 void reserve(size_type newCapacity);
478
479 void assign(size_type count, const value_type& value);
480 template <input_iterator InputIterator, sentinel_for<InputIterator> Sentinel>
481 void assign(InputIterator first, Sentinel last);
482 void assign(std::initializer_list<value_type> ilist);
483 template <typename R>
484 void assign_range(R&& r);
485
489
490 template <input_iterator InputIterator, sentinel_for<InputIterator> Sentinel>
491 iterator insert(const_iterator pos, InputIterator first, Sentinel last);
492 iterator insert(const_iterator pos, std::initializer_list<value_type> ilist);
493 template <typename R>
495 template <typename R>
496 void append_range(R&& r);
497
498 template <typename... Args>
499 iterator emplace(const_iterator pos, Args&&... args);
500
503
504 void push_back(const value_type& value);
505 void push_back(value_type&& value);
506
507 template <typename... Args>
508 reference emplace_back(Args&&... args);
509
510 void pop_back();
511
513 void resize(size_type count, const value_type& value);
514
515private:
517};
518
522using Array = json::ArrayBase<std::allocator>;
523
537template <template <typename> typename Allocator>
538class VariantBase : public grem::Variant<Null, Boolean, StringBase<Allocator>, Number, ObjectBase<Allocator>, ArrayBase<Allocator>> {
539private:
541
542public:
544 using allocator_type = Allocator<VariantBase>;
545
565 [[nodiscard]] static ValueBase<Allocator> parse(UTF8StringView jsonString, const SourceLocation& source = {}, const allocator_type& allocator = allocator_type());
566
586 [[nodiscard]] static ValueBase<Allocator> parse(StringView jsonString, const SourceLocation& source = {}, const allocator_type& allocator = allocator_type());
587
591 VariantBase() noexcept
593
599 explicit VariantBase(const allocator_type& allocator) noexcept
600 : allocator(allocator) {}
601
607 VariantBase(Null, const allocator_type& allocator) noexcept
608 : VariantBase(allocator) {}
609
615
621 VariantBase(std::nullptr_t, const allocator_type& allocator) noexcept
622 : VariantBase(allocator) {}
623
627 VariantBase(std::nullptr_t) noexcept
628 : VariantBase(std::nullptr_t{}, allocator_type()) {}
629
636 VariantBase(Boolean value, const allocator_type& allocator) noexcept
637 : Base(std::in_place_type<Boolean>, value)
638 , allocator(allocator) {}
639
645 VariantBase(Boolean value) noexcept
646 : VariantBase(value, allocator_type()) {}
647
656 VariantBase(const StringBase<Allocator>& value, const allocator_type& allocator)
657 : Base(std::in_place_type<StringBase<Allocator>>, value, allocator)
658 , allocator(this->template as<StringBase<Allocator>>().get_allocator()) {}
659
668 : Base(std::in_place_type<StringBase<Allocator>>, value)
669 , allocator(this->template as<StringBase<Allocator>>().get_allocator()) {}
670
677 VariantBase(StringBase<Allocator>&& value, const allocator_type& allocator) noexcept
678 : Base(std::in_place_type<StringBase<Allocator>>, std::move(value), allocator)
679 , allocator(this->template as<StringBase<Allocator>>().get_allocator()) {}
680
687 : Base(std::in_place_type<StringBase<Allocator>>, std::move(value))
688 , allocator(this->template as<StringBase<Allocator>>().get_allocator()) {}
689
700 VariantBase(const char* value, const allocator_type& allocator)
701 : VariantBase(StringBase<Allocator>{value, allocator}, allocator) {}
702
712 VariantBase(const char* value)
713 : VariantBase(value, allocator_type()) {}
714
724 VariantBase(StringView value, const allocator_type& allocator)
725 : VariantBase(StringBase<Allocator>{value, allocator}, allocator) {}
726
737
747 VariantBase(CStringView value, const allocator_type& allocator)
748 : VariantBase(value.c_str(), allocator) {}
749
760
771 VariantBase(const char8_t* value, const allocator_type& allocator)
772 : VariantBase(std::launder(reinterpret_cast<const char*>(value)), allocator) {
773 static_assert(sizeof(char) == sizeof(char8_t));
774 static_assert(alignof(char) == alignof(char8_t));
775 }
776
786 VariantBase(const char8_t* value)
787 : VariantBase(value, allocator_type()) {}
788
800 : VariantBase(StringBase<Allocator>{value.begin(), value.end(), allocator}, allocator) {}
801
813
825 : VariantBase(value.c_str(), allocator) {}
826
838
846 VariantBase(strict_arithmetic auto value, const allocator_type& allocator) noexcept
847 : Base(std::in_place_type<Number>, static_cast<Number>(value))
848 , allocator(allocator) {}
849
856 VariantBase(strict_arithmetic auto value) noexcept
857 : VariantBase(value, allocator_type()) {}
858
867 VariantBase(const ObjectBase<Allocator>& value, const allocator_type& allocator)
868 : Base(std::in_place_type<ObjectBase<Allocator>>, value, allocator)
869 , allocator(this->template as<ObjectBase<Allocator>>().get_allocator()) {}
870
879 : Base(std::in_place_type<ObjectBase<Allocator>>, value)
880 , allocator(this->template as<ObjectBase<Allocator>>().get_allocator()) {}
881
888 VariantBase(ObjectBase<Allocator>&& value, const allocator_type& allocator) noexcept
889 : Base(std::in_place_type<ObjectBase<Allocator>>, std::move(value), allocator)
890 , allocator(this->template as<ObjectBase<Allocator>>().get_allocator()) {}
891
898 : Base(std::in_place_type<ObjectBase<Allocator>>, std::move(value))
899 , allocator(this->template as<ObjectBase<Allocator>>().get_allocator()) {}
900
909 VariantBase(const ArrayBase<Allocator>& value, const allocator_type& allocator)
910 : Base(std::in_place_type<ArrayBase<Allocator>>, value, allocator)
911 , allocator(this->template as<ArrayBase<Allocator>>().get_allocator()) {}
912
921 : Base(std::in_place_type<ArrayBase<Allocator>>, value)
922 , allocator(this->template as<ArrayBase<Allocator>>().get_allocator()) {}
923
930 VariantBase(ArrayBase<Allocator>&& value, const allocator_type& allocator) noexcept
931 : Base(std::in_place_type<ArrayBase<Allocator>>, std::move(value), allocator)
932 , allocator(this->template as<ArrayBase<Allocator>>().get_allocator()) {}
933
940 : Base(std::in_place_type<ArrayBase<Allocator>>, std::move(value))
941 , allocator(this->template as<ArrayBase<Allocator>>().get_allocator()) {}
942
944 ~VariantBase() = default;
945
947 VariantBase(const VariantBase& other, const allocator_type& allocator) noexcept
948 : Base(static_cast<const Base&>(other))
949 , allocator((this->valueless_by_exception())
950 ? allocator
951 : match(static_cast<Base&>(*this))( //
952 [&](Null&) -> allocator_type { return allocator; }, //
953 [&](Boolean&) -> allocator_type { return allocator; }, //
954 [&](StringBase<Allocator>& value) -> allocator_type { return value.get_allocator(); }, //
955 [&](Number&) -> allocator_type { return allocator; }, //
956 [&](ObjectBase<Allocator>& value) -> allocator_type { return value.get_allocator(); }, //
957 [&](ArrayBase<Allocator>& value) -> allocator_type { return value.get_allocator(); })) {}
958
961 : VariantBase(other, std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator())) {}
962
964 VariantBase(VariantBase&& other, const allocator_type& allocator) noexcept // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
965 : Base(std::move(static_cast<Base&>(other)))
966 , allocator((this->valueless_by_exception())
967 ? allocator
968 : match(static_cast<Base&>(*this))( //
969 [&](Null&) -> allocator_type { return allocator; }, //
970 [&](Boolean&) -> allocator_type { return allocator; }, //
971 [&](StringBase<Allocator>& value) -> allocator_type { return value.get_allocator(); }, //
972 [&](Number&) -> allocator_type { return allocator; }, //
973 [&](ObjectBase<Allocator>& value) -> allocator_type { return value.get_allocator(); }, //
974 [&](ArrayBase<Allocator>& value) -> allocator_type { return value.get_allocator(); })) {}
975
977 VariantBase(VariantBase&& other) noexcept
978 : VariantBase(std::move(other), other.get_allocator()) {}
979
982 if (this == &other) {
983 return *this;
984 }
985 if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value) {
986 if constexpr (!std::allocator_traits<allocator_type>::is_always_equal::value) {
987 if (allocator != other.get_allocator()) {
988 this->template emplace<Null>();
989 }
990 }
991 allocator = other.get_allocator();
992 }
993 static_cast<Base&>(*this) = static_cast<const Base&>(other);
994 if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value) {
995 match(static_cast<Base&>(*this))([&](auto& value) -> void {
996 if constexpr (requires { value.get_allocator(); }) {
997 allocator = value.get_allocator();
998 }
999 });
1000 }
1001 return *this;
1002 }
1003
1006 std::allocator_traits<
1007 allocator_type>::propagate_on_container_move_assignment::value || // NOLINT(cppcoreguidelines-noexcept-move-operations, performance-noexcept-move-constructor)
1008 std::allocator_traits<allocator_type>::is_always_equal::value) {
1009 if (this == &other) {
1010 return *this;
1011 }
1012 this->template emplace<Null>();
1013 if constexpr (!std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value && !std::allocator_traits<allocator_type>::is_always_equal::value) {
1014 if (allocator != other.allocator) {
1015 match(other)( //
1016 [&](const Null&) -> void {}, //
1017 [&](const Boolean& value) -> void { this->template emplace<Boolean>(value); }, //
1018 [&](const StringBase<Allocator>& value) -> void { this->template emplace<StringBase<Allocator>>(value, allocator); }, //
1019 [&](const Number& value) -> void { this->template emplace<Number>(value); }, //
1020 [&](const ObjectBase<Allocator>& value) -> void { this->template emplace<ObjectBase<Allocator>>(value, allocator); }, //
1021 [&](const ArrayBase<Allocator>& value) -> void { this->template emplace<ArrayBase<Allocator>>(value, allocator); });
1022 other.template emplace<Null>();
1023 return *this;
1024 }
1025 }
1026 static_cast<Base&>(*this) = std::move(static_cast<Base&>(other));
1027 if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value) {
1028 match(static_cast<Base&>(*this))([&](auto& value) -> void {
1029 if constexpr (requires { value.get_allocator(); }) {
1030 allocator = value.get_allocator();
1031 } else {
1032 allocator = other.allocator;
1033 }
1034 });
1035 }
1036 return *this;
1037 }
1038
1044 [[nodiscard]] allocator_type get_allocator() const noexcept {
1045 return allocator;
1046 }
1047
1063 [[nodiscard]] StringBase<Allocator> toString(const SerializationOptions& options = {}, const allocator_type& stringAllocator = allocator_type()) const;
1064
1072 [[nodiscard]] GREM_ALWAYS_INLINE bool operator==(const VariantBase& other) const {
1073 return static_cast<const Base&>(*this) == static_cast<const Base&>(other);
1074 }
1075
1083 [[nodiscard]] GREM_ALWAYS_INLINE std::partial_ordering operator<=>(const VariantBase& other) const {
1084 return std::compare_partial_order_fallback(static_cast<const Base&>(*this), static_cast<const Base&>(other));
1085 }
1086
1087private:
1088 [[no_unique_address]] allocator_type allocator;
1089};
1090
1095
1101template <template <typename> typename Allocator>
1102class ValueBase : public VariantBase<Allocator> {
1103public:
1105
1125 [[nodiscard]] static ValueBase parse(UTF8StringView jsonString, const SourceLocation& source = {}, const allocator_type& allocator = allocator_type());
1126
1146 [[nodiscard]] static ValueBase parse(StringView jsonString, const SourceLocation& source = {}, const allocator_type& allocator = allocator_type());
1147
1148 using VariantBase<Allocator>::VariantBase; // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
1149
1157 : VariantBase<Allocator>(std::move(value), allocator) {}
1158
1165 : VariantBase<Allocator>(std::move(value)) {}
1166
1174 : VariantBase<Allocator>(std::move(value))
1175 , source(source) {}
1176
1184 ValueBase(VariantBase<Allocator> value, const SourceLocation& source, const allocator_type& allocator)
1185 : VariantBase<Allocator>(std::move(value), allocator)
1186 , source(source) {}
1187
1189 ~ValueBase() = default;
1190
1192 ValueBase(const ValueBase& other, const allocator_type& allocator) noexcept
1193 : VariantBase<Allocator>(static_cast<const VariantBase<Allocator>&>(other), allocator)
1194 , source(other.source) {}
1195
1197 ValueBase(const ValueBase& other) = default;
1198
1200 ValueBase(ValueBase&& other, const allocator_type& allocator) noexcept // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
1201 : VariantBase<Allocator>(std::move(static_cast<VariantBase<Allocator>&>(other)), allocator)
1202 , source(other.source) {}
1203
1205 ValueBase(ValueBase&& other) noexcept = default;
1206
1208 ValueBase& operator=(const ValueBase& other) = default;
1209
1211 ValueBase& operator=(ValueBase&& other) noexcept(
1212 std::allocator_traits<
1213 allocator_type>::propagate_on_container_move_assignment::value || // NOLINT(cppcoreguidelines-noexcept-move-operations, performance-noexcept-move-constructor)
1214 std::allocator_traits<allocator_type>::is_always_equal::value) = default;
1215
1221 [[nodiscard]] GREM_ALWAYS_INLINE bool isNull() const noexcept {
1222 return this->template is<Null>();
1223 }
1224
1232 [[nodiscard]] GREM_ALWAYS_INLINE Null& getNull() & {
1233 if (!this->template is<Null>()) {
1234 throw json::Error{"Expected null.", source};
1235 }
1236 return this->template as<Null>();
1237 }
1238
1246 [[nodiscard]] GREM_ALWAYS_INLINE const Null& getNull() const& {
1247 if (!this->template is<Null>()) {
1248 throw json::Error{"Expected null.", source};
1249 }
1250 return this->template as<Null>();
1251 }
1252
1260 [[nodiscard]] GREM_ALWAYS_INLINE Null&& getNull() && {
1261 if (!this->template is<Null>()) {
1262 throw json::Error{"Expected null.", source};
1263 }
1264 return std::move(*this).template as<Null>();
1265 }
1266
1274 [[nodiscard]] GREM_ALWAYS_INLINE const Null& getNull() const&& {
1275 if (!this->template is<Null>()) {
1276 throw json::Error{"Expected null.", source};
1277 }
1278 return std::move(*this).template as<Null>();
1279 }
1280
1286 [[nodiscard]] GREM_ALWAYS_INLINE bool isBoolean() const noexcept {
1287 return this->template is<Boolean>();
1288 }
1289
1299 if (!this->template is<Boolean>()) {
1300 throw json::Error{"Expected a boolean.", source};
1301 }
1302 return this->template as<Boolean>();
1303 }
1304
1313 [[nodiscard]] GREM_ALWAYS_INLINE const Boolean& getBoolean() const& {
1314 if (!this->template is<Boolean>()) {
1315 throw json::Error{"Expected a boolean.", source};
1316 }
1317 return this->template as<Boolean>();
1318 }
1319
1329 if (!this->template is<Boolean>()) {
1330 throw json::Error{"Expected a boolean.", source};
1331 }
1332 return std::move(*this).template as<Boolean>();
1333 }
1334
1343 [[nodiscard]] GREM_ALWAYS_INLINE const Boolean&& getBoolean() const&& {
1344 if (!this->template is<Boolean>()) {
1345 throw json::Error{"Expected a boolean.", source};
1346 }
1347 return std::move(*this).template as<Boolean>();
1348 }
1349
1355 [[nodiscard]] GREM_ALWAYS_INLINE bool isString() const noexcept {
1356 return this->template is<String>();
1357 }
1358
1368 if (!this->template is<StringBase<Allocator>>()) {
1369 throw json::Error{"Expected a string.", source};
1370 }
1371 return this->template as<StringBase<Allocator>>();
1372 }
1373
1383 if (!this->template is<StringBase<Allocator>>()) {
1384 throw json::Error{"Expected a string.", source};
1385 }
1386 return this->template as<StringBase<Allocator>>();
1387 }
1388
1398 if (!this->template is<StringBase<Allocator>>()) {
1399 throw json::Error{"Expected a string.", source};
1400 }
1401 return std::move(*this).template as<StringBase<Allocator>>();
1402 }
1403
1412 [[nodiscard]] GREM_ALWAYS_INLINE const StringBase<Allocator>&& getString() const&& {
1413 if (!this->template is<StringBase<Allocator>>()) {
1414 throw json::Error{"Expected a string.", source};
1415 }
1416 return std::move(*this).template as<StringBase<Allocator>>();
1417 }
1418
1424 [[nodiscard]] GREM_ALWAYS_INLINE bool isNumber() const noexcept {
1425 return this->template is<Number>();
1426 }
1427
1437 if (!this->template is<Number>()) {
1438 throw json::Error{"Expected a number.", source};
1439 }
1440 return this->template as<Number>();
1441 }
1442
1451 [[nodiscard]] GREM_ALWAYS_INLINE const Number& getNumber() const& {
1452 if (!this->template is<Number>()) {
1453 throw json::Error{"Expected a number.", source};
1454 }
1455 return this->template as<Number>();
1456 }
1457
1466 [[nodiscard]] GREM_ALWAYS_INLINE Number&& getNumber() && {
1467 if (!this->template is<Number>()) {
1468 throw json::Error{"Expected a number.", source};
1469 }
1470 return std::move(*this).template as<Number>();
1471 }
1472
1481 [[nodiscard]] GREM_ALWAYS_INLINE const Number&& getNumber() const&& {
1482 if (!this->template is<Number>()) {
1483 throw json::Error{"Expected a number.", source};
1484 }
1485 return std::move(*this).template as<Number>();
1486 }
1487
1499 template <typename T>
1500 [[nodiscard]] GREM_ALWAYS_INLINE T getNumber() const {
1501 const json::Number number = getNumber();
1502 if constexpr (integral<T>) {
1503 if (trunc(number) != number) {
1504 throw json::Error{"Expected an integer.", source};
1505 }
1506 if (number < static_cast<json::Number>(Limits<T>::MIN) || number > static_cast<json::Number>(Limits<T>::MAX)) {
1507 throw json::Error{"Value out of range.", source};
1508 }
1509 }
1510 return static_cast<T>(number);
1511 }
1512
1518 [[nodiscard]] GREM_ALWAYS_INLINE bool isObject() const noexcept {
1519 return this->template is<Object>();
1520 }
1521
1531 if (!this->template is<ObjectBase<Allocator>>()) {
1532 throw json::Error{"Expected an object.", source};
1533 }
1534 return this->template as<ObjectBase<Allocator>>();
1535 }
1536
1546 if (!this->template is<ObjectBase<Allocator>>()) {
1547 throw json::Error{"Expected an object.", source};
1548 }
1549 return this->template as<ObjectBase<Allocator>>();
1550 }
1551
1561 if (!this->template is<ObjectBase<Allocator>>()) {
1562 throw json::Error{"Expected an object.", source};
1563 }
1564 return std::move(*this).template as<ObjectBase<Allocator>>();
1565 }
1566
1575 [[nodiscard]] GREM_ALWAYS_INLINE const ObjectBase<Allocator>&& getObject() const&& {
1576 if (!this->template is<ObjectBase<Allocator>>()) {
1577 throw json::Error{"Expected an object.", source};
1578 }
1579 return std::move(*this).template as<ObjectBase<Allocator>>();
1580 }
1581
1587 [[nodiscard]] GREM_ALWAYS_INLINE bool isArray() const noexcept {
1588 return this->template is<Array>();
1589 }
1590
1599 [[nodiscard]] GREM_ALWAYS_INLINE size_t getArraySize() const {
1600 if (!this->template is<ArrayBase<Allocator>>()) {
1601 throw json::Error{"Expected an array.", source};
1602 }
1603 return this->template as<ArrayBase<Allocator>>().size();
1604 }
1605
1615 if (!this->template is<ArrayBase<Allocator>>()) {
1616 throw json::Error{"Expected an array.", source};
1617 }
1618 return this->template as<ArrayBase<Allocator>>();
1619 }
1620
1629 [[nodiscard]] GREM_ALWAYS_INLINE const ArrayBase<Allocator>& getArray() const& {
1630 if (!this->template is<ArrayBase<Allocator>>()) {
1631 throw json::Error{"Expected an array.", source};
1632 }
1633 return this->template as<ArrayBase<Allocator>>();
1634 }
1635
1645 if (!this->template is<ArrayBase<Allocator>>()) {
1646 throw json::Error{"Expected an array.", source};
1647 }
1648 return std::move(*this).template as<ArrayBase<Allocator>>();
1649 }
1650
1659 [[nodiscard]] GREM_ALWAYS_INLINE const ArrayBase<Allocator>&& getArray() const&& {
1660 if (!this->template is<ArrayBase<Allocator>>()) {
1661 throw json::Error{"Expected an array.", source};
1662 }
1663 return std::move(*this).template as<ArrayBase<Allocator>>();
1664 }
1665
1675 [[nodiscard]] GREM_ALWAYS_INLINE bool hasProperty(StringView key) const noexcept {
1676 return isObject() && this->template as<ObjectBase<Allocator>>().contains(key);
1677 }
1678
1690 if (isObject()) {
1691 ObjectBase<Allocator>& object = this->template as<ObjectBase<Allocator>>();
1692 if (const auto it = object.find(key); it != object.end()) {
1693 return &it->second;
1694 }
1695 }
1696 return nullptr;
1697 }
1698
1709 [[nodiscard]] GREM_ALWAYS_INLINE const ValueBase<Allocator>* findProperty(StringView key) const noexcept {
1710 if (isObject()) {
1711 const ObjectBase<Allocator>& object = this->template as<ObjectBase<Allocator>>();
1712 if (const auto it = object.find(key); it != object.end()) {
1713 return &it->second;
1714 }
1715 }
1716 return nullptr;
1717 }
1718
1731 ObjectBase<Allocator>& object = getObject();
1732 const auto it = object.find(key);
1733 if (it == object.end()) {
1734 throw json::Error{formatString("Missing property \"{}\".", key), source};
1735 }
1736 return it->second;
1737 }
1738
1751 const ObjectBase<Allocator>& object = getObject();
1752 const auto it = object.find(key);
1753 if (it == object.end()) {
1754 throw json::Error{formatString("Missing property \"{}\".", key), source};
1755 }
1756 return it->second;
1757 }
1758
1771 ObjectBase<Allocator>&& object = std::move(*this).getObject();
1772 const auto it = object.find(key);
1773 if (it == object.end()) {
1774 throw json::Error{formatString("Missing property \"{}\".", key), source};
1775 }
1776 return std::move(it->second);
1777 }
1778
1791 const ObjectBase<Allocator>&& object = std::move(*this).getObject();
1792 const auto it = object.find(key);
1793 if (it == object.end()) {
1794 throw json::Error{formatString("Missing property \"{}\".", key), source};
1795 }
1796 return std::move(it->second);
1797 }
1798
1807 [[nodiscard]] GREM_ALWAYS_INLINE bool hasItem(size_t index) const noexcept {
1808 return isArray() && index < this->template as<ArrayBase<Allocator>>().size();
1809 }
1810
1821 [[nodiscard]] GREM_ALWAYS_INLINE ValueBase<Allocator>* findItem(size_t index) noexcept {
1822 if (isArray()) {
1823 ArrayBase<Allocator>& array = this->template as<ArrayBase<Allocator>>();
1824 if (index < array.size()) {
1825 return &array[index];
1826 }
1827 }
1828 return nullptr;
1829 }
1830
1841 [[nodiscard]] GREM_ALWAYS_INLINE const ValueBase<Allocator>* findItem(size_t index) const noexcept {
1842 if (isArray()) {
1843 const ArrayBase<Allocator>& array = this->template as<ArrayBase<Allocator>>();
1844 if (index < array.size()) {
1845 return &array[index];
1846 }
1847 }
1848 return nullptr;
1849 }
1850
1863 ArrayBase<Allocator>& array = getArray();
1864 if (index >= array.size()) {
1865 throw json::Error{formatString("Missing item \"[{}]\".", index), source};
1866 }
1867 return array[index];
1868 }
1869
1881 [[nodiscard]] GREM_ALWAYS_INLINE const ValueBase<Allocator>& getItem(size_t index) const& {
1882 const ArrayBase<Allocator>& array = getArray();
1883 if (index >= array.size()) {
1884 throw json::Error{formatString("Missing item \"[{}]\".", index), source};
1885 }
1886 return array[index];
1887 }
1888
1901 ArrayBase<Allocator>&& array = std::move(*this).getArray();
1902 if (index >= array.size()) {
1903 throw json::Error{formatString("Missing item \"[{}]\".", index), source};
1904 }
1905 return std::move(array[index]);
1906 }
1907
1919 [[nodiscard]] GREM_ALWAYS_INLINE const ValueBase<Allocator>&& getItem(size_t index) const&& {
1920 const ArrayBase<Allocator>&& array = std::move(*this).getArray();
1921 if (index >= array.size()) {
1922 throw json::Error{formatString("Missing item \"[{}]\".", index), source};
1923 }
1924 return std::move(array[index]);
1925 }
1926
1940 return getProperty(key).getNull();
1941 }
1942
1955 [[nodiscard]] GREM_ALWAYS_INLINE const Null& getNullProperty(StringView key) const& {
1956 return getProperty(key).getNull();
1957 }
1958
1972 return std::move(*this).getProperty(key).getNull();
1973 }
1974
1988 [[nodiscard]] GREM_ALWAYS_INLINE const Null& getNullProperty(StringView key) const&& {
1989 return std::move(*this).getProperty(key).getNull();
1990 }
1991
2004 [[nodiscard]] GREM_ALWAYS_INLINE Null& getNullItem(size_t index) & {
2005 return getItem(index).getNull();
2006 }
2007
2020 [[nodiscard]] GREM_ALWAYS_INLINE const Null& getNullItem(size_t index) const& {
2021 return getItem(index).getNull();
2022 }
2023
2036 [[nodiscard]] GREM_ALWAYS_INLINE Null&& getNullItem(size_t index) && {
2037 return std::move(*this).getItem(index).getNull();
2038 }
2039
2052 [[nodiscard]] GREM_ALWAYS_INLINE const Null& getNullItem(size_t index) const&& {
2053 return std::move(*this).getItem(index).getNull();
2054 }
2055
2070 return getProperty(key).getBoolean();
2071 }
2072
2086 [[nodiscard]] GREM_ALWAYS_INLINE const Boolean& getBooleanProperty(StringView key) const& {
2087 return getProperty(key).getBoolean();
2088 }
2089
2104 return std::move(*this).getProperty(key).getBoolean();
2105 }
2106
2121 [[nodiscard]] GREM_ALWAYS_INLINE const Boolean& getBooleanProperty(StringView key) const&& {
2122 return std::move(*this).getProperty(key).getBoolean();
2123 }
2124
2138 return getItem(index).getBoolean();
2139 }
2140
2153 [[nodiscard]] GREM_ALWAYS_INLINE const Boolean& getBooleanItem(size_t index) const& {
2154 return getItem(index).getBoolean();
2155 }
2156
2169 [[nodiscard]] GREM_ALWAYS_INLINE Boolean&& getBooleanItem(size_t index) && {
2170 return std::move(*this).getItem(index).getBoolean();
2171 }
2172
2185 [[nodiscard]] GREM_ALWAYS_INLINE const Boolean& getBooleanItem(size_t index) const&& {
2186 return std::move(*this).getItem(index).getBoolean();
2187 }
2188
2203 return getProperty(key).getString();
2204 }
2205
2219 [[nodiscard]] GREM_ALWAYS_INLINE const String& getStringProperty(StringView key) const& {
2220 return getProperty(key).getString();
2221 }
2222
2237 return std::move(*this).getProperty(key).getString();
2238 }
2239
2254 [[nodiscard]] GREM_ALWAYS_INLINE const String& getStringProperty(StringView key) const&& {
2255 return std::move(*this).getProperty(key).getString();
2256 }
2257
2271 return getItem(index).getString();
2272 }
2273
2286 [[nodiscard]] GREM_ALWAYS_INLINE const String& getStringItem(size_t index) const& {
2287 return getItem(index).getString();
2288 }
2289
2302 [[nodiscard]] GREM_ALWAYS_INLINE String&& getStringItem(size_t index) && {
2303 return std::move(*this).getItem(index).getString();
2304 }
2305
2318 [[nodiscard]] GREM_ALWAYS_INLINE const String& getStringItem(size_t index) const&& {
2319 return std::move(*this).getItem(index).getString();
2320 }
2321
2336 return getProperty(key).getNumber();
2337 }
2338
2352 [[nodiscard]] GREM_ALWAYS_INLINE const Number& getNumberProperty(StringView key) const& {
2353 return getProperty(key).getNumber();
2354 }
2355
2370 return std::move(*this).getProperty(key).getNumber();
2371 }
2372
2387 [[nodiscard]] GREM_ALWAYS_INLINE const Number& getNumberProperty(StringView key) const&& {
2388 return std::move(*this).getProperty(key).getNumber();
2389 }
2390
2408 template <typename T>
2410 return getProperty(key).template getNumber<T>();
2411 }
2412
2426 return getItem(index).getNumber();
2427 }
2428
2441 [[nodiscard]] GREM_ALWAYS_INLINE const Number& getNumberItem(size_t index) const& {
2442 return getItem(index).getNumber();
2443 }
2444
2457 [[nodiscard]] GREM_ALWAYS_INLINE Number&& getNumberItem(size_t index) && {
2458 return std::move(*this).getItem(index).getNumber();
2459 }
2460
2473 [[nodiscard]] GREM_ALWAYS_INLINE const Number& getNumberItem(size_t index) const&& {
2474 return std::move(*this).getItem(index).getNumber();
2475 }
2476
2494 template <typename T>
2495 [[nodiscard]] GREM_ALWAYS_INLINE T getNumberItem(size_t index) const {
2496 return getItem(index).template getNumber<T>();
2497 }
2498
2513 return getProperty(key).getObject();
2514 }
2515
2529 [[nodiscard]] GREM_ALWAYS_INLINE const Object& getObjectProperty(StringView key) const& {
2530 return getProperty(key).getObject();
2531 }
2532
2547 return std::move(*this).getProperty(key).getObject();
2548 }
2549
2564 [[nodiscard]] GREM_ALWAYS_INLINE const Object& getObjectProperty(StringView key) const&& {
2565 return std::move(*this).getProperty(key).getObject();
2566 }
2567
2581 return getItem(index).getObject();
2582 }
2583
2596 [[nodiscard]] GREM_ALWAYS_INLINE const Object& getObjectItem(size_t index) const& {
2597 return getItem(index).getObject();
2598 }
2599
2612 [[nodiscard]] GREM_ALWAYS_INLINE Object&& getObjectItem(size_t index) && {
2613 return std::move(*this).getItem(index).getObject();
2614 }
2615
2628 [[nodiscard]] GREM_ALWAYS_INLINE const Object& getObjectItem(size_t index) const&& {
2629 return std::move(*this).getItem(index).getObject();
2630 }
2631
2646 return getProperty(key).getArray();
2647 }
2648
2662 [[nodiscard]] GREM_ALWAYS_INLINE const Array& getArrayProperty(StringView key) const& {
2663 return getProperty(key).getArray();
2664 }
2665
2680 return std::move(*this).getProperty(key).getArray();
2681 }
2682
2697 [[nodiscard]] GREM_ALWAYS_INLINE const Array& getArrayProperty(StringView key) const&& {
2698 return std::move(*this).getProperty(key).getArray();
2699 }
2700
2713 [[nodiscard]] GREM_ALWAYS_INLINE Array& getArrayItem(size_t index) & {
2714 return getItem(index).getArray();
2715 }
2716
2729 [[nodiscard]] GREM_ALWAYS_INLINE const Array& getArrayItem(size_t index) const& {
2730 return getItem(index).getArray();
2731 }
2732
2745 [[nodiscard]] GREM_ALWAYS_INLINE Array&& getArrayItem(size_t index) && {
2746 return std::move(*this).getItem(index).getArray();
2747 }
2748
2761 [[nodiscard]] GREM_ALWAYS_INLINE const Array& getArrayItem(size_t index) const&& {
2762 return std::move(*this).getItem(index).getArray();
2763 }
2764
2770 [[nodiscard]] GREM_ALWAYS_INLINE SourceLocation getSource() const noexcept {
2771 return source;
2772 }
2773
2782 [[nodiscard]] GREM_ALWAYS_INLINE bool operator==(const ValueBase& other) const {
2783 return static_cast<const VariantBase<Allocator>&>(*this) == static_cast<const VariantBase<Allocator>&>(other);
2784 }
2785
2786private:
2787 SourceLocation source{.lineNumber = 0, .columnNumber = 0};
2788};
2789
2795
2803[[nodiscard]] constexpr bool isWhitespace(char32_t codePoint) noexcept {
2804 return codePoint == '\t' || codePoint == '\n' || codePoint == '\v' || codePoint == '\f' || codePoint == '\r' || codePoint == ' ' || codePoint == 0x00A0 ||
2805 codePoint == 0x1680 || (codePoint >= 0x2000 && codePoint <= 0x200A) || codePoint == 0x2028 || codePoint == 0x2029 || codePoint == 0x202F || codePoint == 0x205F ||
2806 codePoint == 0x3000 || codePoint == 0xFEFF;
2807}
2808
2816[[nodiscard]] constexpr bool isPunctuationCharacter(char32_t codePoint) noexcept {
2817 return codePoint == ',' || codePoint == ':' || codePoint == '[' || codePoint == ']' || codePoint == '{' || codePoint == '}';
2818}
2819
2829[[nodiscard]] constexpr bool isLineTerminatorCharacter(char32_t codePoint) noexcept {
2830 return codePoint == '\n' || codePoint == '\r' || codePoint == 0x2028 || codePoint == 0x2029;
2831}
2832
2858
2862template <template <typename> typename Allocator>
2868
2875template <typename It, template <typename> typename Allocator = std::allocator>
2876class Lexer {
2877public:
2879 using allocator_type = Allocator<VariantBase<Allocator>>;
2880
2883
2896 : it(std::move(it))
2897 , end(end)
2898 , source(source)
2899 , allocator(allocator) {}
2900
2902 Lexer(const Lexer& other, const allocator_type& allocator)
2903 : it(other.it)
2904 , end(other.end)
2905 , source(other.source)
2906 , currentCodePoint(other.currentCodePoint)
2907 , allocator(allocator) {}
2908
2910 Lexer(Lexer&& other, const allocator_type& allocator) noexcept // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
2911 : it(other.it)
2912 , end(other.end)
2913 , source(other.source)
2914 , currentCodePoint(other.currentCodePoint)
2915 , allocator(allocator) {}
2916
2918 ~Lexer() = default;
2919
2921 Lexer(const Lexer& other)
2922 : Lexer(other, std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator())) {}
2923
2925 Lexer(Lexer&& other) noexcept
2926 : Lexer(std::move(other), other.get_allocator()) {}
2927
2929 Lexer& operator=(const Lexer& other) {
2930 if (this == &other) {
2931 return *this;
2932 }
2933 it = other.it;
2934 end = other.end;
2935 source = other.source;
2936 currentCodePoint = other.currentCodePoint;
2937 if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_copy_assignment::value) {
2938 allocator = other.allocator;
2939 }
2940 return *this;
2941 }
2942
2944 Lexer& operator=(Lexer&& other) noexcept {
2945 if (this == &other) {
2946 return *this;
2947 }
2948 it = other.it;
2949 end = other.end;
2950 source = other.source;
2951 currentCodePoint = other.currentCodePoint;
2952 if constexpr (std::allocator_traits<allocator_type>::propagate_on_container_move_assignment::value) {
2953 allocator = other.allocator;
2954 }
2955 return *this;
2956 }
2957
2963 [[nodiscard]] allocator_type get_allocator() const noexcept {
2964 return allocator;
2965 }
2966
2981 skipWhitespace();
2982 if (hasReachedEnd()) {
2983 return {.string{allocator}, .source = source, .type = TokenType::END_OF_FILE};
2984 }
2985 switch (peek()) {
2986 case '{': [[fallthrough]];
2987 case '}': [[fallthrough]];
2988 case '[': [[fallthrough]];
2989 case ']': [[fallthrough]];
2990 case ':': [[fallthrough]];
2991 case ',': return scanPunctuator();
2992 case '\"': [[fallthrough]];
2993 case '\'': return scanString();
2994 case '0': [[fallthrough]];
2995 case '1': [[fallthrough]];
2996 case '2': [[fallthrough]];
2997 case '3': [[fallthrough]];
2998 case '4': [[fallthrough]];
2999 case '5': [[fallthrough]];
3000 case '6': [[fallthrough]];
3001 case '7': [[fallthrough]];
3002 case '8': [[fallthrough]];
3003 case '9': [[fallthrough]];
3004 case '+': [[fallthrough]];
3005 case '-': [[fallthrough]];
3006 case '.': return scanNumber();
3007 default: return scanIdentifier();
3008 }
3009 }
3010
3011private:
3012 void skipWhitespace() {
3013 while (!hasReachedEnd()) {
3014 if (isWhitespace(peek())) {
3015 if (isLineTerminatorCharacter(peek())) {
3016 skipLineTerminatorSequence();
3017 } else {
3018 advance();
3019 }
3020 } else if (peek() == '/') {
3021 advance();
3022 if (hasReachedEnd()) {
3023 throw json::Error{"Invalid token.", source};
3024 }
3025 if (peek() == '/') {
3026 advance();
3027 while (!hasReachedEnd()) {
3028 if (isLineTerminatorCharacter(peek())) {
3029 skipLineTerminatorSequence();
3030 break;
3031 }
3032 advance();
3033 }
3034 } else if (peek() == '*') {
3035 advance();
3036 while (!hasReachedEnd()) {
3037 if (isLineTerminatorCharacter(peek())) {
3038 skipLineTerminatorSequence();
3039 } else if (peek() == '*') {
3040 advance();
3041 if (!hasReachedEnd() && peek() == '/') {
3042 advance();
3043 break;
3044 }
3045 } else {
3046 advance();
3047 }
3048 }
3049 } else {
3050 throw json::Error{"Invalid token.", source};
3051 }
3052 } else {
3053 break;
3054 }
3055 }
3056 }
3057
3058 void skipLineTerminatorSequence() {
3059 if (peek() == '\r') {
3060 advance();
3061 if (!hasReachedEnd() && peek() == '\n') {
3062 advance();
3063 }
3064 } else {
3065 advance();
3066 }
3067 ++source.lineNumber;
3068 source.columnNumber = 1;
3069 }
3070
3071 void advance() {
3072 if (!currentCodePoint) {
3073 ++it;
3074 }
3075 currentCodePoint.reset();
3076 ++source.columnNumber;
3077 }
3078
3079 [[nodiscard]] bool hasReachedEnd() const noexcept {
3080 return it == end && !currentCodePoint;
3081 }
3082
3083 [[nodiscard]] char32_t peek() const {
3084 if (!currentCodePoint) {
3085 currentCodePoint = *it++;
3086 }
3087 return *currentCodePoint;
3088 }
3089
3090 [[nodiscard]] Optional<char32_t> lookahead() const {
3091 if (!currentCodePoint) {
3092 currentCodePoint = *it++;
3093 }
3094 if (it != end) {
3095 return *it;
3096 }
3097 return {};
3098 }
3099
3100 [[nodiscard]] Token scanPunctuator() {
3101 StringBase<Allocator> string{1, static_cast<char>(peek()), allocator};
3102 const SourceLocation punctuatorSource = source;
3103 TokenType type{};
3104 switch (peek()) {
3105 case ',': type = TokenType::PUNCTUATOR_COMMA; break;
3106 case ':': type = TokenType::PUNCTUATOR_COLON; break;
3107 case '[': type = TokenType::PUNCTUATOR_OPEN_SQUARE_BRACKET; break;
3108 case ']': type = TokenType::PUNCTUATOR_CLOSE_SQUARE_BRACKET; break;
3109 case '{': type = TokenType::PUNCTUATOR_OPEN_CURLY_BRACE; break;
3110 case '}': type = TokenType::PUNCTUATOR_CLOSE_CURLY_BRACE; break;
3111 default: break;
3112 }
3113 advance();
3114 return {.string = std::move(string), .source = punctuatorSource, .type = type};
3115 }
3116
3117 [[nodiscard]] Token scanString() {
3118 const char32_t quoteCharacter = peek();
3119 StringBase<Allocator> string{allocator};
3120 const SourceLocation stringSource = source;
3121 advance();
3122 while (!hasReachedEnd()) {
3123 if (!unicode::isValidCodePoint(peek())) {
3124 throw json::Error{"Invalid UTF-8.", source};
3125 }
3126 if (peek() == quoteCharacter) {
3127 advance();
3128 return {.string = std::move(string), .source = stringSource, .type = TokenType::STRING};
3129 }
3130 if (isLineTerminatorCharacter(peek())) {
3131 throw json::Error{"Unexpected line terminator in string.", source};
3132 }
3133 if (peek() != '\\') {
3134 const InplaceBuffer<char8_t, 4> codePointUTF8 = unicode::encodeUTF8FromCodePoint(peek());
3135 string.append(StringView{std::launder(reinterpret_cast<const char*>(codePointUTF8.data())), codePointUTF8.size()});
3136 advance();
3137 continue;
3138 }
3139 advance();
3140 if (hasReachedEnd()) {
3141 throw json::Error{"Empty escape sequence.", source};
3142 }
3143 if (isLineTerminatorCharacter(peek())) {
3144 skipLineTerminatorSequence();
3145 continue;
3146 }
3147 switch (peek()) {
3148 case '\"': string.push_back('\"'); break;
3149 case '\'': string.push_back('\''); break;
3150 case '\\': string.push_back('\\'); break;
3151 case 'b': string.push_back('\b'); break;
3152 case 'f': string.push_back('\f'); break;
3153 case 'n': string.push_back('\n'); break;
3154 case 'r': string.push_back('\r'); break;
3155 case 't': string.push_back('\t'); break;
3156 case 'v': string.push_back('\v'); break;
3157 case '0': [[fallthrough]];
3158 case '1': [[fallthrough]];
3159 case '2': [[fallthrough]];
3160 case '3': [[fallthrough]];
3161 case '4': [[fallthrough]];
3162 case '5': [[fallthrough]];
3163 case '6': [[fallthrough]];
3164 case '7': [[fallthrough]];
3165 case '8': [[fallthrough]];
3166 case '9': scanNumericEscapeSequence(string, 1, 3, 8, [](char32_t codePoint) noexcept -> bool { return (codePoint >= '0' && codePoint <= '7'); }); continue;
3167 case 'x':
3168 advance();
3169 scanNumericEscapeSequence(string, 2, 2, 16, [](char32_t codePoint) noexcept -> bool {
3170 return (codePoint >= '0' && codePoint <= '9') || (codePoint >= 'a' && codePoint <= 'f') || (codePoint >= 'A' && codePoint <= 'F');
3171 });
3172 continue;
3173 case 'u':
3174 advance();
3175 scanNumericEscapeSequence(string, 4, 4, 16, [](char32_t codePoint) noexcept -> bool {
3176 return (codePoint >= '0' && codePoint <= '9') || (codePoint >= 'a' && codePoint <= 'f') || (codePoint >= 'A' && codePoint <= 'F');
3177 });
3178 continue;
3179 case 'U':
3180 advance();
3181 scanNumericEscapeSequence(string, 8, 8, 16, [](char32_t codePoint) noexcept -> bool {
3182 return (codePoint >= '0' && codePoint <= '9') || (codePoint >= 'a' && codePoint <= 'f') || (codePoint >= 'A' && codePoint <= 'F');
3183 });
3184 continue;
3185 default: {
3186 const InplaceBuffer<char8_t, 4> codePointUTF8 = unicode::encodeUTF8FromCodePoint(peek());
3187 string.append(StringView{std::launder(reinterpret_cast<const char*>(codePointUTF8.data())), codePointUTF8.size()});
3188 break;
3189 }
3190 }
3191 advance();
3192 }
3193 throw json::Error{"Missing end of string quote character.", source};
3194 }
3195
3196 [[nodiscard]] Token scanNumber() {
3197 StringBase<Allocator> string{allocator};
3198 const SourceLocation numberSource = source;
3199 bool negative = false;
3200 if (peek() == '+') {
3201 advance();
3202 } else if (peek() == '-') {
3203 string.push_back('-');
3204 advance();
3205 negative = true;
3206 }
3207 if (hasReachedEnd()) {
3208 throw json::Error{"Missing number.", source};
3209 }
3210 if (peek() == 'I') {
3211 if (scanIdentifier().type == TokenType::NUMBER_POSITIVE_INFINITY) {
3212 return {.string{allocator}, .source = numberSource, .type = (negative) ? TokenType::NUMBER_NEGATIVE_INFINITY : TokenType::NUMBER_POSITIVE_INFINITY};
3213 }
3214 throw json::Error{"Invalid number.", numberSource};
3215 }
3216 if (peek() == 'N') {
3217 if (scanIdentifier().type == TokenType::NUMBER_POSITIVE_NAN) {
3218 return {.string{allocator}, .source = numberSource, .type = (negative) ? TokenType::NUMBER_NEGATIVE_NAN : TokenType::NUMBER_POSITIVE_NAN};
3219 }
3220 throw json::Error{"Invalid number.", numberSource};
3221 }
3222 TokenType type = TokenType::NUMBER_DECIMAL;
3223 if (!hasReachedEnd() && peek() == '0') {
3224 string.push_back('0');
3225 advance();
3226 if (!hasReachedEnd() && (peek() == 'b' || peek() == 'B')) {
3227 string.push_back('b');
3228 advance();
3229 type = TokenType::NUMBER_BINARY;
3230 } else if (!hasReachedEnd() && (peek() == 'x' || peek() == 'X')) {
3231 string.push_back('x');
3232 advance();
3233 type = TokenType::NUMBER_HEXADECIMAL;
3234 } else if (hasReachedEnd() || peek() != '.') {
3235 type = TokenType::NUMBER_OCTAL;
3236 }
3237 }
3238 bool eNotation = false;
3239 bool fraction = false;
3240 while (!hasReachedEnd()) {
3241 if (peek() == '.') {
3242 if (lookahead() == '.') {
3243 break;
3244 }
3245 if (type != TokenType::NUMBER_DECIMAL) {
3246 break;
3247 }
3248 if (eNotation) {
3249 throw json::Error{"Decimal point in E notation exponent.", source};
3250 }
3251 if (fraction) {
3252 throw json::Error{"Multiple decimal points in number.", source};
3253 }
3254 string.push_back('.');
3255 advance();
3256 fraction = true;
3257 } else if ((peek() == 'e' || peek() == 'E') && type != TokenType::NUMBER_HEXADECIMAL) {
3258 if (type != TokenType::NUMBER_DECIMAL) {
3259 break;
3260 }
3261 if (eNotation) {
3262 throw json::Error{"Multiple exponent symbols in E notation.", source};
3263 }
3264 string.push_back('e');
3265 advance();
3266 eNotation = true;
3267 fraction = true;
3268 if (hasReachedEnd()) {
3269 throw json::Error{"Missing exponent in E notation.", source};
3270 }
3271 if (peek() >= '0' && peek() <= '9') {
3272 string.push_back(static_cast<char>(peek()));
3273 advance();
3274 } else if ((peek() == '+' || peek() == '-')) {
3275 string.push_back(static_cast<char>(peek()));
3276 advance();
3277 if (!hasReachedEnd() && peek() >= '0' && peek() <= '9') {
3278 string.push_back(static_cast<char>(peek()));
3279 advance();
3280 } else {
3281 throw json::Error{"Missing exponent in E notation.", source};
3282 }
3283 }
3284 } else if ( //
3285 (type == TokenType::NUMBER_BINARY && (peek() == '0' || peek() == '1')) || //
3286 (type == TokenType::NUMBER_OCTAL && (peek() >= '0' && peek() <= '7')) || //
3287 (type == TokenType::NUMBER_DECIMAL && (peek() >= '0' && peek() <= '9')) || //
3288 (type == TokenType::NUMBER_HEXADECIMAL && ((peek() >= '0' && peek() <= '9') || (peek() >= 'a' && peek() <= 'f') || (peek() >= 'A' && peek() <= 'F')))) {
3289 string.push_back(static_cast<char>(peek()));
3290 advance();
3291 } else if (peek() == '_') {
3292 advance();
3293 } else {
3294 break;
3295 }
3296 }
3297 if (!hasReachedEnd()) {
3298 if (!isWhitespace(peek()) && !isPunctuationCharacter(peek()) && peek() != '\"' && peek() != '\'' && peek() != '/') {
3299 throw json::Error{"Invalid character after number.", source};
3300 }
3301 }
3302 return {.string = std::move(string), .source = numberSource, .type = type};
3303 }
3304
3305 [[nodiscard]] Token scanIdentifier() {
3306 StringBase<Allocator> string{allocator};
3307 const SourceLocation identifierSource = source;
3308 do {
3309 if (!unicode::isValidCodePoint(peek())) {
3310 throw json::Error{"Invalid UTF-8.", source};
3311 }
3312 const InplaceBuffer<char8_t, 4> codePointUTF8 = unicode::encodeUTF8FromCodePoint(peek());
3313 string.append(StringView{std::launder(reinterpret_cast<const char*>(codePointUTF8.data())), codePointUTF8.size()});
3314 advance();
3315 } while (!hasReachedEnd() && !isWhitespace(peek()) && !isPunctuationCharacter(peek()) && peek() != '\"' && peek() != '\'' && peek() != '/');
3316 TokenType type = TokenType::IDENTIFIER_NAME;
3317 if (string == "null") {
3318 string = {};
3319 type = TokenType::IDENTIFIER_NULL;
3320 } else if (string == "false") {
3321 string = {};
3322 type = TokenType::IDENTIFIER_FALSE;
3323 } else if (string == "true") {
3324 string = {};
3325 type = TokenType::IDENTIFIER_TRUE;
3326 } else if (string == "Infinity") {
3327 string = {};
3328 type = TokenType::NUMBER_POSITIVE_INFINITY;
3329 } else if (string == "NaN") {
3330 string = {};
3331 type = TokenType::NUMBER_POSITIVE_NAN;
3332 }
3333 return {.string = std::move(string), .source = identifierSource, .type = type};
3334 }
3335
3336 void scanNumericEscapeSequence(StringBase<Allocator>& output, size_t minDigitCount, size_t maxDigitCount, int radix, bool (*isDigit)(char32_t) noexcept) {
3337 const SourceLocation escapeSequenceSource = source;
3338 StringBase<Allocator> digits{allocator};
3339 digits.reserve(maxDigitCount);
3340 while (digits.size() < maxDigitCount && !hasReachedEnd() && isDigit(peek())) {
3341 digits.push_back(static_cast<char>(peek()));
3342 advance();
3343 }
3344 if (digits.size() < minDigitCount) {
3345 throw json::Error{"Invalid escape sequence length.", escapeSequenceSource};
3346 }
3347 const char* const digitsBegin = digits.data();
3348 const char* const digitsEnd = digitsBegin + digits.size();
3349 uint32_t codePointValue = 0;
3350 if (const std::from_chars_result parseResult = std::from_chars(digitsBegin, digitsEnd, codePointValue, radix);
3351 parseResult.ec != std::errc{} || parseResult.ptr != digitsEnd || !unicode::isValidCodePoint(static_cast<char32_t>(codePointValue))) {
3352 throw json::Error{"Invalid code point value.", escapeSequenceSource};
3353 }
3354 const InplaceBuffer<char8_t, 4> codePointUTF8 = unicode::encodeUTF8FromCodePoint(static_cast<char32_t>(codePointValue));
3355 output.append(StringView{std::launder(reinterpret_cast<const char*>(codePointUTF8.data())), codePointUTF8.size()});
3356 }
3357
3358 mutable unicode::UTF8Iterator<It> it;
3359 unicode::UTF8Sentinel end;
3360 SourceLocation source;
3361 mutable Optional<char32_t> currentCodePoint{};
3362 [[no_unique_address]] allocator_type allocator;
3363};
3364
3373template <typename It, template <typename> typename Allocator = std::allocator>
3374class Parser {
3375public:
3377 using allocator_type = Allocator<ValueBase<Allocator>>;
3378
3381
3386 public:
3396 virtual void visitNull(const SourceLocation& source, Null value) {
3397 (void)value;
3398 throw json::Error{"Unexpected null.", source};
3399 }
3400
3410 virtual void visitBoolean(const SourceLocation& source, Boolean value) {
3411 (void)value;
3412 throw json::Error{"Unexpected boolean.", source};
3413 }
3414
3424 virtual void visitString(const SourceLocation& source, StringBase<Allocator>&& value) {
3425 (void)std::move(value);
3426 throw json::Error{"Unexpected string.", source};
3427 }
3428
3438 virtual void visitNumber(const SourceLocation& source, Number value) {
3439 (void)value;
3440 throw json::Error{"Unexpected number.", source};
3441 }
3442
3457 virtual void visitObject(const SourceLocation& source, Parser& parser) {
3458 (void)parser;
3459 throw json::Error{"Unexpected object.", source};
3460 }
3461
3476 virtual void visitArray(const SourceLocation& source, Parser& parser) {
3477 (void)parser;
3478 throw json::Error{"Unexpected array.", source};
3479 }
3480
3481 protected:
3482 ~ValueVisitor() = default;
3483 };
3484
3491 template <typename Visitor>
3493 Visitor visitor;
3494
3497
3498 void visitNull(const SourceLocation& source, Null value) override {
3499 if constexpr (requires { visitor.visitNull(source, value); }) {
3500 visitor.visitNull(source, value);
3501 } else {
3502 ValueVisitor::visitNull(source, value);
3503 }
3504 }
3505
3506 void visitBoolean(const SourceLocation& source, Boolean value) override {
3507 if constexpr (requires { visitor.visitBoolean(source, value); }) {
3508 visitor.visitBoolean(source, value);
3509 } else {
3510 ValueVisitor::visitBoolean(source, value);
3511 }
3512 }
3513
3514 void visitString(const SourceLocation& source, StringBase<Allocator>&& value) override {
3515 if constexpr (requires { visitor.visitString(source, std::move(value)); }) {
3516 visitor.visitString(source, std::move(value));
3517 } else {
3518 ValueVisitor::visitString(source, std::move(value));
3519 }
3520 }
3521
3522 void visitNumber(const SourceLocation& source, Number value) override {
3523 if constexpr (requires { visitor.visitNumber(source, value); }) {
3524 visitor.visitNumber(source, value);
3525 } else {
3526 ValueVisitor::visitNumber(source, value);
3527 }
3528 }
3529
3530 void visitObject(const SourceLocation& source, Parser& parser) override {
3531 if constexpr (requires { visitor.visitObject(source, parser); }) {
3532 visitor.visitObject(source, parser);
3533 } else {
3534 ValueVisitor::visitObject(source, parser);
3535 }
3536 }
3537
3538 void visitArray(const SourceLocation& source, Parser& parser) override {
3539 if constexpr (requires { visitor.visitArray(source, parser); }) {
3540 visitor.visitArray(source, parser);
3541 } else {
3542 ValueVisitor::visitArray(source, parser);
3543 }
3544 }
3545 };
3546
3552 public:
3569 virtual void visitProperty(const SourceLocation& source, StringBase<Allocator>&& key, Parser& parser) = 0;
3570
3571 protected:
3572 ~PropertyVisitor() = default;
3573 };
3574
3581 template <typename Visitor>
3583 Visitor visitor;
3584
3587
3588 void visitProperty(const SourceLocation& source, StringBase<Allocator>&& key, Parser& parser) override {
3589 if constexpr (requires { visitor.visitProperty(source, std::move(key), parser); }) {
3590 visitor.visitProperty(source, std::move(key), parser);
3591 }
3592 }
3593 };
3594
3600 // clang-format off
3601 void visitNull(const SourceLocation& source, Null value) override { (void)source; (void)value; }
3602 void visitBoolean(const SourceLocation& source, Boolean value) override { (void)source; (void)value; }
3603 void visitString(const SourceLocation& source, StringBase<Allocator>&& value) override { (void)source; (void)std::move(value); }
3604 void visitNumber(const SourceLocation& source, Number value) override { (void)source; (void)value; }
3605 void visitObject(const SourceLocation& source, Parser& parser) override { (void)source; parser.parseObject(SkipPropertyVisitor{}); }
3606 void visitArray(const SourceLocation& source, Parser& parser) override { (void)source; parser.parseArray(SkipValueVisitor{}); }
3607 // clang-format on
3608 };
3609
3615 // clang-format off
3616 void visitProperty(const SourceLocation& source, StringBase<Allocator>&& key, Parser& parser) override { (void)source; (void)std::move(key); parser.parseValue(SkipValueVisitor{}); }
3617 // clang-format on
3618 };
3619
3626 explicit Parser(Lexer<It, Allocator> lexer, const allocator_type& allocator = allocator_type())
3627 : lexer(std::move(lexer), allocator) {}
3628
3638 explicit Parser(unicode::UTF8View codePoints, const SourceLocation& source = {}, const allocator_type& allocator = allocator_type()) requires(same_as<It, const char8_t*>)
3639 : Parser(Lexer<It, Allocator>{codePoints.begin(), codePoints.end(), source, allocator}) {}
3640
3650 explicit Parser(UTF8StringView jsonString, const SourceLocation& source = {}, const allocator_type& allocator = allocator_type()) requires(same_as<It, const char8_t*>)
3651 : Parser(unicode::UTF8View{jsonString}, source, allocator) {}
3652
3663 explicit Parser(StringView jsonString, const SourceLocation& source = {}, const allocator_type& allocator = allocator_type()) requires(same_as<It, const char8_t*>)
3664 : Parser(unicode::UTF8View{jsonString}, source, allocator) {}
3665
3674 explicit Parser(std::istream& stream, const SourceLocation& source = {}, const allocator_type& allocator = allocator_type())
3675 requires(same_as<It, std::istreambuf_iterator<char>>)
3676 : Parser(Lexer<It, Allocator>{unicode::UTF8Iterator<It>{It{stream}, It{}}, unicode::UTF8Sentinel{}, source, allocator}) {}
3677
3686 explicit Parser(std::streambuf* streambuf, const SourceLocation& source = {}, const allocator_type& allocator = allocator_type())
3687 requires(same_as<It, std::istreambuf_iterator<char>>)
3688 : Parser(Lexer<It, Allocator>{unicode::UTF8Iterator<It>{It{streambuf}, It{}}, unicode::UTF8Sentinel{}, source, allocator}) {}
3689
3691 Parser(const Parser& other, const allocator_type& allocator)
3692 : lexer(other.lexer, allocator) {
3693 if (other.currentToken) {
3694 currentToken = Token{
3695 .string{other.currentToken->string, allocator},
3696 .source = other.currentToken->source,
3697 .type = other.currentToken->type,
3698 };
3699 }
3700 }
3701
3703 Parser(Parser&& other, const allocator_type& allocator) noexcept // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
3704 : lexer(std::move(other.lexer), allocator) {
3705 if (other.currentToken) {
3706 currentToken = Token{
3707 .string{std::move(other.currentToken->string), allocator},
3708 .source = other.currentToken->source,
3709 .type = other.currentToken->type,
3710 };
3711 }
3712 }
3713
3715 ~Parser() = default;
3716
3718 Parser(const Parser& other)
3719 : Parser(other, std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator())) {}
3720
3722 Parser(Parser&& other) noexcept
3723 : Parser(std::move(other), other.get_allocator()) {}
3724
3726 Parser& operator=(const Parser&) = default;
3727
3729 Parser& operator=(Parser&&) noexcept = default;
3730
3736 [[nodiscard]] allocator_type get_allocator() const noexcept {
3737 return lexer.get_allocator();
3738 }
3739
3762 void parseFile(ValueVisitor& visitor) {
3763 parseValue(visitor);
3764 if (const Token& token = peek(); token.type != TokenType::END_OF_FILE) {
3765 throw json::Error{"Multiple top-level values.", token.source};
3766 }
3767 }
3768
3790 void parseValue(ValueVisitor& visitor) {
3791 switch (const Token& token = peek(); token.type) {
3792 case TokenType::END_OF_FILE: throw json::Error{"Expected a value.", token.source};
3794 advance();
3795 visitor.visitNull(token.source, Null{});
3796 break;
3798 advance();
3799 visitor.visitBoolean(token.source, Boolean{false});
3800 break;
3802 advance();
3803 visitor.visitBoolean(token.source, Boolean{true});
3804 break;
3805 case TokenType::IDENTIFIER_NAME: throw json::Error{"Unexpected name identifier.", token.source};
3806 case TokenType::PUNCTUATOR_COMMA: throw json::Error{"Unexpected comma.", token.source};
3807 case TokenType::PUNCTUATOR_COLON: throw json::Error{"Unexpected colon.", token.source};
3809 const SourceLocation source = token.source;
3810 visitor.visitArray(source, *this);
3811 break;
3812 }
3813 case TokenType::PUNCTUATOR_CLOSE_SQUARE_BRACKET: throw json::Error{"Unexpected closing bracket.", token.source};
3815 const SourceLocation source = token.source;
3816 visitor.visitObject(source, *this);
3817 break;
3818 }
3819 case TokenType::PUNCTUATOR_CLOSE_CURLY_BRACE: throw json::Error{"Unexpected closing brace.", token.source};
3820 case TokenType::STRING: visitor.visitString(token.source, std::move(eat().string)); break;
3821 case TokenType::NUMBER_BINARY: visitor.visitNumber(token.source, parseNumberContents(eat(), 2)); break;
3822 case TokenType::NUMBER_OCTAL: visitor.visitNumber(token.source, parseNumberContents(eat(), 8)); break;
3823 case TokenType::NUMBER_DECIMAL: visitor.visitNumber(token.source, parseNumberContents(eat(), 10)); break;
3824 case TokenType::NUMBER_HEXADECIMAL: visitor.visitNumber(token.source, parseNumberContents(eat(), 16)); break;
3826 advance();
3827 visitor.visitNumber(token.source, Number{Limits<Number>::INF});
3828 break;
3830 advance();
3831 visitor.visitNumber(token.source, Number{-Limits<Number>::INF});
3832 break;
3834 advance();
3835 visitor.visitNumber(token.source, Number{Limits<Number>::QUIET_NAN});
3836 break;
3838 advance();
3839 visitor.visitNumber(token.source, Number{-Limits<Number>::QUIET_NAN});
3840 break;
3841 }
3842 }
3843
3860 void parseObject(PropertyVisitor& visitor) {
3861 if (const Token& token = peek(); token.type != TokenType::PUNCTUATOR_OPEN_CURLY_BRACE) {
3862 throw json::Error{"Expected an object.", token.source};
3863 }
3864 advance();
3865 while (true) {
3867 switch (const Token& token = peek(); token.type) {
3868 case TokenType::END_OF_FILE: throw json::Error{"Missing end of object.", token.source};
3869 case TokenType::IDENTIFIER_NULL: throw json::Error{"Unexpected null.", token.source};
3870 case TokenType::IDENTIFIER_FALSE: throw json::Error{"Unexpected false.", token.source};
3871 case TokenType::IDENTIFIER_TRUE: throw json::Error{"Unexpected true.", token.source};
3872 case TokenType::IDENTIFIER_NAME: [[fallthrough]];
3873 case TokenType::STRING: key = std::move(eat().string); break;
3874 case TokenType::PUNCTUATOR_COMMA: [[fallthrough]];
3875 case TokenType::PUNCTUATOR_COLON: [[fallthrough]];
3876 case TokenType::PUNCTUATOR_OPEN_SQUARE_BRACKET: [[fallthrough]];
3877 case TokenType::PUNCTUATOR_CLOSE_SQUARE_BRACKET: [[fallthrough]];
3878 case TokenType::PUNCTUATOR_OPEN_CURLY_BRACE: throw json::Error{"Unexpected punctuator.", token.source};
3880 case TokenType::NUMBER_BINARY: [[fallthrough]];
3881 case TokenType::NUMBER_OCTAL: [[fallthrough]];
3882 case TokenType::NUMBER_DECIMAL: [[fallthrough]];
3883 case TokenType::NUMBER_HEXADECIMAL: [[fallthrough]];
3884 case TokenType::NUMBER_POSITIVE_INFINITY: [[fallthrough]];
3885 case TokenType::NUMBER_NEGATIVE_INFINITY: [[fallthrough]];
3886 case TokenType::NUMBER_POSITIVE_NAN: [[fallthrough]];
3887 case TokenType::NUMBER_NEGATIVE_NAN: throw json::Error{"Unexpected number.", token.source};
3888 }
3889 if (const Token token = eat(); token.type != TokenType::PUNCTUATOR_COLON) {
3890 throw json::Error{"Expected a colon.", token.source};
3891 }
3892 const SourceLocation source = peek().source;
3893 visitor.visitProperty(source, std::move(key), *this);
3894 if (peek().source == source) {
3895 skipValue();
3896 }
3897 if (const Token& token = peek(); token.type == TokenType::PUNCTUATOR_COMMA) {
3898 advance();
3899 } else if (token.type == TokenType::PUNCTUATOR_CLOSE_CURLY_BRACE) {
3900 advance();
3901 break;
3902 } else {
3903 throw json::Error{"Expected a comma or closing brace.", token.source};
3904 }
3905 }
3906 }
3907
3928 void parseArray(ValueVisitor& visitor) {
3929 if (const Token& token = peek(); token.type != TokenType::PUNCTUATOR_OPEN_SQUARE_BRACKET) {
3930 throw json::Error{"Expected an array.", token.source};
3931 }
3932 advance();
3933 while (true) {
3935 advance();
3936 return;
3937 }
3938 parseValue(visitor);
3939 if (const Token& token = peek(); token.type == TokenType::PUNCTUATOR_COMMA) {
3940 advance();
3941 } else if (token.type == TokenType::PUNCTUATOR_CLOSE_SQUARE_BRACKET) {
3942 advance();
3943 break;
3944 } else {
3945 throw json::Error{"Expected a comma or closing bracket.", token.source};
3946 }
3947 }
3948 }
3949
3953 void parseFile(ValueVisitor&& visitor) { // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
3954 parseFile(visitor);
3955 }
3956
3960 void parseValue(ValueVisitor&& visitor) { // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
3961 parseValue(visitor);
3962 }
3963
3967 void parseObject(PropertyVisitor&& visitor) { // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
3968 parseObject(visitor);
3969 }
3970
3974 void parseArray(ValueVisitor&& visitor) { // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
3975 parseArray(visitor);
3976 }
3977
3981 template <typename Visitor>
3982 void parseFile(Visitor visitor) {
3983 parseFile(static_cast<ValueVisitor&&>(ConcreteValueVisitor<Visitor>{std::move(visitor)}));
3984 }
3985
3989 template <typename Visitor>
3990 void parseValue(Visitor visitor) {
3991 parseValue(static_cast<ValueVisitor&&>(ConcreteValueVisitor<Visitor>{std::move(visitor)}));
3992 }
3993
3997 template <typename Visitor>
3998 void parseObject(Visitor visitor) {
3999 parseObject(static_cast<PropertyVisitor&&>(ConcretePropertyVisitor<Visitor>{std::move(visitor)}));
4000 }
4001
4005 template <typename Visitor>
4006 void parseArray(Visitor visitor) {
4007 parseArray(static_cast<ValueVisitor&&>(ConcreteValueVisitor<Visitor>{std::move(visitor)}));
4008 }
4009
4023 void skipFile() {
4024 parseFile(SkipValueVisitor{});
4025 }
4026
4039 void skipValue() {
4040 parseValue(SkipValueVisitor{});
4041 }
4042
4061 if (const Token& token = peek(); token.type != TokenType::END_OF_FILE) {
4062 throw json::Error{"Multiple top-level values.", token.source};
4063 }
4064 return result;
4065 }
4066
4089 struct Visitor final : ValueVisitor {
4091 allocator_type allocator;
4092
4093 Visitor(Optional<ValueBase<Allocator>>& result, const allocator_type& allocator)
4094 : result(result)
4095 , allocator(allocator) {}
4096
4097 // clang-format off
4098 void visitNull(const SourceLocation& source, Null value) override { result.emplace(VariantBase<Allocator>{value, allocator}, source); }
4099 void visitBoolean(const SourceLocation& source, Boolean value) override { result.emplace(VariantBase<Allocator>{value, allocator}, source); }
4100 void visitString(const SourceLocation& source, StringBase<Allocator>&& value) override { result.emplace(VariantBase<Allocator>{std::move(value), allocator}, source); }
4101 void visitNumber(const SourceLocation& source, Number value) override { result.emplace(VariantBase<Allocator>{value, allocator}, source); }
4102 void visitObject(const SourceLocation& source, Parser& parser) override { result.emplace(VariantBase<Allocator>{parser.parseObject(), allocator}, source); }
4103 void visitArray(const SourceLocation& source, Parser& parser) override { result.emplace(VariantBase<Allocator>{parser.parseArray(), allocator}, source); }
4104 // clang-format on
4105 };
4107 parseValue(Visitor{result, get_allocator()});
4108 return std::move(*result);
4109 }
4110
4126 const Token token = eat();
4127 switch (token.type) {
4128 case TokenType::IDENTIFIER_NULL: return Null{};
4129 default: break;
4130 }
4131 throw json::Error{"Expected null.", token.source};
4132 }
4133
4147 [[nodiscard]] bool peekIsNull() const {
4148 return peek().type == TokenType::IDENTIFIER_NULL;
4149 }
4150
4166 const Token token = eat();
4167 switch (token.type) {
4168 case TokenType::IDENTIFIER_FALSE: return Boolean{false};
4169 case TokenType::IDENTIFIER_TRUE: return Boolean{true};
4170 default: break;
4171 }
4172 throw json::Error{"Expected a boolean.", token.source};
4173 }
4174
4189 [[nodiscard]] bool peekIsBoolean() const {
4190 switch (peek().type) {
4191 case TokenType::IDENTIFIER_FALSE: [[fallthrough]];
4192 case TokenType::IDENTIFIER_TRUE: return true;
4193 default: break;
4194 }
4195 return false;
4196 }
4197
4213 Token token = eat();
4214 switch (token.type) {
4215 case TokenType::STRING: return std::move(token.string);
4216 default: break;
4217 }
4218 throw json::Error{"Expected a string.", token.source};
4219 }
4220
4234 [[nodiscard]] bool peekIsString() const {
4235 return peek().type == TokenType::STRING;
4236 }
4237
4253 const Token token = eat();
4254 switch (token.type) {
4255 case TokenType::NUMBER_BINARY: return parseNumberContents(token, 2);
4256 case TokenType::NUMBER_OCTAL: return parseNumberContents(token, 8);
4257 case TokenType::NUMBER_DECIMAL: return parseNumberContents(token, 10);
4258 case TokenType::NUMBER_HEXADECIMAL: return parseNumberContents(token, 16);
4263 default: break;
4264 }
4265 throw json::Error{"Expected a number.", token.source};
4266 }
4267
4281 [[nodiscard]] bool peekIsNumber() const {
4282 switch (peek().type) {
4283 case TokenType::NUMBER_BINARY: [[fallthrough]];
4284 case TokenType::NUMBER_OCTAL: [[fallthrough]];
4285 case TokenType::NUMBER_DECIMAL: [[fallthrough]];
4286 case TokenType::NUMBER_HEXADECIMAL: [[fallthrough]];
4287 case TokenType::NUMBER_POSITIVE_INFINITY: [[fallthrough]];
4288 case TokenType::NUMBER_NEGATIVE_INFINITY: [[fallthrough]];
4289 case TokenType::NUMBER_POSITIVE_NAN: [[fallthrough]];
4290 case TokenType::NUMBER_NEGATIVE_NAN: return true;
4291 default: break;
4292 }
4293 return false;
4294 }
4295
4312 const Token& token = peek();
4313 switch (token.type) {
4315 struct Visitor final : PropertyVisitor {
4316 ObjectBase<Allocator>& result;
4317
4318 explicit Visitor(ObjectBase<Allocator>& result) noexcept
4319 : result(result) {}
4320
4321 void visitProperty(const SourceLocation&, StringBase<Allocator>&& key, Parser& parser) override {
4322 result.emplace(std::move(key), parser.parseValue());
4323 }
4324 };
4326 parseObject(Visitor{result});
4327 return result;
4328 }
4329 default: break;
4330 }
4331 throw json::Error{"Expected an object.", token.source};
4332 }
4333
4347 [[nodiscard]] bool peekIsObject() const {
4349 }
4350
4367 const Token& token = peek();
4368 switch (token.type) {
4370 struct Visitor final : ValueVisitor {
4371 ArrayBase<Allocator>& result;
4372
4373 explicit Visitor(ArrayBase<Allocator>& result)
4374 : result(result) {}
4375
4376 // clang-format off
4377 void visitNull(const SourceLocation& source, Null value) override { result.emplace_back(VariantBase<Allocator>{value, result.get_allocator()}, source); }
4378 void visitBoolean(const SourceLocation& source, Boolean value) override { result.emplace_back(VariantBase<Allocator>{value, result.get_allocator()}, source); }
4379 void visitString(const SourceLocation& source, StringBase<Allocator>&& value) override { result.emplace_back(VariantBase<Allocator>{std::move(value)}, source); }
4380 void visitNumber(const SourceLocation& source, Number value) override { result.emplace_back(VariantBase<Allocator>{value, result.get_allocator()}, source); }
4381 void visitObject(const SourceLocation& source, Parser& parser) override { result.emplace_back(VariantBase<Allocator>{parser.parseObject()}, source); }
4382 void visitArray(const SourceLocation& source, Parser& parser) override { result.emplace_back(VariantBase<Allocator>{parser.parseArray()}, source); }
4383 // clang-format on
4384 };
4386 parseArray(Visitor{result});
4387 return result;
4388 }
4389 default: break;
4390 }
4391 throw json::Error{"Expected an array.", token.source};
4392 }
4393
4407 [[nodiscard]] bool peekIsArray() const {
4409 }
4410
4420 void advance() {
4421 if (!currentToken) {
4422 lexer.scan();
4423 }
4424 currentToken.reset();
4425 }
4426
4445 [[nodiscard]] const Token& peek() const {
4446 if (!currentToken) {
4447 currentToken = lexer.scan();
4448 }
4449 return *currentToken;
4450 }
4451
4465 [[nodiscard]] Token eat() {
4466 if (!currentToken) {
4467 currentToken = lexer.scan();
4468 }
4469 Token result = std::move(*currentToken);
4470 currentToken.reset();
4471 return result;
4472 }
4473
4474private:
4475 [[nodiscard]] static Number parseNumberContents(const Token& token, int radix) {
4476 const char* numberStringBegin = token.string.c_str();
4477 const char* const numberStringEnd = token.string.data() + token.string.size();
4478 char* endPointer = const_cast<char*>(numberStringEnd);
4479 if (radix == 10) {
4480 const double numberValue = std::strtod(numberStringBegin, &endPointer);
4481 if (endPointer != numberStringEnd) {
4482 throw json::Error{"Invalid number.", token.source};
4483 }
4484 return Number{numberValue};
4485 }
4486 bool negative = false;
4487 if (!token.string.empty() && token.string.front() == '-') {
4488 negative = true;
4489 ++numberStringBegin;
4490 }
4491 const unsigned long long integerNumberValue = std::strtoull(numberStringBegin, &endPointer, radix);
4492 if (endPointer != numberStringEnd) {
4493 throw json::Error{"Invalid number.", token.source};
4494 }
4495 const double numberValue = static_cast<double>(integerNumberValue);
4496 return Number{(negative) ? -numberValue : numberValue};
4497 }
4498
4499 mutable Lexer<It, Allocator> lexer;
4500 mutable Optional<Token> currentToken{};
4501};
4502
4506template <template <typename> typename Allocator>
4508
4514
4518template <template <typename> typename Allocator>
4520
4526
4527namespace detail {
4528
4529template <typename T>
4530[[nodiscard]] size_t getRecursiveSize(const T& value);
4531
4532} // namespace detail
4533
4550template <typename T>
4552
4568template <typename T>
4570
4594template <typename T, typename SerializerOverride = detail::NoSerializerOverride>
4595void serialize(std::ostream& stream, const T& value, const SerializationOptions& options = {}, SerializerOverride serializerOverride = {});
4596
4622template <typename T, typename DeserializerOverride = detail::NoDeserializerOverride>
4623void deserialize(std::istream& stream, T& value, const DeserializationOptions& options = {}, DeserializerOverride deserializerOverride = {}, const SourceLocation& source = {});
4624
4640template <template <typename> typename Allocator>
4641inline std::ostream& operator<<(std::ostream& stream, const ObjectBase<Allocator>& value) {
4642 json::serialize(stream, value);
4643 return stream;
4644}
4645
4664template <template <typename> typename Allocator>
4665inline std::istream& operator>>(std::istream& stream, ObjectBase<Allocator>& value) {
4666 try {
4667 json::deserialize(stream, value);
4668 } catch (const json::Error&) {
4669 stream.setstate(std::istream::failbit);
4670 }
4671 return stream;
4672}
4673
4689template <template <typename> typename Allocator>
4690inline std::ostream& operator<<(std::ostream& stream, const ArrayBase<Allocator>& value) {
4691 json::serialize(stream, value);
4692 return stream;
4693}
4694
4713template <template <typename> typename Allocator>
4714inline std::istream& operator>>(std::istream& stream, ArrayBase<Allocator>& value) {
4715 try {
4716 json::deserialize(stream, value);
4717 } catch (const json::Error&) {
4718 stream.setstate(std::istream::failbit);
4719 }
4720 return stream;
4721}
4722
4738template <template <typename> typename Allocator>
4739inline std::ostream& operator<<(std::ostream& stream, const VariantBase<Allocator>& value) {
4740 json::serialize(stream, value);
4741 return stream;
4742}
4743
4762template <template <typename> typename Allocator>
4763inline std::istream& operator>>(std::istream& stream, VariantBase<Allocator>& value) {
4764 try {
4765 json::deserialize(stream, value);
4766 } catch (const json::Error&) {
4767 stream.setstate(std::istream::failbit);
4768 }
4769 return stream;
4770}
4771
4787template <template <typename> typename Allocator>
4788inline std::ostream& operator<<(std::ostream& stream, const ValueBase<Allocator>& value) {
4789 json::serialize(stream, static_cast<const VariantBase<Allocator>&>(value));
4790 return stream;
4791}
4792
4811template <template <typename> typename Allocator>
4812inline std::istream& operator>>(std::istream& stream, ValueBase<Allocator>& value) {
4813 try {
4814 json::deserialize(stream, value);
4815 } catch (const json::Error&) {
4816 stream.setstate(std::istream::failbit);
4817 }
4818 return stream;
4819}
4820
4846template <typename T, typename SerializerOverride = detail::NoSerializerOverride, typename Allocator = std::allocator<char>>
4847inline grem::StringBase<char, std::char_traits<char>, Allocator> serializeToString(const T& value, const SerializationOptions& options = {},
4848 SerializerOverride serializerOverride = {}, const Allocator& allocator = Allocator()) {
4849 std::basic_ostringstream<char, std::char_traits<char>, Allocator> stream{std::ios_base::out, allocator};
4850 json::serialize(stream, value, options, serializerOverride);
4851 return std::move(stream).str();
4852}
4853
4880template <typename T, typename DeserializerOverride = detail::NoDeserializerOverride, typename Allocator = std::allocator<char>>
4881inline void deserializeFromString(grem::StringBase<char, std::char_traits<char>, Allocator> string, T& value, const DeserializationOptions& options = {},
4882 DeserializerOverride deserializerOverride = {}, const SourceLocation& source = {}) {
4883 std::basic_istringstream<char, std::char_traits<char>, Allocator> stream{std::move(string)}; // NOLINT(performance-move-const-arg)
4884 json::deserialize(stream, value, options, deserializerOverride, source);
4885}
4886
4914template <typename T, typename DeserializerOverride = detail::NoDeserializerOverride, typename Allocator = std::allocator<char>>
4915[[nodiscard]] inline T deserializeFromString(grem::StringBase<char, std::char_traits<char>, Allocator> string, const DeserializationOptions& options = {},
4916 DeserializerOverride deserializerOverride = {}, const SourceLocation& source = {}) {
4917 T value{};
4918 json::deserializeFromString(std::move(string), value, options, deserializerOverride, source);
4919 return value;
4920}
4921
4925struct Writer {
4926private:
4927 std::ostream& stream;
4928
4929public:
4934
4941 explicit Writer(std::ostream& stream, const SerializationOptions& options = {})
4942 : stream(stream)
4943 , options(options) {}
4944
4952 void write(char ch) {
4953 stream << ch;
4954 }
4955
4963 void write(StringView raw) {
4964 stream << raw;
4965 }
4966
4979 for (size_t i = 0; i < options.indentation; ++i) {
4980 write(options.indentationCharacter);
4981 }
4982 }
4983
4990 stream << options.newlineString;
4991 }
4992
4998 void writeNull() {
4999 write("null");
5000 }
5001
5009 void writeBoolean(Boolean value) {
5010 write((value) ? "true" : "false");
5011 }
5012
5021 constexpr CStringView HEXADECIMAL_DIGITS = "0123456789ABCDEF";
5022 write('\"');
5023 for (const char ch : value) {
5024 if (ch >= ' ' && ch <= '~' && ch != '\"' && ch != '\\') {
5025 write(ch);
5026 } else {
5027 write('\\');
5028 switch (ch) {
5029 case '\"': write('\"'); break;
5030 case '\\': write('\\'); break;
5031 case '\b': write('b'); break;
5032 case '\f': write('f'); break;
5033 case '\n': write('n'); break;
5034 case '\r': write('r'); break;
5035 case '\t': write('t'); break;
5036 case '\v': write('v'); break;
5037 case '\0': write('0'); break;
5038 default:
5039 write('x');
5040 write(HEXADECIMAL_DIGITS[(bit_cast<uint8_t>(ch) >> 4) & 0x0F]);
5041 write(HEXADECIMAL_DIGITS[(bit_cast<uint8_t>(ch) & 0x0F)]);
5042 break;
5043 }
5044 }
5045 }
5046 write('\"');
5047 }
5048
5058 static_assert(sizeof(char8_t) == sizeof(char));
5059 writeString(StringView{std::launder(reinterpret_cast<const char*>(value.data())), value.size()});
5060 }
5061
5072 void writeString(const auto& value) {
5073 if constexpr (requires { StringView{value}; }) {
5074 writeString(StringView{value});
5075 } else if constexpr (requires { UTF8StringView{value}; }) {
5077 } else {
5078 std::ostringstream stringStream{};
5079 json::serialize(stringStream, value, {.prettyPrint = false});
5080 writeString(std::move(stringStream).str());
5081 }
5082 }
5083
5091 void writeNumber(Number value) {
5092 if (std::isnan(value)) {
5093 if (std::signbit(value)) {
5094 stream << "-NaN";
5095 } else {
5096 stream << "NaN";
5097 }
5098 } else if (std::isinf(value)) {
5099 if (std::signbit(value)) {
5100 stream << "-Infinity";
5101 } else {
5102 stream << "Infinity";
5103 }
5104 } else [[likely]] {
5105 char chars[32];
5106 const std::to_chars_result result = std::to_chars(chars, chars + sizeof(chars) - 1, value);
5107 GREM_ASSERT(result.ec == std::errc{});
5108 *result.ptr = '\0';
5109 stream << static_cast<const char*>(chars);
5110 }
5111 }
5112
5134 void writeCustomObject(size_t propertyCountHint, auto callback) {
5135 write('{');
5136 if (options.prettyPrint) {
5137 if (propertyCountHint <= options.prettyPrintMaxSingleLineObjectPropertyCount) {
5138 bool empty = true;
5139 callback(WriteSmallPrettyObjectProperty{*this, empty});
5140 if (!empty) {
5141 write(' ');
5142 }
5143 } else {
5144 bool empty = true;
5145 callback(WriteLargePrettyObjectProperty{*this, empty});
5146 if (!empty) {
5147 writeNewline();
5148 options.indentation -= options.relativeIndentation;
5150 }
5151 }
5152 } else {
5153 bool successor = false;
5154 callback(WriteCompactObjectProperty{*this, successor});
5155 }
5156 write('}');
5157 }
5158
5177 void writeCustomObject(auto callback) {
5179 }
5180
5195 template <typename SerializerOverride = detail::NoSerializerOverride>
5196 void writeObject(const auto& value, SerializerOverride serializerOverride = {}) {
5197 const size_t propertyCountHint = detail::getRecursiveSize(value) - 1;
5198 writeCustomObject(propertyCountHint, [&](auto writeProperty) -> void {
5199 for (const auto& element : value) {
5200 writeProperty(element.first, element.second, [&](const auto& v) -> void { serialize(v, serializerOverride); });
5201 }
5202 });
5203 }
5204
5225 void writeCustomArray(size_t itemCountHint, auto callback) {
5226 write('[');
5227 if (options.prettyPrint) {
5228 if (itemCountHint <= options.prettyPrintMaxSingleLineArrayItemCount) {
5229 bool successor = false;
5230 callback(WriteSmallPrettyArrayItem{*this, successor});
5231 } else {
5232 bool empty = true;
5233 callback(WriteLargePrettyArrayItem{*this, empty});
5234 if (!empty) {
5235 writeNewline();
5236 options.indentation -= options.relativeIndentation;
5238 }
5239 }
5240 } else {
5241 bool successor = false;
5242 callback(WriteCompactArrayItem{*this, successor});
5243 }
5244 write(']');
5245 }
5246
5264 void writeCustomArray(auto callback) {
5266 }
5267
5282 template <typename SerializerOverride = detail::NoSerializerOverride>
5283 void writeArray(const auto& value, SerializerOverride serializerOverride = {}) {
5284 const size_t itemCountHint = detail::getRecursiveSize(value) - 1;
5285 writeCustomArray(itemCountHint, [&](auto writeItem) -> void {
5286 if constexpr (requires {
5287 std::begin(value);
5288 std::end(value);
5289 }) {
5290 for (const auto& element : value) {
5291 writeItem(element, [&](const auto& v) -> void { serialize(v, serializerOverride); });
5292 }
5293 } else {
5294 const size_t n = std::size(value);
5295 for (size_t i = 0; i < n; ++i) {
5296 const auto& element = value[i];
5297 writeItem(element, [&](const auto& v) -> void { serialize(v, serializerOverride); });
5298 }
5299 }
5300 });
5301 }
5302
5320 template <typename SerializerOverride = detail::NoSerializerOverride>
5321 void writeOptional(const auto& value, SerializerOverride serializerOverride = {}) {
5322 if (value) {
5323 serialize(*value, serializerOverride);
5324 } else {
5325 writeNull();
5326 }
5327 }
5328
5345 template <typename Aggregate, typename SerializerOverride = detail::NoSerializerOverride>
5346 void writeAggregateObject(const Aggregate& value, SerializerOverride serializerOverride = {}) {
5347 const size_t propertyCountHint = detail::getRecursiveSize(value) - 1;
5348 writeCustomObject(propertyCountHint, [&](auto writeProperty) -> void {
5349 meta::forEachNamedField(value, [&](StringView name, const auto& field) -> void { //
5350 writeProperty(name, field, [&](const auto& f) -> void { serialize(f, serializerOverride); });
5351 });
5352 });
5353 }
5354
5370 template <typename Aggregate, typename SerializerOverride = detail::NoSerializerOverride>
5371 void writeAggregateArray(const Aggregate& value, SerializerOverride serializerOverride = {}) {
5372 const size_t itemCountHint = detail::getRecursiveSize(value) - 1;
5373 writeCustomArray(itemCountHint, [&](auto writeItem) -> void {
5374 meta::forEachField(value, [&](const auto& field) -> void { //
5375 writeItem(field, [&](const auto& f) -> void { serialize(f, serializerOverride); });
5376 });
5377 });
5378 }
5379
5395 template <typename T, typename SerializerOverride = detail::NoSerializerOverride>
5396 void serialize(const T& value, SerializerOverride serializerOverride = {});
5397
5398private:
5399 struct WriteSmallPrettyObjectProperty {
5400 Writer& writer;
5401 bool& empty;
5402
5403 void operator()(const auto& key, const auto& value, auto writeValue) {
5404 if (empty) {
5405 writer.write(' ');
5406 empty = false;
5407 } else {
5408 writer.write(", ");
5409 }
5410 writer.writeString(key);
5411 writer.write(": ");
5412 writeValue(value);
5413 }
5414
5415 void operator()(const auto& key, const auto& value) {
5416 (*this)(key, value, [&](const auto& value) -> void { writer.serialize(value); });
5417 }
5418 };
5419
5420 struct WriteLargePrettyObjectProperty {
5421 Writer& writer;
5422 bool& empty;
5423
5424 void operator()(const auto& key, const auto& value, auto writeValue) {
5425 if (empty) {
5426 writer.writeNewline();
5427 writer.options.indentation += writer.options.relativeIndentation;
5428 writer.writeIndentation();
5429 empty = false;
5430 } else {
5431 writer.write(',');
5432 writer.writeNewline();
5433 writer.writeIndentation();
5434 }
5435 writer.writeString(key);
5436 writer.write(": ");
5437 writeValue(value);
5438 }
5439
5440 void operator()(const auto& key, const auto& value) {
5441 (*this)(key, value, [&](const auto& value) -> void { writer.serialize(value); });
5442 }
5443 };
5444
5445 struct WriteCompactObjectProperty {
5446 Writer& writer;
5447 bool& successor;
5448
5449 void operator()(const auto& key, const auto& value, auto writeValue) {
5450 if (successor) {
5451 writer.write(',');
5452 }
5453 successor = true;
5454 writer.writeString(key);
5455 writer.write(':');
5456 writeValue(value);
5457 }
5458
5459 void operator()(const auto& key, const auto& value) {
5460 (*this)(key, value, [&](const auto& value) -> void { writer.serialize(value); });
5461 }
5462 };
5463
5464 struct WriteSmallPrettyArrayItem {
5465 Writer& writer;
5466 bool& successor;
5467
5468 void operator()(const auto& value, auto writeValue) {
5469 if (successor) {
5470 writer.write(", ");
5471 }
5472 successor = true;
5473 writeValue(value);
5474 }
5475
5476 void operator()(const auto& value) {
5477 (*this)(value, [&](const auto& value) -> void { writer.serialize(value); });
5478 }
5479 };
5480
5481 struct WriteLargePrettyArrayItem {
5482 Writer& writer;
5483 bool& empty;
5484
5485 void operator()(const auto& value, auto writeValue) {
5486 if (empty) {
5487 writer.writeNewline();
5488 writer.options.indentation += writer.options.relativeIndentation;
5489 writer.writeIndentation();
5490 empty = false;
5491 } else {
5492 writer.write(',');
5493 writer.writeNewline();
5494 writer.writeIndentation();
5495 }
5496 writeValue(value);
5497 }
5498
5499 void operator()(const auto& value) {
5500 (*this)(value, [&](const auto& value) -> void { writer.serialize(value); });
5501 }
5502 };
5503
5504 struct WriteCompactArrayItem {
5505 Writer& writer;
5506 bool& successor;
5507
5508 void operator()(const auto& value, auto writeValue) {
5509 if (successor) {
5510 writer.write(',');
5511 }
5512 successor = true;
5513 writeValue(value);
5514 }
5515
5516 void operator()(const auto& value) {
5517 (*this)(value, [&](const auto& value) -> void { writer.serialize(value); });
5518 }
5519 };
5520};
5521
5525struct Reader {
5526private:
5527 using It = std::istreambuf_iterator<char>;
5528
5529 Parser<It> parser;
5530
5531public:
5533 using Token = typename Parser<It>::Token;
5534
5539
5548 explicit Reader(std::istream& stream, const SourceLocation& source = {}, const DeserializationOptions& options = {})
5549 : parser(stream, source)
5550 , options(options) {}
5551
5567 const SourceLocation source = parser.peek().source;
5568 parser.parseNull();
5569 return source;
5570 }
5571
5586 [[nodiscard]] bool nextIsNull() const {
5587 return parser.peekIsNull();
5588 }
5589
5609 const SourceLocation source = parser.peek().source;
5610 value = parser.parseBoolean();
5611 return source;
5612 }
5613
5628 [[nodiscard]] Boolean readBoolean() {
5629 Boolean value{};
5630 readBoolean(value);
5631 return value;
5632 }
5633
5648 [[nodiscard]] bool nextIsBoolean() const {
5649 return parser.peekIsBoolean();
5650 }
5651
5664 Optional<Boolean> value{};
5665 readOptional(value);
5666 return value;
5667 }
5668
5688 const SourceLocation source = parser.peek().source;
5689 value = parser.parseString();
5690 return source;
5691 }
5692
5710 String string{};
5711 const SourceLocation source = readString(string);
5712 convertString(value, std::move(string), source);
5713 return source;
5714 }
5715
5730 [[nodiscard]] String readString() {
5731 String value{};
5732 readString(value);
5733 return value;
5734 }
5735
5750 [[nodiscard]] bool nextIsString() const {
5751 return parser.peekIsString();
5752 }
5753
5766 Optional<String> value{};
5767 readOptional(value);
5768 return value;
5769 }
5770
5790 const SourceLocation source = parser.peek().source;
5791 value = parser.parseNumber();
5792 return source;
5793 }
5794
5811 template <typename T>
5813 Number number{};
5814 const SourceLocation source = readNumber(number);
5815 if constexpr (integral<T>) {
5816 if (trunc(number) != number) {
5817 throw json::Error{"Expected an integer.", source};
5818 }
5819 if (number < static_cast<json::Number>(Limits<T>::MIN) || number > static_cast<json::Number>(Limits<T>::MAX)) {
5820 throw json::Error{"Value out of range.", source};
5821 }
5822 }
5823 value = static_cast<T>(number);
5824 return source;
5825 }
5826
5841 [[nodiscard]] Number readNumber() {
5842 Number value{};
5843 readNumber(value);
5844 return value;
5845 }
5846
5861 [[nodiscard]] bool nextIsNumber() const {
5862 return parser.peekIsNumber();
5863 }
5864
5881 template <typename T>
5882 [[nodiscard]] T readNumber() {
5883 T value{};
5884 readNumber(value);
5885 return value;
5886 }
5887
5900 Optional<Number> value{};
5901 readOptional(value);
5902 return value;
5903 }
5904
5929 const SourceLocation source = parser.peek().source;
5930 if (const Token token = parser.eat(); token.type != TokenType::PUNCTUATOR_OPEN_CURLY_BRACE) {
5931 throw json::Error{"Expected an object.", token.source};
5932 }
5933 if (parser.peek().type == TokenType::PUNCTUATOR_CLOSE_CURLY_BRACE) {
5934 parser.advance();
5935 } else {
5936 while (true) {
5937 String propertyKey{};
5938 if (Token token = parser.eat(); token.type == TokenType::STRING || token.type == TokenType::IDENTIFIER_NAME) {
5939 propertyKey = std::move(token.string);
5940 } else {
5941 throw json::Error{"Expected a string or a name identifier.", token.source};
5942 }
5943 if (const Token token = parser.eat(); token.type != TokenType::PUNCTUATOR_COLON) {
5944 throw json::Error{"Expected a colon.", token.source};
5945 }
5946 const SourceLocation propertySource = parser.peek().source;
5947 readProperty(propertySource, propertyKey);
5948 if (parser.peek().source == propertySource) {
5949 parser.skipValue();
5950 }
5951 const Token token = parser.eat();
5952 if (token.type == TokenType::PUNCTUATOR_CLOSE_CURLY_BRACE) {
5953 break;
5954 }
5955 if (token.type == TokenType::PUNCTUATOR_COMMA) {
5956 if (parser.peek().type == TokenType::PUNCTUATOR_CLOSE_CURLY_BRACE) {
5957 parser.advance();
5958 break;
5959 }
5960 } else {
5961 throw json::Error{"Expected a comma or closing brace.", token.source};
5962 }
5963 }
5964 }
5965 return source;
5966 }
5967
5987 const SourceLocation source = parser.peek().source;
5988 value = parser.parseObject();
5989 return source;
5990 }
5991
6023 template <typename DeserializerOverride = detail::NoDeserializerOverride>
6024 SourceLocation readObject(auto& value, DeserializerOverride deserializerOverride = {}) {
6025 const SourceLocation source = parser.peek().source;
6026 if (const Token token = parser.eat(); token.type != TokenType::PUNCTUATOR_OPEN_CURLY_BRACE) {
6027 throw json::Error{"Expected an object.", token.source};
6028 }
6029 value.clear();
6030 if (parser.peek().type == TokenType::PUNCTUATOR_CLOSE_CURLY_BRACE) {
6031 parser.advance();
6032 } else {
6033 while (true) {
6034 std::remove_cvref_t<decltype(std::begin(value)->first)> propertyKey{};
6035 std::remove_cvref_t<decltype(std::begin(value)->second)> propertyValue{};
6036 if (Token token = parser.eat(); token.type == TokenType::STRING || token.type == TokenType::IDENTIFIER_NAME) {
6037 convertString(propertyKey, std::move(token.string), token.source);
6038 } else {
6039 throw json::Error{"Expected a string or a name identifier.", token.source};
6040 }
6041 if (const Token token = parser.eat(); token.type != TokenType::PUNCTUATOR_COLON) {
6042 throw json::Error{"Expected a colon.", token.source};
6043 }
6044 deserialize(propertyValue, deserializerOverride);
6045 value.emplace(std::move(propertyKey), std::move(propertyValue));
6046 const Token token = parser.eat();
6047 if (token.type == TokenType::PUNCTUATOR_CLOSE_CURLY_BRACE) {
6048 break;
6049 }
6050 if (token.type == TokenType::PUNCTUATOR_COMMA) {
6051 if (parser.peek().type == TokenType::PUNCTUATOR_CLOSE_CURLY_BRACE) {
6052 parser.advance();
6053 break;
6054 }
6055 } else {
6056 throw json::Error{"Expected a comma or closing brace.", token.source};
6057 }
6058 }
6059 }
6060 return source;
6061 }
6062
6077 [[nodiscard]] Object readObject() {
6078 Object value{};
6079 readObject(value);
6080 return value;
6081 }
6082
6108 template <typename Object>
6109 [[nodiscard]] Object readObject() {
6110 Object value{};
6111 readObject(value);
6112 return value;
6113 }
6114
6129 [[nodiscard]] bool nextIsObject() const {
6130 return parser.peekIsObject();
6131 }
6132
6145 Optional<Object> value{};
6146 readOptional(value);
6147 return value;
6148 }
6149
6172 const SourceLocation source = parser.peek().source;
6173 if (const Token token = parser.eat(); token.type != TokenType::PUNCTUATOR_OPEN_SQUARE_BRACKET) {
6174 throw json::Error{"Expected an array.", token.source};
6175 }
6176 if (parser.peek().type == TokenType::PUNCTUATOR_CLOSE_SQUARE_BRACKET) {
6177 parser.advance();
6178 } else {
6179 while (true) {
6180 const SourceLocation itemSource = parser.peek().source;
6181 readItem(itemSource);
6182 if (parser.peek().source == itemSource) {
6183 parser.skipValue();
6184 }
6185 const Token token = parser.eat();
6187 break;
6188 }
6189 if (token.type == TokenType::PUNCTUATOR_COMMA) {
6190 if (parser.peek().type == TokenType::PUNCTUATOR_CLOSE_SQUARE_BRACKET) {
6191 parser.advance();
6192 break;
6193 }
6194 } else {
6195 throw json::Error{"Expected a comma or closing bracket.", token.source};
6196 }
6197 }
6198 }
6199 return source;
6200 }
6201
6221 const SourceLocation source = parser.peek().source;
6222 value = parser.parseArray();
6223 return source;
6224 }
6225
6255 template <typename DeserializerOverride = detail::NoDeserializerOverride>
6256 SourceLocation readArray(auto& value, DeserializerOverride deserializerOverride = {}) {
6257 const SourceLocation source = parser.peek().source;
6258 if (const Token token = parser.eat(); token.type != TokenType::PUNCTUATOR_OPEN_SQUARE_BRACKET) {
6259 throw json::Error{"Expected an array.", token.source};
6260 }
6261 value.clear();
6262 if (parser.peek().type == TokenType::PUNCTUATOR_CLOSE_SQUARE_BRACKET) {
6263 parser.advance();
6264 } else {
6265 while (true) {
6266 std::remove_cvref_t<decltype(*std::begin(value))> item{};
6267 deserialize(item, deserializerOverride);
6268 value.push_back(std::move(item));
6269 const Token token = parser.eat();
6270 if (token.type == TokenType::PUNCTUATOR_CLOSE_SQUARE_BRACKET) {
6271 break;
6272 }
6273 if (token.type == TokenType::PUNCTUATOR_COMMA) {
6274 if (parser.peek().type == TokenType::PUNCTUATOR_CLOSE_SQUARE_BRACKET) {
6275 parser.advance();
6276 break;
6277 }
6278 } else {
6279 throw json::Error{"Expected a comma or closing bracket.", token.source};
6280 }
6281 }
6282 }
6283 return source;
6284 }
6285
6300 [[nodiscard]] Array readArray() {
6301 Array value{};
6302 readArray(value);
6303 return value;
6304 }
6305
6329 template <typename Array>
6330 [[nodiscard]] Array readArray() {
6331 Array value{};
6332 readArray(value);
6333 return value;
6334 }
6335
6350 [[nodiscard]] bool nextIsArray() const {
6351 return parser.peekIsArray();
6352 }
6353
6366 Optional<Array> value{};
6367 readOptional(value);
6368 return value;
6369 }
6370
6389 const SourceLocation source = parser.peek().source;
6390 value = static_cast<Variant&&>(parser.parseValue());
6391 return source;
6392 }
6393
6412 const SourceLocation source = parser.peek().source;
6413 value = parser.parseValue();
6414 return source;
6415 }
6416
6430 [[nodiscard]] Value readValue() {
6431 Value value{};
6432 readValue(value);
6433 return value;
6434 }
6435
6465 template <typename T, typename DeserializerOverride = detail::NoDeserializerOverride>
6466 SourceLocation readOptional(T& value, DeserializerOverride deserializerOverride = {}) {
6467 const SourceLocation source = parser.peek().source;
6468 if (parser.peek().type == TokenType::IDENTIFIER_NULL) {
6469 parser.advance();
6470 value = T{};
6471 } else {
6472 std::remove_cvref_t<decltype(*value)> result{};
6473 deserialize(result, deserializerOverride);
6474 value = std::move(result);
6475 }
6476 return source;
6477 }
6478
6504 template <typename Aggregate, typename DeserializerOverride = detail::NoDeserializerOverride>
6505 Optional<SourceLocation> readAggregateField(StringView fieldName, Aggregate& aggregate, DeserializerOverride deserializerOverride = {}) {
6506 const SourceLocation source = parser.peek().source;
6507 meta::forEachNamedField(aggregate, [&](StringView name, auto& field) -> void {
6508 if (fieldName == name) {
6509 deserialize(field, deserializerOverride);
6510 }
6511 });
6512 if (parser.peek().source == source) {
6513 return {};
6514 }
6515 return source;
6516 }
6517
6548 template <typename Aggregate, typename DeserializerOverride = detail::NoDeserializerOverride>
6549 SourceLocation readAggregateObject(Aggregate& value, DeserializerOverride deserializerOverride = {}) {
6550 return readCustomObject([&](const SourceLocation&, const String& key) -> void { readAggregateField(key, value, deserializerOverride); });
6551 }
6552
6579 template <typename Aggregate, typename DeserializerOverride = detail::NoDeserializerOverride>
6580 [[nodiscard]] Aggregate readAggregateObject(DeserializerOverride deserializerOverride = {}) {
6581 Aggregate result{};
6582 readAggregateObject(result, deserializerOverride);
6583 return result;
6584 }
6585
6614 template <typename Aggregate, typename DeserializerOverride = detail::NoDeserializerOverride>
6615 SourceLocation readAggregateArray(Aggregate& value, DeserializerOverride deserializerOverride = {}) {
6616 const SourceLocation source = parser.peek().source;
6617 if (const Token token = parser.eat(); token.type != TokenType::PUNCTUATOR_OPEN_SQUARE_BRACKET) {
6618 throw json::Error{"Expected an array.", token.source};
6619 }
6620 if (parser.peek().type == TokenType::PUNCTUATOR_CLOSE_SQUARE_BRACKET) {
6621 parser.advance();
6622 } else {
6623 meta::forEachField(value, [&](auto& field) -> void {
6624 const SourceLocation source = parser.peek().source;
6625 deserialize(field, deserializerOverride);
6626 if (parser.peek().source == source) {
6627 parser.skipValue();
6628 }
6629 const Token nextToken = parser.peek();
6630 if (nextToken.type == TokenType::PUNCTUATOR_CLOSE_SQUARE_BRACKET) {
6631 throw json::Error{"Expected " + toString(meta::aggregate_size_v<Aggregate>) + " items.", nextToken.source};
6632 }
6633 if (nextToken.type == TokenType::PUNCTUATOR_COMMA) {
6634 parser.advance();
6635 if (parser.peek().type == TokenType::PUNCTUATOR_CLOSE_SQUARE_BRACKET) {
6636 throw json::Error{"Expected " + toString(meta::aggregate_size_v<Aggregate>) + " items.", nextToken.source};
6637 }
6638 } else {
6639 throw json::Error{"Expected a comma or closing bracket.", nextToken.source};
6640 }
6641 });
6642 const Token token = parser.eat();
6643 if (token.type != TokenType::PUNCTUATOR_CLOSE_SQUARE_BRACKET) {
6644 throw json::Error{"Expected only " + toString(meta::aggregate_size_v<Aggregate>) + " items.", token.source};
6645 }
6646 }
6647 return source;
6648 }
6649
6674 template <typename Aggregate, typename DeserializerOverride = detail::NoDeserializerOverride>
6675 [[nodiscard]] Aggregate readAggregateArray(DeserializerOverride deserializerOverride = {}) {
6676 Aggregate result{};
6677 readAggregateArray(result, deserializerOverride);
6678 return result;
6679 }
6680
6696 template <typename T, typename DeserializerOverride = detail::NoDeserializerOverride>
6697 void deserialize(T& value, DeserializerOverride deserializerOverride = {});
6698
6716 template <typename T, typename DeserializerOverride = detail::NoDeserializerOverride>
6717 [[nodiscard]] T deserialize(DeserializerOverride deserializerOverride = {}) {
6718 T result{};
6719 deserialize(result, deserializerOverride);
6720 return result;
6721 }
6722
6723private:
6724 static void convertString(auto& value, String&& string, const SourceLocation& source) {
6725 if constexpr (requires { value = std::move(string); }) {
6726 value = std::move(string);
6727 } else if constexpr (requires { value = String{}; }) {
6728 value = String{std::move(string)};
6729 } else if constexpr (requires { value = UTF8String{}; }) {
6730 value = UTF8String{string.begin(), string.end()};
6731 } else {
6732 json::deserializeFromString(std::move(string), value, {}, {}, source);
6733 }
6734 }
6735};
6736
6737template <typename T, typename SerializerOverride>
6738inline void serialize(std::ostream& stream, const T& value, const SerializationOptions& options, SerializerOverride serializerOverride) {
6739 Writer{stream, options}.serialize(value, serializerOverride);
6740}
6741
6742template <typename T, typename DeserializerOverride>
6743inline void deserialize(std::istream& stream, T& value, const DeserializationOptions& options, DeserializerOverride deserializerOverride, const SourceLocation& source) {
6744 Reader{stream, source, options}.deserialize(value, deserializerOverride);
6745}
6746
6747namespace detail {
6748
6749struct NoVisitor {};
6750
6751template <typename Base, typename Callback>
6752struct VisitNull : Base {
6753 [[no_unique_address]] Callback callback;
6754
6755 VisitNull(Callback callback)
6756 : callback(std::move(callback)) {}
6757
6758 VisitNull(Base base, Callback callback)
6759 : Base(std::move(base))
6760 , callback(std::move(callback)) {}
6761
6762 void visitNull(const SourceLocation& source, Null value) {
6763 callback(source, value);
6764 }
6765
6766 template <typename NewBase>
6767 [[nodiscard]] auto operator|(NewBase other) && {
6768 return VisitNull<NewBase, Callback>{std::move(other), std::move(callback)};
6769 }
6770};
6771
6772template <typename Base, typename Callback>
6773struct VisitBoolean : Base {
6774 [[no_unique_address]] Callback callback;
6775
6776 VisitBoolean(Callback callback)
6777 : callback(std::move(callback)) {}
6778
6779 VisitBoolean(Base base, Callback callback)
6780 : Base(std::move(base))
6781 , callback(std::move(callback)) {}
6782
6783 void visitBoolean(const SourceLocation& source, Boolean value) {
6784 callback(source, value);
6785 }
6786
6787 template <typename NewBase>
6788 [[nodiscard]] auto operator|(NewBase other) && {
6789 return VisitBoolean<NewBase, Callback>{std::move(other), std::move(callback)};
6790 }
6791};
6792
6793template <typename Base, typename Callback>
6794struct VisitString : Base {
6795 [[no_unique_address]] Callback callback;
6796
6797 VisitString(Callback callback)
6798 : callback(std::move(callback)) {}
6799
6800 VisitString(Base base, Callback callback)
6801 : Base(std::move(base))
6802 , callback(std::move(callback)) {}
6803
6804 void visitString(const SourceLocation& source, String&& value) {
6805 callback(source, std::move(value));
6806 }
6807
6808 template <typename NewBase>
6809 [[nodiscard]] auto operator|(NewBase other) && {
6810 return VisitString<NewBase, Callback>{std::move(other), std::move(callback)};
6811 }
6812};
6813
6814template <typename Base, typename Callback>
6815struct VisitNumber : Base {
6816 [[no_unique_address]] Callback callback;
6817
6818 VisitNumber(Callback callback)
6819 : callback(std::move(callback)) {}
6820
6821 VisitNumber(Base base, Callback callback)
6822 : Base(std::move(base))
6823 , callback(std::move(callback)) {}
6824
6825 void visitNumber(const SourceLocation& source, Number value) {
6826 callback(source, value);
6827 }
6828
6829 template <typename NewBase>
6830 [[nodiscard]] auto operator|(NewBase other) && {
6831 return VisitNumber<NewBase, Callback>{std::move(other), std::move(callback)};
6832 }
6833};
6834
6835template <typename Base, typename Callback>
6836struct VisitObject : Base {
6837 [[no_unique_address]] Callback callback;
6838
6839 VisitObject(Callback callback)
6840 : callback(std::move(callback)) {}
6841
6842 VisitObject(Base base, Callback callback)
6843 : Base(std::move(base))
6844 , callback(std::move(callback)) {}
6845
6846 void visitObject(const SourceLocation& source, auto& parser) {
6847 callback(source, parser);
6848 }
6849
6850 template <typename NewBase>
6851 [[nodiscard]] auto operator|(NewBase other) && {
6852 return VisitObject<NewBase, Callback>{std::move(other), std::move(callback)};
6853 }
6854};
6855
6856template <typename Base, typename Callback>
6857struct VisitArray : Base {
6858 [[no_unique_address]] Callback callback;
6859
6860 VisitArray(Callback callback)
6861 : callback(std::move(callback)) {}
6862
6863 VisitArray(Base base, Callback callback)
6864 : Base(std::move(base))
6865 , callback(std::move(callback)) {}
6866
6867 void visitArray(const SourceLocation& source, auto& parser) {
6868 callback(source, parser);
6869 }
6870
6871 template <typename NewBase>
6872 [[nodiscard]] auto operator|(NewBase other) && {
6873 return VisitArray<NewBase, Callback>{std::move(other), std::move(callback)};
6874 }
6875};
6876
6877template <typename Base, typename Callback>
6878struct VisitProperty : Base {
6879 [[no_unique_address]] Callback callback;
6880
6881 VisitProperty(Callback callback)
6882 : callback(std::move(callback)) {}
6883
6884 VisitProperty(Base base, Callback callback)
6885 : Base(std::move(base))
6886 , callback(std::move(callback)) {}
6887
6888 template <template <typename> typename Allocator>
6889 void visitProperty(const SourceLocation& source, StringBase<Allocator>&& key, auto& parser) {
6890 callback(source, std::move(key), parser);
6891 }
6892
6893 template <typename NewBase>
6894 [[nodiscard]] auto operator|(NewBase other) && {
6895 return VisitProperty<NewBase, Callback>{std::move(other), std::move(callback)};
6896 }
6897};
6898
6899} // namespace detail
6900
6923template <typename Callback>
6924[[nodiscard]] inline auto onNull(Callback callback) {
6925 return detail::VisitNull<detail::NoVisitor, Callback>{std::move(callback)};
6926}
6927
6950template <typename Callback>
6951[[nodiscard]] inline auto onBoolean(Callback callback) {
6952 return detail::VisitBoolean<detail::NoVisitor, Callback>{std::move(callback)};
6953}
6954
6977template <typename Callback>
6978[[nodiscard]] inline auto onString(Callback callback) {
6979 return detail::VisitString<detail::NoVisitor, Callback>{std::move(callback)};
6980}
6981
7004template <typename Callback>
7005[[nodiscard]] inline auto onNumber(Callback callback) {
7006 return detail::VisitNumber<detail::NoVisitor, Callback>{std::move(callback)};
7007}
7008
7031template <typename Callback>
7032[[nodiscard]] inline auto onObject(Callback callback) {
7033 return detail::VisitObject<detail::NoVisitor, Callback>{std::move(callback)};
7034}
7035
7058template <typename Callback>
7059[[nodiscard]] inline auto onArray(Callback callback) {
7060 return detail::VisitArray<detail::NoVisitor, Callback>{std::move(callback)};
7061}
7062
7078template <typename Callback>
7079[[nodiscard]] inline auto onProperty(Callback callback) {
7080 return detail::VisitProperty<detail::NoVisitor, Callback>{std::move(callback)};
7081}
7082
7083namespace detail {
7084
7085template <template <typename> typename Allocator>
7086consteval void derivedFromStringBaseTest(const StringBase<Allocator>&);
7087
7088template <template <typename> typename Allocator>
7089consteval void derivedFromObjectBaseTest(const ObjectBase<Allocator>&);
7090
7091template <template <typename> typename Allocator>
7092consteval void derivedFromArrayBaseTest(const ArrayBase<Allocator>&);
7093
7094template <template <typename> typename Allocator>
7095consteval void derivedFromVariantBaseTest(const VariantBase<Allocator>&);
7096
7097template <typename T>
7098concept derived_from_string_base = requires(const T t) { detail::derivedFromStringBaseTest(t); };
7099
7100template <typename T>
7101concept derived_from_object_base = requires(const T t) { detail::derivedFromObjectBaseTest(t); };
7102
7103template <typename T>
7104concept derived_from_array_base = requires(const T t) { detail::derivedFromArrayBaseTest(t); };
7105
7106template <typename T>
7107concept derived_from_raw_value_base = requires(const T t) { detail::derivedFromVariantBaseTest(t); };
7108
7109template <typename T>
7110concept nullable = //
7111 !arithmetic<T> && //
7112 requires(const T value) {
7113 static_cast<bool>(value);
7114 static_cast<bool>(!value);
7115 T{};
7116 };
7117
7118template <typename T>
7119concept serializable_as_string = //
7120 derived_from_string_base<T> || //
7121 requires(const T input, T output) {
7122 StringView{input};
7123 output = String{};
7124 } || //
7125 requires(const T input, T output) {
7126 UTF8StringView{input};
7127 output = UTF8String{};
7128 };
7129
7130template <typename T>
7131concept serializable_as_string_view = //
7132 requires(const T input) { StringView{input}; } || //
7133 requires(const T input) { UTF8StringView{input}; };
7134
7135template <typename T>
7136concept serializable_as_duration = //
7137 requires(const T input, T output, const DurationBase<Number, Ratio<1, 1>> seconds) {
7138 duration_cast<DurationBase<Number, Ratio<1, 1>>>(input);
7139 output = duration_cast<T>(seconds);
7140 };
7141
7142template <typename T>
7143concept serializable_as_array = //
7144 requires(Reader& reader, Writer& writer, const T input, T output, const size_t i) {
7145 std::size(input);
7146 writer.serialize(input[i]);
7147 reader.deserialize(output[i]);
7148 };
7149
7150template <typename T>
7151concept serializable_as_map = //
7152 derived_from_object_base<T> || //
7153 requires(Reader& reader, Writer& writer, const T input, T output) {
7154 writer.writeString(std::begin(input)->first);
7155 writer.serialize(std::begin(input)->second);
7156
7157 output.clear();
7158 std::remove_cvref_t<decltype(std::begin(output)->first)>{};
7159 std::remove_cvref_t<decltype(std::begin(output)->second)>{};
7160 reader.readString(std::begin(output)->first);
7161 reader.deserialize(std::begin(output)->second);
7162 output.emplace(std::remove_cvref_t<decltype(std::begin(output)->first)>{}, std::remove_cvref_t<decltype(std::begin(output)->second)>{});
7163 };
7164
7165template <typename T>
7166concept serializable_as_list = //
7167 derived_from_array_base<T> || //
7168 requires(Reader& reader, Writer& writer, const T input, T output) {
7169 writer.serialize(*std::begin(input));
7170
7171 output.clear();
7172 std::remove_cvref_t<decltype(*std::begin(output))>{};
7173 reader.deserialize(*std::begin(output));
7174 output.push_back(std::remove_cvref_t<decltype(*std::begin(output))>{});
7175 };
7176
7177template <typename T>
7178concept serializable_as_optional = //
7179 !pointer<T> && //
7180 requires(Reader& reader, Writer& writer, const T input, T output, std::remove_cvref_t<decltype(*output)> result) {
7181 static_cast<bool>(input);
7182 writer.serialize(*input);
7183
7184 output = T{};
7185 std::remove_cvref_t<decltype(*output)>{};
7186 reader.deserialize(result);
7187 output = std::move(result);
7188 };
7189
7190template <typename T>
7191inline size_t getRecursiveSize(const T& value) {
7192 if constexpr (derived_from_raw_value_base<T>) {
7193 return match(value)([&](const auto& v) -> size_t { return getRecursiveSize(v); });
7194 } else if constexpr (serializable_as_string<T> || serializable_as_string_view<T> || serializable_as_duration<T>) {
7195 return 1;
7196 } else if constexpr (serializable_as_map<T>) {
7197 if constexpr (nullable<T>) {
7198 if (!value) {
7199 return 1;
7200 }
7201 }
7202 size_t result = 1;
7203 for (const auto& kv : value) {
7204 result += getRecursiveSize(kv.second);
7205 }
7206 return result;
7207 } else if constexpr (serializable_as_list<T> || serializable_as_array<T>) {
7208 if constexpr (nullable<T>) {
7209 if (!value) {
7210 return 1;
7211 }
7212 }
7213 size_t result = 1;
7214 if constexpr (requires {
7215 std::begin(value);
7216 std::end(value);
7217 }) {
7218 for (const auto& v : value) {
7219 result += getRecursiveSize(v);
7220 }
7221 } else {
7222 const size_t n = std::size(value);
7223 for (size_t i = 0; i < n; ++i) {
7224 const auto& v = value[i];
7225 result += getRecursiveSize(v);
7226 }
7227 }
7228 return result;
7229 } else if constexpr (serializable_as_optional<T>) {
7230 return 1;
7231 } else if constexpr (aggregate<T>) {
7232 if constexpr (nullable<T>) {
7233 if (!value) {
7234 return 1;
7235 }
7236 }
7237 size_t result = 1;
7238 meta::forEachField(value, [&](const auto& v) -> void { result += getRecursiveSize(v); });
7239 return result;
7240 } else {
7241 return 1;
7242 }
7243}
7244
7245} // namespace detail
7246
7248template <>
7249struct Serializer<Null> {
7250 void serializeTo(Writer& writer, Null) {
7251 writer.writeNull();
7252 }
7253};
7254
7255template <>
7256struct Serializer<std::nullptr_t> {
7257 void serializeTo(Writer& writer, std::nullptr_t) {
7258 writer.writeNull();
7259 }
7260};
7261
7262template <>
7263struct Serializer<Boolean> {
7264 void serializeTo(Writer& writer, Boolean value) {
7265 writer.writeBoolean(value);
7266 }
7267};
7268
7269template <strict_arithmetic Arithmetic>
7270struct Serializer<Arithmetic> {
7271 void serializeTo(Writer& writer, Arithmetic value) {
7272 writer.writeNumber(static_cast<Number>(value));
7273 }
7274};
7275
7276template <>
7277struct Serializer<char> {
7278 void serializeTo(Writer& writer, char value) {
7279 writer.writeString(StringView{&value, 1});
7280 }
7281};
7282
7283template <>
7284struct Serializer<char8_t> {
7285 void serializeTo(Writer& writer, char8_t value) {
7286 writer.writeString(UTF8StringView{&value, 1});
7287 }
7288};
7289
7290template <template <typename> typename Allocator>
7291struct Serializer<StringBase<Allocator>> {
7292 void serializeTo(Writer& writer, const StringBase<Allocator>& value) {
7293 writer.writeString(value);
7294 }
7295};
7296
7297template <template <typename> typename Allocator>
7298struct Serializer<ObjectBase<Allocator>> {
7299 void serializeTo(Writer& writer, const ObjectBase<Allocator>& value) {
7300 writer.writeObject(value);
7301 }
7302};
7303
7304template <template <typename> typename Allocator>
7305struct Serializer<ArrayBase<Allocator>> {
7306 void serializeTo(Writer& writer, const ArrayBase<Allocator>& value) {
7307 writer.writeArray(value);
7308 }
7309};
7310
7311template <template <typename> typename Allocator>
7312struct Serializer<VariantBase<Allocator>> {
7313 void serializeTo(Writer& writer, const VariantBase<Allocator>& value) {
7314 match(value)([&](const auto& v) -> void { writer.serialize(v); });
7315 }
7316};
7317
7318template <template <typename> typename Allocator>
7319struct Serializer<ValueBase<Allocator>> : Serializer<VariantBase<Allocator>> {};
7320
7321template <>
7322struct Deserializer<Null> {
7323 void deserializeFrom(Reader& reader, Null&) {
7324 reader.readNull();
7325 }
7326};
7327
7328template <>
7329struct Deserializer<std::nullptr_t> {
7330 void deserializeFrom(Reader& reader, std::nullptr_t&) {
7331 reader.readNull();
7332 }
7333};
7334
7335template <>
7336struct Deserializer<Boolean> {
7337 void deserializeFrom(Reader& reader, Boolean& value) {
7338 reader.readBoolean(value);
7339 }
7340};
7341
7342template <strict_arithmetic Arithmetic>
7343struct Deserializer<Arithmetic> {
7344 void deserializeFrom(Reader& reader, Arithmetic& value) {
7345 reader.readNumber(value);
7346 }
7347};
7348
7349template <>
7350struct Deserializer<char> {
7351 void deserializeFrom(Reader& reader, char& value) {
7352 String string{};
7353 const SourceLocation source = reader.readString(string);
7354 if (string.size() != 1) {
7355 throw json::Error{"Expected only a single character.", source};
7356 }
7357 value = string.front();
7358 }
7359};
7360
7361template <>
7362struct Deserializer<char8_t> {
7363 void deserializeFrom(Reader& reader, char8_t& value) {
7364 String string{};
7365 const SourceLocation source = reader.readString(string);
7366 if (string.size() != sizeof(char8_t)) {
7367 throw json::Error{"Expected only a single UTF-8 code unit.", source};
7368 }
7369 memcpy(&value, string.data(), sizeof(char8_t));
7370 }
7371};
7372
7373template <>
7374struct Deserializer<String> {
7375 void deserializeFrom(Reader& reader, String& value) {
7376 reader.readString(value);
7377 }
7378};
7379
7380template <>
7381struct Deserializer<Object> {
7382 void deserializeFrom(Reader& reader, Object& value) {
7383 reader.readObject(value);
7384 }
7385};
7386
7387template <>
7388struct Deserializer<Array> {
7389 void deserializeFrom(Reader& reader, Array& value) {
7390 reader.readArray(value);
7391 }
7392};
7393
7394template <>
7395struct Deserializer<Variant> {
7396 void deserializeFrom(Reader& reader, Variant& value) {
7397 reader.readValue(value);
7398 }
7399};
7400
7401template <>
7402struct Deserializer<Value> {
7403 void deserializeFrom(Reader& reader, Value& value) {
7404 reader.readValue(value);
7405 }
7406};
7408
7409template <typename T, typename SerializerOverride>
7410inline void Writer::serialize(const T& value, SerializerOverride serializerOverride) {
7411 using X = std::remove_cvref_t<T>;
7412 if constexpr (requires { serializerOverride(*this, value); }) {
7413 serializerOverride(*this, value);
7414 } else if constexpr (requires { json::Serializer<X>{}; }) {
7415 json::Serializer<X>{}.serializeTo(*this, value);
7416 } else {
7417 if constexpr (detail::nullable<X>) {
7418 if (!value) {
7419 writeNull();
7420 return;
7421 }
7422 }
7423 if constexpr (detail::serializable_as_string<X> || detail::serializable_as_string_view<X>) {
7424 writeString(value);
7425 } else if constexpr (detail::serializable_as_duration<X>) {
7426 writeNumber(duration_cast<DurationBase<Number, Ratio<1, 1>>>(value).count());
7427 } else if constexpr (detail::serializable_as_map<X>) {
7428 writeObject(value, serializerOverride);
7429 } else if constexpr (detail::serializable_as_list<X>) {
7430 writeArray(value, serializerOverride);
7431 } else if constexpr (detail::serializable_as_array<X>) {
7432 using Element = std::remove_cvref_t<decltype(value[size_t{0}])>;
7433 if constexpr (
7434 requires(const T t, const size_t i) {
7435 X::RANK;
7436 t[i] == t[i];
7437 } && !detail::serializable_as_array<Element> && requires(Element e) { X{e}; }) {
7438 const Element& element = value[size_t{0}];
7439 if (all(equal(value, X{element}))) {
7440 serialize(element, serializerOverride);
7441 return;
7442 }
7443 }
7444 writeArray(value, serializerOverride);
7445 } else if constexpr (detail::serializable_as_optional<X>) {
7446 writeOptional(value, serializerOverride);
7447 } else if constexpr (aggregate<X>) {
7448 writeAggregateObject(value, serializerOverride);
7449 } else if constexpr (enumeration<X>) {
7450 bool found = false;
7451 meta::forEachNamedEnumerand<X>([&](StringView name, auto type) -> void {
7452 if (!found && value == type) {
7453 found = true;
7454 writeString(name);
7455 }
7456 });
7457 } else {
7458 static_assert(meta::always_false_v<X>, "JSON serialization is not implemented for the given type.");
7459 }
7460 }
7461}
7462
7463template <typename T, typename DeserializerOverride>
7464inline void Reader::deserialize(T& value, DeserializerOverride deserializerOverride) {
7465 using X = std::remove_cvref_t<T>;
7466 if constexpr (requires { deserializerOverride(*this, value); }) {
7467 deserializerOverride(*this, value);
7468 } else if constexpr (requires { json::Deserializer<X>{}; }) {
7469 json::Deserializer<X>{}.deserializeFrom(*this, value);
7470 } else if constexpr (detail::serializable_as_string<X>) {
7471 readString(value);
7472 } else if constexpr (detail::serializable_as_duration<X>) {
7473 Number seconds{};
7474 readNumber(seconds);
7475 value = duration_cast<X>(DurationBase<Number, Ratio<1, 1>>{seconds});
7476 } else if constexpr (detail::serializable_as_map<X>) {
7477 readObject(value, deserializerOverride);
7478 } else if constexpr (detail::serializable_as_list<X>) {
7479 readArray(value, deserializerOverride);
7480 } else if constexpr (detail::serializable_as_array<X>) {
7481 size_t index = 0;
7482 const size_t size = std::size(value);
7483 using Element = std::remove_cvref_t<decltype(value[index])>;
7484 if constexpr (
7485 requires(const T t, const size_t i) {
7486 X::RANK;
7487 t[i] == t[i];
7488 } && !detail::serializable_as_array<Element> && requires(Element e) { X{e}; }) {
7489 if (!nextIsArray()) {
7490 value = X{deserialize<std::remove_cvref_t<decltype(value[index])>>(deserializerOverride)};
7491 return;
7492 }
7493 }
7494 const SourceLocation source = readCustomArray([&](const json::SourceLocation& source) -> void {
7495 if (index >= size) {
7496 throw json::Error{"Expected " + toString(size) + " array items.", source};
7497 }
7498 deserialize(value[index], deserializerOverride);
7499 ++index;
7500 });
7501 if (index != size) {
7502 throw json::Error{"Expected " + toString(size) + " array items.", source};
7503 }
7504 } else if constexpr (detail::serializable_as_optional<X>) {
7505 readOptional(value, deserializerOverride);
7506 } else if constexpr (aggregate<X>) {
7507 readAggregateObject(value, deserializerOverride);
7508 } else if constexpr (enumeration<X>) {
7509 json::String string{};
7510 const SourceLocation source = readString(string);
7511 Optional<X> result{};
7512 meta::forEachNamedEnumerand<X>([&](StringView name, auto type) -> void {
7513 if (!result && string == name) {
7514 result = type();
7515 }
7516 });
7517 if (!result) {
7518 throw json::Error{"Invalid type \"" + string + "\".", source};
7519 }
7520 value = *result;
7521 } else {
7522 static_assert(meta::always_false_v<X>, "JSON deserialization is not implemented for the given type.");
7523 }
7524}
7525
7526template <template <typename> typename Allocator>
7529
7530template <template <typename> typename Allocator>
7531inline ObjectBase<Allocator>::ObjectBase(const allocator_type& allocator) noexcept
7532 : membersSortedByName(allocator) {}
7533
7534template <template <typename> typename Allocator>
7535inline ObjectBase<Allocator>::~ObjectBase() = default;
7536
7537template <template <typename> typename Allocator>
7539 : membersSortedByName(other.membersSortedByName, allocator) {}
7540
7541template <template <typename> typename Allocator>
7543 : ObjectBase(other, std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator())) {}
7544
7545template <template <typename> typename Allocator>
7546inline ObjectBase<Allocator>::ObjectBase(ObjectBase&& other, const allocator_type& allocator) noexcept // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
7547 : membersSortedByName(std::move(other.membersSortedByName), allocator) {}
7548
7549template <template <typename> typename Allocator>
7551 : ObjectBase(std::move(other), other.get_allocator()) {}
7552
7553template <template <typename> typename Allocator>
7555
7556template <template <typename> typename Allocator>
7558 std::allocator_traits<
7559 allocator_type>::propagate_on_container_move_assignment::value || // NOLINT(cppcoreguidelines-noexcept-move-operations, performance-noexcept-move-constructor)
7560 std::allocator_traits<allocator_type>::is_always_equal::value) = default;
7561
7562template <template <typename> typename Allocator>
7563template <input_iterator InputIterator, sentinel_for<InputIterator> Sentinel>
7564inline ObjectBase<Allocator>::ObjectBase(InputIterator first, Sentinel last, const allocator_type& allocator)
7565 : membersSortedByName(first, last, allocator) {
7566 sort(membersSortedByName, Compare{});
7567 const auto newEnd = unique(membersSortedByName, [](const value_type& a, const value_type& b) -> bool { return a.first == b.first; });
7568 membersSortedByName.erase(newEnd, membersSortedByName.end());
7569}
7570
7571template <template <typename> typename Allocator>
7572inline ObjectBase<Allocator>::ObjectBase(std::initializer_list<value_type> ilist, const allocator_type& allocator)
7573 : ObjectBase(ilist.begin(), ilist.end(), allocator) {}
7574
7575template <template <typename> typename Allocator>
7576inline ObjectBase<Allocator>& ObjectBase<Allocator>::operator=(std::initializer_list<value_type> ilist) {
7577 membersSortedByName = ilist;
7578 sort(membersSortedByName, Compare{});
7579 const auto newEnd = unique(membersSortedByName, [](const value_type& a, const value_type& b) -> bool { return a.first == b.first; });
7580 membersSortedByName.erase(newEnd, membersSortedByName.end());
7581 return *this;
7582}
7583
7584template <template <typename> typename Allocator>
7586 return membersSortedByName.get_allocator();
7587}
7588
7589template <template <typename> typename Allocator>
7591 if (const auto it = find(key); it != end()) {
7592 return it->second;
7593 }
7594 throw std::out_of_range{"JSON object does not contain key \"" + grem::String{key} + "\"."};
7595}
7596
7597template <template <typename> typename Allocator>
7599 if (const auto it = find(key); it != end()) {
7600 return it->second;
7601 }
7602 throw std::out_of_range{"JSON object does not contain key \"" + grem::String{key} + "\"."};
7603}
7604
7605template <template <typename> typename Allocator>
7607 return try_emplace(k).first->second;
7608}
7609
7610template <template <typename> typename Allocator>
7612 return try_emplace(std::move(k)).first->second;
7613}
7614
7615template <template <typename> typename Allocator>
7617 return membersSortedByName.begin();
7618}
7619
7620template <template <typename> typename Allocator>
7622 return membersSortedByName.begin();
7623}
7624
7625template <template <typename> typename Allocator>
7627 return membersSortedByName.cbegin();
7628}
7629
7630template <template <typename> typename Allocator>
7632 return membersSortedByName.end();
7633}
7634
7635template <template <typename> typename Allocator>
7637 return membersSortedByName.end();
7638}
7639
7640template <template <typename> typename Allocator>
7642 return membersSortedByName.cend();
7643}
7644
7645template <template <typename> typename Allocator>
7647 return membersSortedByName.rbegin();
7648}
7649
7650template <template <typename> typename Allocator>
7652 return membersSortedByName.rbegin();
7653}
7654
7655template <template <typename> typename Allocator>
7657 return membersSortedByName.crbegin();
7658}
7659
7660template <template <typename> typename Allocator>
7662 return membersSortedByName.rend();
7663}
7664
7665template <template <typename> typename Allocator>
7667 return membersSortedByName.rend();
7668}
7669
7670template <template <typename> typename Allocator>
7672 return membersSortedByName.crend();
7673}
7674
7675template <template <typename> typename Allocator>
7676inline bool ObjectBase<Allocator>::empty() const noexcept {
7677 return membersSortedByName.empty();
7678}
7679
7680template <template <typename> typename Allocator>
7682 return membersSortedByName.size();
7683}
7684
7685template <template <typename> typename Allocator>
7687 return membersSortedByName.max_size();
7688}
7689
7690template <template <typename> typename Allocator>
7692 return membersSortedByName.capacity();
7693}
7694
7695template <template <typename> typename Allocator>
7696inline void ObjectBase<Allocator>::clear() noexcept {
7697 membersSortedByName.clear();
7698}
7699
7700template <template <typename> typename Allocator>
7702 membersSortedByName.reserve(newCapacity);
7703}
7704
7705template <template <typename> typename Allocator>
7706template <typename P>
7708 return emplace(std::forward<P>(value));
7709}
7710
7711template <template <typename> typename Allocator>
7712template <typename P>
7714 return emplace_hint(pos, std::forward<P>(value));
7715}
7716
7717template <template <typename> typename Allocator>
7718template <input_iterator InputIterator, sentinel_for<InputIterator> Sentinel>
7719inline void ObjectBase<Allocator>::insert(InputIterator first, Sentinel last) {
7720 const size_t offset = membersSortedByName.size();
7721 try {
7722 while (first != last) {
7723 membersSortedByName.push_back(*first++);
7724 }
7725 const auto newMembersBegin = membersSortedByName.begin() + static_cast<ptrdiff_t>(offset);
7726 sort(Subrange{newMembersBegin, membersSortedByName.end()}, Compare{});
7727 inplaceMerge(membersSortedByName, newMembersBegin);
7728 } catch (...) {
7729 membersSortedByName.resize(offset);
7730 throw;
7731 }
7732}
7733
7734template <template <typename> typename Allocator>
7735inline void ObjectBase<Allocator>::insert(std::initializer_list<value_type> ilist) {
7736 insert(ilist.begin(), ilist.end());
7737}
7738
7739template <template <typename> typename Allocator>
7740template <typename R>
7741inline void ObjectBase<Allocator>::insert_range(R&& r) { // NOLINT(cppcoreguidelines-missing-std-forward)
7742 insert(std::begin(r), std::end(r));
7743}
7744
7745template <template <typename> typename Allocator>
7746template <typename... Args>
7748 value_type value{std::forward<Args>(args)...};
7749 const auto [first, last] = equal_range(value.first);
7750 if (first != last) {
7751 return {first, false};
7752 }
7753 const auto it = membersSortedByName.insert(last, std::move(value));
7754 return {it, true};
7755}
7756
7757template <template <typename> typename Allocator>
7758template <typename... Args>
7760 return emplace(std::forward<Args>(args)...).first;
7761}
7762
7763template <template <typename> typename Allocator>
7764template <typename... Args>
7766 const auto [first, last] = equal_range(k);
7767 if (first != last) {
7768 return {first, false};
7769 }
7770 const auto it = membersSortedByName.emplace(last, std::piecewise_construct, std::forward_as_tuple(k), std::forward_as_tuple(std::forward<Args>(args)...));
7771 return {it, true};
7772}
7773
7774template <template <typename> typename Allocator>
7775template <typename... Args>
7777 const auto [first, last] = equal_range(k);
7778 if (first != last) {
7779 return {first, false};
7780 }
7781 const auto it = membersSortedByName.emplace(last, std::piecewise_construct, std::forward_as_tuple(std::move(k)), std::forward_as_tuple(std::forward<Args>(args)...));
7782 return {it, true};
7783}
7784
7785template <template <typename> typename Allocator>
7786template <typename... Args>
7788 return try_emplace(k, std::forward<Args>(args)...);
7789}
7790
7791template <template <typename> typename Allocator>
7792template <typename... Args>
7794 return try_emplace(std::move(k), std::forward<Args>(args)...);
7795}
7796
7797template <template <typename> typename Allocator>
7799 return membersSortedByName.erase(pos);
7800}
7801
7802template <template <typename> typename Allocator>
7804 const auto [first, last] = equal_range(key);
7805 const size_type count = static_cast<size_type>(last - first);
7806 membersSortedByName.erase(first, last);
7807 return count;
7808}
7809
7810template <template <typename> typename Allocator>
7811inline void ObjectBase<Allocator>::swap(ObjectBase& other) noexcept {
7812 membersSortedByName.swap(other.membersSortedByName);
7813}
7814
7815template <template <typename> typename Allocator>
7817 a.swap(b);
7818}
7819
7820template <template <typename> typename Allocator>
7822 const auto [first, last] = equal_range(key);
7823 return static_cast<size_type>(last - first);
7824}
7825
7826template <template <typename> typename Allocator>
7827inline bool ObjectBase<Allocator>::contains(StringView key) const noexcept {
7828 return count(key) > 0;
7829}
7830
7831template <template <typename> typename Allocator>
7833 if (const auto [first, last] = equal_range(key); first != last) {
7834 return first;
7835 }
7836 return end();
7837}
7838
7839template <template <typename> typename Allocator>
7841 if (const auto [first, last] = equal_range(key); first != last) {
7842 return first;
7843 }
7844 return end();
7845}
7846
7847template <template <typename> typename Allocator>
7849 const auto [first, last] = equalRange(membersSortedByName, key, Compare{});
7850 return {first, last};
7851}
7852
7853template <template <typename> typename Allocator>
7855 const auto [first, last] = equalRange(membersSortedByName, key, Compare{});
7856 return {first, last};
7857}
7858
7859template <template <typename> typename Allocator>
7861 return lowerBound(membersSortedByName, key, Compare{});
7862}
7863
7864template <template <typename> typename Allocator>
7866 return lowerBound(membersSortedByName, key, Compare{});
7867}
7868
7869template <template <typename> typename Allocator>
7871 return upperBound(membersSortedByName, key, Compare{});
7872}
7873
7874template <template <typename> typename Allocator>
7876 return upperBound(membersSortedByName, key, Compare{});
7877}
7878
7879template <template <typename> typename Allocator>
7880inline bool ObjectBase<Allocator>::operator==(const ObjectBase& other) const noexcept {
7881 return membersSortedByName == other.membersSortedByName;
7882}
7883
7884template <template <typename> typename Allocator>
7885inline std::partial_ordering ObjectBase<Allocator>::operator<=>(const ObjectBase& other) const noexcept {
7886 return std::compare_partial_order_fallback(membersSortedByName, other.membersSortedByName);
7887}
7888
7889template <template <typename> typename Allocator, typename Predicate>
7890inline typename ObjectBase<Allocator>::size_type erase_if(ObjectBase<Allocator>& container, Predicate predicate) {
7891 return erase_if(container.membersSortedByName, predicate);
7892}
7893
7894template <template <typename> typename Allocator>
7895inline bool ObjectBase<Allocator>::Compare::operator()(const value_type& a, const value_type& b) const noexcept {
7896 return a.first < b.first;
7897}
7898
7899template <template <typename> typename Allocator>
7900inline bool ObjectBase<Allocator>::Compare::operator()(const value_type& a, StringView b) const noexcept {
7901 return a.first < b;
7902}
7903
7904template <template <typename> typename Allocator>
7905inline bool ObjectBase<Allocator>::Compare::operator()(StringView a, const value_type& b) const noexcept {
7906 return a < b.first;
7907}
7908
7909template <template <typename> typename Allocator>
7910inline bool ObjectBase<Allocator>::Compare::operator()(StringView a, StringView b) const noexcept {
7911 return a < b;
7912}
7913
7914template <template <typename> typename Allocator>
7917
7918template <template <typename> typename Allocator>
7919inline ArrayBase<Allocator>::ArrayBase(const allocator_type& allocator) noexcept
7920 : values(allocator) {}
7921
7922template <template <typename> typename Allocator>
7923inline ArrayBase<Allocator>::~ArrayBase() = default;
7924
7925template <template <typename> typename Allocator>
7926inline ArrayBase<Allocator>::ArrayBase(const ArrayBase& other, const allocator_type& allocator)
7927 : values(other.values, allocator) {}
7928
7929template <template <typename> typename Allocator>
7931 : ArrayBase(other, std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator())) {}
7932
7933template <template <typename> typename Allocator>
7934inline ArrayBase<Allocator>::ArrayBase(ArrayBase&& other, const allocator_type& allocator) noexcept // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
7935 : values(std::move(other.values), allocator) {}
7936
7937template <template <typename> typename Allocator>
7939 : ArrayBase(std::move(other), other.get_allocator()) {}
7940
7941template <template <typename> typename Allocator>
7942inline ArrayBase<Allocator>& ArrayBase<Allocator>::operator=(const ArrayBase& other) = default;
7943
7944template <template <typename> typename Allocator>
7946 std::allocator_traits<
7947 allocator_type>::propagate_on_container_move_assignment::value || // NOLINT(cppcoreguidelines-noexcept-move-operations, performance-noexcept-move-constructor)
7948 std::allocator_traits<allocator_type>::is_always_equal::value) = default;
7949
7950template <template <typename> typename Allocator>
7951template <input_iterator InputIterator, sentinel_for<InputIterator> Sentinel>
7952inline ArrayBase<Allocator>::ArrayBase(InputIterator first, Sentinel last, const allocator_type& allocator)
7953 : values(first, last, allocator) {}
7954
7955template <template <typename> typename Allocator>
7957 : values(count, value, allocator) {}
7958
7959template <template <typename> typename Allocator>
7960inline ArrayBase<Allocator>::ArrayBase(std::initializer_list<value_type> ilist, const allocator_type& allocator)
7961 : values(ilist, allocator) {}
7962
7963template <template <typename> typename Allocator>
7964inline ArrayBase<Allocator>& ArrayBase<Allocator>::operator=(std::initializer_list<value_type> ilist) {
7965 values = ilist;
7966 return *this;
7967}
7968
7969template <template <typename> typename Allocator>
7970inline void ArrayBase<Allocator>::swap(ArrayBase& other) noexcept {
7971 values.swap(other.values);
7972}
7973
7974template <template <typename> typename Allocator>
7975inline void swap(ArrayBase<Allocator>& a, ArrayBase<Allocator>& b) noexcept {
7976 a.swap(b);
7977}
7978
7979template <template <typename> typename Allocator>
7981 return values.get_allocator();
7982}
7983
7984template <template <typename> typename Allocator>
7986 return values.data();
7987}
7988
7989template <template <typename> typename Allocator>
7991 return values.data();
7992}
7993
7994template <template <typename> typename Allocator>
7996 return values.size();
7997}
7998
7999template <template <typename> typename Allocator>
8001 return values.max_size();
8002}
8003
8004template <template <typename> typename Allocator>
8006 return values.capacity();
8007}
8008
8009template <template <typename> typename Allocator>
8010inline bool ArrayBase<Allocator>::empty() const noexcept {
8011 return values.empty();
8012}
8013
8014template <template <typename> typename Allocator>
8016 return values.begin();
8017}
8018
8019template <template <typename> typename Allocator>
8021 return values.begin();
8022}
8023
8024template <template <typename> typename Allocator>
8026 return values.cbegin();
8027}
8028
8029template <template <typename> typename Allocator>
8031 return values.end();
8032}
8033
8034template <template <typename> typename Allocator>
8036 return values.end();
8037}
8038
8039template <template <typename> typename Allocator>
8041 return values.cend();
8042}
8043
8044template <template <typename> typename Allocator>
8046 return values.rbegin();
8047}
8048
8049template <template <typename> typename Allocator>
8051 return values.rbegin();
8052}
8053
8054template <template <typename> typename Allocator>
8056 return values.crbegin();
8057}
8058
8059template <template <typename> typename Allocator>
8061 return values.rend();
8062}
8063
8064template <template <typename> typename Allocator>
8066 return values.rend();
8067}
8068
8069template <template <typename> typename Allocator>
8071 return values.crend();
8072}
8073
8074template <template <typename> typename Allocator>
8076 return values.front();
8077}
8078
8079template <template <typename> typename Allocator>
8081 return values.front();
8082}
8083
8084template <template <typename> typename Allocator>
8086 return values.back();
8087}
8088
8089template <template <typename> typename Allocator>
8091 return values.back();
8092}
8093
8094template <template <typename> typename Allocator>
8096 if (pos < values.size()) {
8097 return values[pos];
8098 }
8099 throw std::out_of_range{"JSON array does not contain item [" + toString(pos) + "]."};
8100}
8101
8102template <template <typename> typename Allocator>
8104 if (pos < values.size()) {
8105 return values[pos];
8106 }
8107 throw std::out_of_range{"JSON array does not contain item [" + toString(pos) + "]."};
8108}
8109
8110template <template <typename> typename Allocator>
8112 return values[pos];
8113}
8114
8115template <template <typename> typename Allocator>
8117 return values[pos];
8118}
8119
8120template <template <typename> typename Allocator>
8121inline bool ArrayBase<Allocator>::operator==(const ArrayBase& other) const {
8122 return values == other.values;
8123}
8124
8125template <template <typename> typename Allocator>
8126inline std::partial_ordering ArrayBase<Allocator>::operator<=>(const ArrayBase& other) const noexcept {
8127 return std::compare_partial_order_fallback(values, other.values);
8128}
8129
8130template <template <typename> typename Allocator, typename U>
8131inline typename ArrayBase<Allocator>::size_type erase(ArrayBase<Allocator>& container, const U& value) {
8132 return erase(container.values, value);
8133}
8134
8135template <template <typename> typename Allocator, typename Predicate>
8136inline typename ArrayBase<Allocator>::size_type erase_if(ArrayBase<Allocator>& container, Predicate predicate) {
8137 return erase_if(container.values, predicate);
8138}
8139
8140template <template <typename> typename Allocator>
8141inline void ArrayBase<Allocator>::clear() noexcept {
8142 values.clear();
8143}
8144
8145template <template <typename> typename Allocator>
8147 values.reserve(newCapacity);
8148}
8149
8150template <template <typename> typename Allocator>
8152 values.shrink_to_fit();
8153}
8154
8155template <template <typename> typename Allocator>
8157 values.assign(count, value);
8158}
8159
8160template <template <typename> typename Allocator>
8161template <input_iterator InputIterator, sentinel_for<InputIterator> Sentinel>
8162inline void ArrayBase<Allocator>::assign(InputIterator first, Sentinel last) {
8163 values.assign(first, last);
8164}
8165
8166template <template <typename> typename Allocator>
8167inline void ArrayBase<Allocator>::assign(std::initializer_list<value_type> ilist) {
8168 values.assign(ilist);
8169}
8170
8171template <template <typename> typename Allocator>
8172template <typename R>
8174 values.assign_range(std::forward<R>(r));
8175}
8176
8177template <template <typename> typename Allocator>
8179 return values.insert(pos, value);
8180}
8181
8182template <template <typename> typename Allocator>
8184 return values.insert(pos, std::move(value));
8185}
8186
8187template <template <typename> typename Allocator>
8189 return values.insert(pos, count, value);
8190}
8191
8192template <template <typename> typename Allocator>
8193template <input_iterator InputIterator, sentinel_for<InputIterator> Sentinel>
8194inline typename ArrayBase<Allocator>::iterator ArrayBase<Allocator>::insert(const_iterator pos, InputIterator first, Sentinel last) {
8195 return values.insert(pos, first, last);
8196}
8197
8198template <template <typename> typename Allocator>
8199inline typename ArrayBase<Allocator>::iterator ArrayBase<Allocator>::insert(const_iterator pos, std::initializer_list<value_type> ilist) {
8200 return values.insert(pos, ilist);
8201}
8202
8203template <template <typename> typename Allocator>
8204template <typename R>
8206 return values.insert_range(pos, std::forward<R>(r));
8207}
8208
8209template <template <typename> typename Allocator>
8210template <typename R>
8212 values.append_range(std::forward<R>(r));
8213}
8214
8215template <template <typename> typename Allocator>
8216template <typename... Args>
8218 return values.emplace(pos, std::forward<Args>(args)...);
8219}
8220
8221template <template <typename> typename Allocator>
8223 return values.erase(pos);
8224}
8225
8226template <template <typename> typename Allocator>
8228 return values.erase(first, last);
8229}
8230
8231template <template <typename> typename Allocator>
8233 values.push_back(value);
8234}
8235
8236template <template <typename> typename Allocator>
8238 values.push_back(std::move(value));
8239}
8240
8241template <template <typename> typename Allocator>
8242template <typename... Args>
8244 return values.emplace_back(std::forward<Args>(args)...);
8245}
8246
8247template <template <typename> typename Allocator>
8249 values.pop_back();
8250}
8251
8252template <template <typename> typename Allocator>
8254 values.resize(count);
8255}
8256
8257template <template <typename> typename Allocator>
8259 values.resize(count, value);
8260}
8261
8262template <template <typename> typename Allocator>
8264 return ValueBase<Allocator>::parse(jsonString, source, allocator);
8265}
8266
8267template <template <typename> typename Allocator>
8269 static_assert(sizeof(char) == sizeof(char8_t));
8270 static_assert(alignof(char) == alignof(char8_t));
8271 return parse(UTF8StringView{std::launder(reinterpret_cast<const char8_t*>(jsonString.data())), jsonString.size()}, source, allocator);
8272}
8273
8274template <template <typename> typename Allocator>
8276 return json::serializeToString(*this, options, {}, Allocator<char>{stringAllocator});
8277}
8278
8279template <template <typename> typename Allocator>
8281 unicode::UTF8View codePoints{jsonString};
8282 return Parser<const char8_t*, Allocator>{Lexer<const char8_t*, Allocator>{codePoints.begin(), codePoints.end(), source, allocator}, allocator}.parseFile();
8283}
8284
8285template <template <typename> typename Allocator>
8287 static_assert(sizeof(char) == sizeof(char8_t));
8288 static_assert(alignof(char) == alignof(char8_t));
8289 return parse(UTF8StringView{std::launder(reinterpret_cast<const char8_t*>(jsonString.data())), jsonString.size()}, source, allocator);
8290}
8291
8292} // namespace grem::json
8293
8294namespace grem::pmr {
8295
8307
8308} // namespace grem::pmr
8309
8310#endif
#define GREM_ASSERT(expression)
Definition assertions.hpp:77
#define GREM_ALWAYS_INLINE
Definition attributes.hpp:10
Definition ArrayList.hpp:27
typename std::allocator_traits< Allocator >::size_type size_type
Definition ArrayList.hpp:34
typename std::allocator_traits< Allocator >::const_pointer const_pointer
Definition ArrayList.hpp:39
std::reverse_iterator< const_iterator > const_reverse_iterator
Definition ArrayList.hpp:43
const value_type & const_reference
Definition ArrayList.hpp:37
typename std::allocator_traits< Allocator >::pointer pointer
Definition ArrayList.hpp:38
value_type & reference
Definition ArrayList.hpp:36
typename std::allocator_traits< Allocator >::difference_type difference_type
Definition ArrayList.hpp:35
pointer iterator
Definition ArrayList.hpp:40
const_pointer const_iterator
Definition ArrayList.hpp:41
std::reverse_iterator< iterator > reverse_iterator
Definition ArrayList.hpp:42
Base exception type for runtime errors.
Definition Error.hpp:38
Optional value type that holds either a value or no value.
Definition Optional.hpp:58
Definition Subrange.hpp:88
Tagged union value type that holds a value of one of the given types.
Definition Variant.hpp:293
constexpr T & emplace(Args &&... args)
Construct an alternative given its type, destroying the old value.
Definition Variant.hpp:591
constexpr index_type index() const noexcept
Get the alternative index of the currently active value held by the variant.
Definition Variant.hpp:716
constexpr bool is() const noexcept
Check if the variant currently holds the alternative with the given type.
Definition Variant.hpp:740
constexpr T & as() &noexcept
Access the underlying value with the given type without a safety check.
Definition Variant.hpp:784
constexpr bool valueless_by_exception() const noexcept
Check if the variant is in the valueless by exception state.
Definition Variant.hpp:726
JSON array type whose API mimics that of std::vector<Value>.
Definition json.hpp:397
allocator_type get_allocator() const noexcept
iterator insert_range(const_iterator pos, R &&r)
typename ArrayList< value_type >::const_iterator const_iterator
Definition json.hpp:408
typename ArrayList< value_type >::pointer pointer
Definition json.hpp:405
size_type size() const noexcept
ArrayBase & operator=(const ArrayBase &other)
Allocator< value_type > allocator_type
Definition json.hpp:402
friend size_type erase_if(ArrayBase &container, Predicate predicate)
Definition json.hpp:8136
typename ArrayList< value_type >::const_pointer const_pointer
Definition json.hpp:406
reverse_iterator rbegin() noexcept
size_type max_size() const noexcept
typename ArrayList< value_type >::difference_type difference_type
Definition json.hpp:401
const_iterator cend() const noexcept
typename ArrayList< value_type >::const_reference const_reference
Definition json.hpp:404
typename ArrayList< value_type >::const_reverse_iterator const_reverse_iterator
Definition json.hpp:410
const_reverse_iterator crbegin() const noexcept
ArrayBase() noexcept
Definition json.hpp:7915
bool operator==(const ArrayBase &other) const
Definition json.hpp:8121
ValueBase< Allocator > value_type
Definition json.hpp:399
size_type capacity() const noexcept
void swap(ArrayBase &other) noexcept
typename ArrayList< value_type >::reverse_iterator reverse_iterator
Definition json.hpp:409
reference operator[](size_type pos)
Definition json.hpp:8111
reference emplace_back(Args &&... args)
iterator emplace(const_iterator pos, Args &&... args)
typename ArrayList< value_type >::iterator iterator
Definition json.hpp:407
reverse_iterator rend() noexcept
std::partial_ordering operator<=>(const ArrayBase &other) const noexcept
Definition json.hpp:8126
const_reverse_iterator crend() const noexcept
void reserve(size_type newCapacity)
typename ArrayList< value_type >::size_type size_type
Definition json.hpp:400
friend size_type erase(ArrayBase &container, const U &value)
Definition json.hpp:8131
void push_back(const value_type &value)
const_iterator cbegin() const noexcept
typename ArrayList< value_type >::reference reference
Definition json.hpp:403
iterator insert(const_iterator pos, const value_type &value)
void assign(size_type count, const value_type &value)
Lexical analyzer for scanning and tokenizing input in the JSON5 format.
Definition json.hpp:2876
Token scan()
Scan and consume the next token from the input.
Definition json.hpp:2980
Lexer & operator=(Lexer &&other) noexcept
Move assignment.
Definition json.hpp:2944
Lexer & operator=(const Lexer &other)
Copy assignment.
Definition json.hpp:2929
Lexer(Lexer &&other, const allocator_type &allocator) noexcept
Move constructor.
Definition json.hpp:2910
Allocator< VariantBase< Allocator > > allocator_type
Allocator type used by the lexer.
Definition json.hpp:2879
TokenBase< Allocator > Token
Token type of the lexer.
Definition json.hpp:2882
Lexer(const Lexer &other)
Copy constructor.
Definition json.hpp:2921
allocator_type get_allocator() const noexcept
Get the allocator used by the lexer.
Definition json.hpp:2963
Lexer(const Lexer &other, const allocator_type &allocator)
Copy constructor.
Definition json.hpp:2902
Lexer(Lexer &&other) noexcept
Move constructor.
Definition json.hpp:2925
Lexer(unicode::UTF8Iterator< It > it, unicode::UTF8Sentinel end, const SourceLocation &source, const allocator_type &allocator=allocator_type())
Construct a lexer with a Unicode iterator pair as input.
Definition json.hpp:2895
~Lexer()=default
Destructor.
JSON object type whose API mimics that of std::map<String, Value>.
Definition json.hpp:258
std::partial_ordering operator<=>(const ObjectBase &other) const noexcept
Definition json.hpp:7885
iterator erase(const_iterator pos)
typename ArrayList< value_type >::reverse_iterator reverse_iterator
Definition json.hpp:272
const_reverse_iterator crbegin() const noexcept
void reserve(size_type newCapacity)
reverse_iterator rend() noexcept
Pair< iterator, bool > insert(P &&value)
typename ArrayList< value_type >::const_reference const_reference
Definition json.hpp:267
ObjectBase() noexcept
Definition json.hpp:7527
Pair< iterator, bool > emplace(Args &&... args)
reverse_iterator rbegin() noexcept
mapped_type & operator[](const key_type &k)
Definition json.hpp:7606
const_iterator cbegin() const noexcept
bool operator==(const ObjectBase &other) const noexcept
Definition json.hpp:7880
typename ArrayList< value_type >::const_pointer const_pointer
Definition json.hpp:269
Pair< iterator, bool > try_emplace(const key_type &k, Args &&... args)
size_type size() const noexcept
ObjectBase & operator=(const ObjectBase &other)
Pair< StringBase< Allocator >, ValueBase< Allocator > > value_type
Definition json.hpp:262
typename ArrayList< value_type >::const_reverse_iterator const_reverse_iterator
Definition json.hpp:273
typename ArrayList< value_type >::iterator iterator
Definition json.hpp:270
const_iterator cend() const noexcept
typename ArrayList< value_type >::const_iterator const_iterator
Definition json.hpp:271
void swap(ObjectBase &other) noexcept
bool contains(StringView key) const noexcept
size_type capacity() const noexcept
iterator find(StringView key) noexcept
friend size_type erase_if(ObjectBase &container, Predicate predicate)
Definition json.hpp:7890
size_type max_size() const noexcept
typename ArrayList< value_type >::reference reference
Definition json.hpp:266
allocator_type get_allocator() const noexcept
iterator lower_bound(StringView key) noexcept
typename ArrayList< value_type >::size_type size_type
Definition json.hpp:263
ValueBase< Allocator > mapped_type
Definition json.hpp:261
size_type count(StringView key) const noexcept
iterator upper_bound(StringView key) noexcept
StringBase< Allocator > key_type
Definition json.hpp:260
Pair< iterator, iterator > equal_range(StringView key) noexcept
Allocator< value_type > allocator_type
Definition json.hpp:265
const_reverse_iterator crend() const noexcept
typename ArrayList< value_type >::difference_type difference_type
Definition json.hpp:264
mapped_type & at(StringView key)
iterator emplace_hint(const_iterator hint, Args &&... args)
Polymorphic interface for visitation-based parsing of JSON object properties.
Definition json.hpp:3551
virtual void visitProperty(const SourceLocation &source, StringBase< Allocator > &&key, Parser &parser)=0
Callback for each object property.
Polymorphic interface for visitation-based parsing of JSON values.
Definition json.hpp:3385
virtual void visitArray(const SourceLocation &source, Parser &parser)
Callback for arrays.
Definition json.hpp:3476
virtual void visitBoolean(const SourceLocation &source, Boolean value)
Callback for values of type Boolean.
Definition json.hpp:3410
virtual void visitNumber(const SourceLocation &source, Number value)
Callback for values of type Number.
Definition json.hpp:3438
virtual void visitObject(const SourceLocation &source, Parser &parser)
Callback for objects.
Definition json.hpp:3457
virtual void visitString(const SourceLocation &source, StringBase< Allocator > &&value)
Callback for values of type String.
Definition json.hpp:3424
virtual void visitNull(const SourceLocation &source, Null value)
Callback for values of type Null.
Definition json.hpp:3396
Syntactic analyzer for parsing input in the JSON5 format obtained from a json::Lexer.
Definition json.hpp:3374
Boolean parseBoolean()
Definition json.hpp:4165
bool peekIsNull() const
Definition json.hpp:4147
ValueBase< Allocator > parseValue()
Definition json.hpp:4088
const Token & peek() const
Definition json.hpp:4445
Parser & operator=(const Parser &)=default
void parseArray(ValueVisitor &visitor)
Read a single JSON array from the input and visit each of its values.
Definition json.hpp:3928
bool peekIsString() const
Definition json.hpp:4234
allocator_type get_allocator() const noexcept
Definition json.hpp:3736
Parser(const Parser &other)
Definition json.hpp:3718
bool peekIsBoolean() const
Definition json.hpp:4189
void parseObject(Visitor visitor)
Definition json.hpp:3998
Parser(Parser &&other, const allocator_type &allocator) noexcept
Definition json.hpp:3703
void parseObject(PropertyVisitor &&visitor)
Definition json.hpp:3967
bool peekIsObject() const
Definition json.hpp:4347
void parseFile(ValueVisitor &visitor)
Definition json.hpp:3762
Allocator< ValueBase< Allocator > > allocator_type
Allocator type used by the parser.
Definition json.hpp:3377
void parseValue(Visitor visitor)
Definition json.hpp:3990
Parser(unicode::UTF8View codePoints, const SourceLocation &source={}, const allocator_type &allocator=allocator_type())
Definition json.hpp:3638
StringBase< Allocator > parseString()
Definition json.hpp:4212
void parseArray(ValueVisitor &&visitor)
Definition json.hpp:3974
Parser(StringView jsonString, const SourceLocation &source={}, const allocator_type &allocator=allocator_type())
Definition json.hpp:3663
Number parseNumber()
Definition json.hpp:4252
void parseFile(Visitor visitor)
Definition json.hpp:3982
bool peekIsNumber() const
Definition json.hpp:4281
Parser & operator=(Parser &&) noexcept=default
void parseArray(Visitor visitor)
Definition json.hpp:4006
void parseFile(ValueVisitor &&visitor)
Definition json.hpp:3953
bool peekIsArray() const
Definition json.hpp:4407
Parser(std::istream &stream, const SourceLocation &source={}, const allocator_type &allocator=allocator_type())
Definition json.hpp:3674
ArrayBase< Allocator > parseArray()
Definition json.hpp:4366
void parseObject(PropertyVisitor &visitor)
Read a single JSON object from the input and visit each of its properties.
Definition json.hpp:3860
Parser(std::streambuf *streambuf, const SourceLocation &source={}, const allocator_type &allocator=allocator_type())
Definition json.hpp:3686
Null parseNull()
Definition json.hpp:4125
TokenBase< Allocator > Token
Token type of the parser.
Definition json.hpp:3380
Parser(UTF8StringView jsonString, const SourceLocation &source={}, const allocator_type &allocator=allocator_type())
Definition json.hpp:3650
void parseValue(ValueVisitor &visitor)
Read a single JSON value from the input and visit it.
Definition json.hpp:3790
ValueBase< Allocator > parseFile()
Definition json.hpp:4059
Parser(Lexer< It, Allocator > lexer, const allocator_type &allocator=allocator_type())
Construct a parser with an existing lexer as input.
Definition json.hpp:3626
void skipFile()
Definition json.hpp:4023
Parser(Parser &&other) noexcept
Definition json.hpp:3722
void parseValue(ValueVisitor &&visitor)
Definition json.hpp:3960
ObjectBase< Allocator > parseObject()
Definition json.hpp:4311
Parser(const Parser &other, const allocator_type &allocator)
Definition json.hpp:3691
JSON value with an associated SourceLocation.
Definition json.hpp:1102
GREM_ALWAYS_INLINE Number && getNumberItem(size_t index) &&
Get an item of the Array in this value as a Number, throwing an exception if this value is not actual...
Definition json.hpp:2457
GREM_ALWAYS_INLINE const Array & getArrayItem(size_t index) const &&
Get an item of the Array in this value as an Array, throwing an exception if this value is not actual...
Definition json.hpp:2761
GREM_ALWAYS_INLINE Boolean && getBooleanItem(size_t index) &&
Get an item of the Array in this value as a Boolean, throwing an exception if this value is not actua...
Definition json.hpp:2169
GREM_ALWAYS_INLINE Boolean && getBoolean() &&
Get this value as a Boolean, throwing an exception if it is not actually a boolean.
Definition json.hpp:1328
GREM_ALWAYS_INLINE T getNumberProperty(StringView key) const
Get a property of the Object in this value as a Number, throwing an exception if this value is not ac...
Definition json.hpp:2409
GREM_ALWAYS_INLINE const ObjectBase< Allocator > & getObject() const &
Get this value as an Object, throwing an exception if it is not actually an object.
Definition json.hpp:1545
ValueBase(ValueBase &&other) noexcept=default
Move constructor.
GREM_ALWAYS_INLINE const ObjectBase< Allocator > && getObject() const &&
Get this value as an Object, throwing an exception if it is not actually an object.
Definition json.hpp:1575
GREM_ALWAYS_INLINE String && getStringItem(size_t index) &&
Get an item of the Array in this value as a String, throwing an exception if this value is not actual...
Definition json.hpp:2302
GREM_ALWAYS_INLINE T getNumberItem(size_t index) const
Get an item of the Array in this value as a Number, throwing an exception if this value is not actual...
Definition json.hpp:2495
GREM_ALWAYS_INLINE Array & getArrayItem(size_t index) &
Get an item of the Array in this value as an Array, throwing an exception if this value is not actual...
Definition json.hpp:2713
GREM_ALWAYS_INLINE const Null & getNullProperty(StringView key) const &
Get a property of the Object in this value as Null, throwing an exception if this value is not actual...
Definition json.hpp:1955
GREM_ALWAYS_INLINE const String & getStringItem(size_t index) const &
Get an item of the Array in this value as a String, throwing an exception if this value is not actual...
Definition json.hpp:2286
GREM_ALWAYS_INLINE const Object & getObjectItem(size_t index) const &&
Get an item of the Array in this value as an Object, throwing an exception if this value is not actua...
Definition json.hpp:2628
GREM_ALWAYS_INLINE const Null & getNullItem(size_t index) const &
Get an item of the Array in this value as Null, throwing an exception if this value is not actually a...
Definition json.hpp:2020
GREM_ALWAYS_INLINE const Array & getArrayProperty(StringView key) const &&
Get a property of the Object in this value as an Array, throwing an exception if this value is not ac...
Definition json.hpp:2697
GREM_ALWAYS_INLINE Object & getObjectProperty(StringView key) &
Get a property of the Object in this value as an Object, throwing an exception if this value is not a...
Definition json.hpp:2512
GREM_ALWAYS_INLINE const StringBase< Allocator > && getString() const &&
Get this value as a String, throwing an exception if it is not actually a string.
Definition json.hpp:1412
GREM_ALWAYS_INLINE Number && getNumberProperty(StringView key) &&
Get a property of the Object in this value as a Number, throwing an exception if this value is not ac...
Definition json.hpp:2369
GREM_ALWAYS_INLINE const StringBase< Allocator > & getString() const &
Get this value as a String, throwing an exception if it is not actually a string.
Definition json.hpp:1367
GREM_ALWAYS_INLINE const String & getStringItem(size_t index) const &&
Get an item of the Array in this value as a String, throwing an exception if this value is not actual...
Definition json.hpp:2318
ValueBase(VariantBase< Allocator > value, const SourceLocation &source, const allocator_type &allocator)
Construct a JSON value with an associated source location.
Definition json.hpp:1184
GREM_ALWAYS_INLINE Boolean && getBooleanProperty(StringView key) &&
Get a property of the Object in this value as a Boolean, throwing an exception if this value is not a...
Definition json.hpp:2103
GREM_ALWAYS_INLINE const ValueBase< Allocator > & getProperty(StringView key) const &
Get a property of the Object in this value, throwing an exception if it is not actually an object or ...
Definition json.hpp:1750
GREM_ALWAYS_INLINE const Boolean & getBoolean() const &
Get this value as a Boolean, throwing an exception if it is not actually a boolean.
Definition json.hpp:1313
ValueBase(const ValueBase &other, const allocator_type &allocator) noexcept
Copy constructor.
Definition json.hpp:1192
GREM_ALWAYS_INLINE bool isString() const noexcept
Check if this value is of type String.
Definition json.hpp:1355
GREM_ALWAYS_INLINE const Boolean && getBoolean() const &&
Get this value as a Boolean, throwing an exception if it is not actually a boolean.
Definition json.hpp:1343
GREM_ALWAYS_INLINE const Number & getNumberItem(size_t index) const &
Get an item of the Array in this value as a Number, throwing an exception if this value is not actual...
Definition json.hpp:2441
GREM_ALWAYS_INLINE Null && getNull() &&
Get this value as Null, throwing an exception if it is not actually null.
Definition json.hpp:1260
GREM_ALWAYS_INLINE const Number && getNumber() const &&
Get this value as a Number, throwing an exception if it is not actually a number.
Definition json.hpp:1481
GREM_ALWAYS_INLINE const ValueBase< Allocator > & getItem(size_t index) const &
Get an item of the Array in this value, throwing an exception if it is not actually an array or if th...
Definition json.hpp:1881
GREM_ALWAYS_INLINE String & getStringProperty(StringView key) &
Get a property of the Object in this value as a String, throwing an exception if this value is not ac...
Definition json.hpp:2202
GREM_ALWAYS_INLINE ObjectBase< Allocator > & getObject() &
Get this value as an Object, throwing an exception if it is not actually an object.
Definition json.hpp:1530
GREM_ALWAYS_INLINE const Boolean & getBooleanItem(size_t index) const &
Get an item of the Array in this value as a Boolean, throwing an exception if this value is not actua...
Definition json.hpp:2153
GREM_ALWAYS_INLINE bool isNull() const noexcept
Check if this value is of type Null.
Definition json.hpp:1221
ValueBase(const ValueBase &other)=default
Copy constructor.
GREM_ALWAYS_INLINE Boolean & getBoolean() &
Get this value as a Boolean, throwing an exception if it is not actually a boolean.
Definition json.hpp:1298
GREM_ALWAYS_INLINE ValueBase< Allocator > && getItem(size_t index) &&
Get an item of the Array in this value, throwing an exception if it is not actually an array or if th...
Definition json.hpp:1900
GREM_ALWAYS_INLINE Array & getArrayProperty(StringView key) &
Get a property of the Object in this value as an Array, throwing an exception if this value is not ac...
Definition json.hpp:2645
GREM_ALWAYS_INLINE Null && getNullItem(size_t index) &&
Get an item of the Array in this value as Null, throwing an exception if this value is not actually a...
Definition json.hpp:2036
GREM_ALWAYS_INLINE Array && getArrayProperty(StringView key) &&
Get a property of the Object in this value as an Array, throwing an exception if this value is not ac...
Definition json.hpp:2679
GREM_ALWAYS_INLINE const ArrayBase< Allocator > & getArray() const &
Get this value as an Array, throwing an exception if it is not actually an array.
Definition json.hpp:1629
GREM_ALWAYS_INLINE const Object & getObjectProperty(StringView key) const &
Get a property of the Object in this value as an Object, throwing an exception if this value is not a...
Definition json.hpp:2529
ValueBase(VariantBase< Allocator > value)
Construct a JSON value.
Definition json.hpp:1164
GREM_ALWAYS_INLINE ObjectBase< Allocator > && getObject() &&
Get this value as an Object, throwing an exception if it is not actually an object.
Definition json.hpp:1560
GREM_ALWAYS_INLINE const Number & getNumberItem(size_t index) const &&
Get an item of the Array in this value as a Number, throwing an exception if this value is not actual...
Definition json.hpp:2473
GREM_ALWAYS_INLINE bool isObject() const noexcept
Check if this value is of type Object.
Definition json.hpp:1518
GREM_ALWAYS_INLINE Boolean & getBooleanProperty(StringView key) &
Get a property of the Object in this value as a Boolean, throwing an exception if this value is not a...
Definition json.hpp:2069
GREM_ALWAYS_INLINE const ValueBase< Allocator > * findItem(size_t index) const noexcept
Get an item of the Array in this value, returning nullptr if it is not actually an array or if the in...
Definition json.hpp:1841
GREM_ALWAYS_INLINE ValueBase< Allocator > * findItem(size_t index) noexcept
Get an item of the Array in this value, returning nullptr if it is not actually an array or if the in...
Definition json.hpp:1821
GREM_ALWAYS_INLINE const ArrayBase< Allocator > && getArray() const &&
Get this value as an Array, throwing an exception if it is not actually an array.
Definition json.hpp:1659
GREM_ALWAYS_INLINE String & getStringItem(size_t index) &
Get an item of the Array in this value as a String, throwing an exception if this value is not actual...
Definition json.hpp:2270
ValueBase & operator=(const ValueBase &other)=default
Copy assignment.
GREM_ALWAYS_INLINE SourceLocation getSource() const noexcept
Get the source location of this value.
Definition json.hpp:2770
GREM_ALWAYS_INLINE const String & getStringProperty(StringView key) const &&
Get a property of the Object in this value as a String, throwing an exception if this value is not ac...
Definition json.hpp:2254
GREM_ALWAYS_INLINE ArrayBase< Allocator > && getArray() &&
Get this value as an Array, throwing an exception if it is not actually an array.
Definition json.hpp:1644
~ValueBase()=default
Destructor.
GREM_ALWAYS_INLINE ValueBase< Allocator > & getProperty(StringView key) &
Get a property of the Object in this value, throwing an exception if it is not actually an object or ...
Definition json.hpp:1730
GREM_ALWAYS_INLINE StringBase< Allocator > && getString() &&
Get this value as a String, throwing an exception if it is not actually a string.
Definition json.hpp:1397
GREM_ALWAYS_INLINE const Object & getObjectItem(size_t index) const &
Get an item of the Array in this value as an Object, throwing an exception if this value is not actua...
Definition json.hpp:2596
GREM_ALWAYS_INLINE const Number & getNumber() const &
Get this value as a Number, throwing an exception if it is not actually a number.
Definition json.hpp:1451
GREM_ALWAYS_INLINE Number & getNumberItem(size_t index) &
Get an item of the Array in this value as a Number, throwing an exception if this value is not actual...
Definition json.hpp:2425
GREM_ALWAYS_INLINE ArrayBase< Allocator > & getArray() &
Get this value as an Array, throwing an exception if it is not actually an array.
Definition json.hpp:1614
GREM_ALWAYS_INLINE const Null & getNullItem(size_t index) const &&
Get an item of the Array in this value as Null, throwing an exception if this value is not actually a...
Definition json.hpp:2052
GREM_ALWAYS_INLINE bool isNumber() const noexcept
Check if this value is of type Number.
Definition json.hpp:1424
GREM_ALWAYS_INLINE Object && getObjectItem(size_t index) &&
Get an item of the Array in this value as an Object, throwing an exception if this value is not actua...
Definition json.hpp:2612
GREM_ALWAYS_INLINE const Number & getNumberProperty(StringView key) const &
Get a property of the Object in this value as a Number, throwing an exception if this value is not ac...
Definition json.hpp:2352
ValueBase & operator=(ValueBase &&other) noexcept(std::allocator_traits< allocator_type >::propagate_on_container_move_assignment::value||//NOLINT(cppcoreguidelines-noexcept-move-operations, performance-noexcept-move-constructor) std::allocator_traits< allocator_type >::is_always_equal::value)=default
Move assignment.
GREM_ALWAYS_INLINE const Boolean & getBooleanItem(size_t index) const &&
Get an item of the Array in this value as a Boolean, throwing an exception if this value is not actua...
Definition json.hpp:2185
GREM_ALWAYS_INLINE T getNumber() const
Get this value as a Number, throwing an exception if it is not actually a number, or not the correct ...
Definition json.hpp:1500
GREM_ALWAYS_INLINE bool hasProperty(StringView key) const noexcept
Check if this value is of type Object and has a property with a given key.
Definition json.hpp:1675
GREM_ALWAYS_INLINE Boolean & getBooleanItem(size_t index) &
Get an item of the Array in this value as a Boolean, throwing an exception if this value is not actua...
Definition json.hpp:2137
GREM_ALWAYS_INLINE Array && getArrayItem(size_t index) &&
Get an item of the Array in this value as an Array, throwing an exception if this value is not actual...
Definition json.hpp:2745
ValueBase(VariantBase< Allocator > value, const allocator_type &allocator)
Construct a JSON value.
Definition json.hpp:1156
GREM_ALWAYS_INLINE const Null & getNull() const &&
Get this value as Null, throwing an exception if it is not actually null.
Definition json.hpp:1274
GREM_ALWAYS_INLINE const Array & getArrayProperty(StringView key) const &
Get a property of the Object in this value as an Array, throwing an exception if this value is not ac...
Definition json.hpp:2662
GREM_ALWAYS_INLINE ValueBase< Allocator > & getItem(size_t index) &
Get an item of the Array in this value, throwing an exception if it is not actually an array or if th...
Definition json.hpp:1862
GREM_ALWAYS_INLINE Object && getObjectProperty(StringView key) &&
Get a property of the Object in this value as an Object, throwing an exception if this value is not a...
Definition json.hpp:2546
GREM_ALWAYS_INLINE Null && getNullProperty(StringView key) &&
Get a property of the Object in this value as Null, throwing an exception if this value is not actual...
Definition json.hpp:1971
GREM_ALWAYS_INLINE String && getStringProperty(StringView key) &&
Get a property of the Object in this value as a String, throwing an exception if this value is not ac...
Definition json.hpp:2236
GREM_ALWAYS_INLINE Null & getNullProperty(StringView key) &
Get a property of the Object in this value as Null, throwing an exception if this value is not actual...
Definition json.hpp:1939
GREM_ALWAYS_INLINE Number && getNumber() &&
Get this value as a Number, throwing an exception if it is not actually a number.
Definition json.hpp:1466
GREM_ALWAYS_INLINE bool isArray() const noexcept
Check if this value is of type Array.
Definition json.hpp:1587
static ValueBase parse(UTF8StringView jsonString, const SourceLocation &source={}, const allocator_type &allocator=allocator_type())
Parse a value of any JSON type from a UTF-8 JSON string.
Definition json.hpp:8280
GREM_ALWAYS_INLINE const Boolean & getBooleanProperty(StringView key) const &
Get a property of the Object in this value as a Boolean, throwing an exception if this value is not a...
Definition json.hpp:2086
GREM_ALWAYS_INLINE const Null & getNullProperty(StringView key) const &&
Get a property of the Object in this value as Null, throwing an exception if this value is not actual...
Definition json.hpp:1988
GREM_ALWAYS_INLINE Null & getNull() &
Get this value as Null, throwing an exception if it is not actually null.
Definition json.hpp:1232
GREM_ALWAYS_INLINE const String & getStringProperty(StringView key) const &
Get a property of the Object in this value as a String, throwing an exception if this value is not ac...
Definition json.hpp:2219
GREM_ALWAYS_INLINE ValueBase< Allocator > * findProperty(StringView key) noexcept
Get a property of the Object in this value, returning nullptr if it is not actually an object or if t...
Definition json.hpp:1689
GREM_ALWAYS_INLINE Object & getObjectItem(size_t index) &
Get an item of the Array in this value as an Object, throwing an exception if this value is not actua...
Definition json.hpp:2580
GREM_ALWAYS_INLINE ValueBase< Allocator > && getProperty(StringView key) &&
Get a property of the Object in this value, throwing an exception if it is not actually an object or ...
Definition json.hpp:1770
GREM_ALWAYS_INLINE Number & getNumberProperty(StringView key) &
Get a property of the Object in this value as a Number, throwing an exception if this value is not ac...
Definition json.hpp:2335
GREM_ALWAYS_INLINE const Number & getNumberProperty(StringView key) const &&
Get a property of the Object in this value as a Number, throwing an exception if this value is not ac...
Definition json.hpp:2387
GREM_ALWAYS_INLINE bool hasItem(size_t index) const noexcept
Check if this value is of type Array and has an item at the given index.
Definition json.hpp:1807
GREM_ALWAYS_INLINE StringBase< Allocator > & getString() &
Get this value as a String, throwing an exception if it is not actually a string.
Definition json.hpp:1382
ValueBase(ValueBase &&other, const allocator_type &allocator) noexcept
Move constructor.
Definition json.hpp:1200
GREM_ALWAYS_INLINE const ValueBase< Allocator > && getProperty(StringView key) const &&
Get a property of the Object in this value, throwing an exception if it is not actually an object or ...
Definition json.hpp:1790
GREM_ALWAYS_INLINE const Array & getArrayItem(size_t index) const &
Get an item of the Array in this value as an Array, throwing an exception if this value is not actual...
Definition json.hpp:2729
ValueBase(VariantBase< Allocator > value, const SourceLocation &source)
Construct a JSON value with an associated source location.
Definition json.hpp:1173
GREM_ALWAYS_INLINE bool isBoolean() const noexcept
Check if this value is of type Boolean.
Definition json.hpp:1286
GREM_ALWAYS_INLINE size_t getArraySize() const
Get the size of the Array in this value, throwing an exception if it is not actually an array.
Definition json.hpp:1599
GREM_ALWAYS_INLINE Number & getNumber() &
Get this value as a Number, throwing an exception if it is not actually a number.
Definition json.hpp:1436
GREM_ALWAYS_INLINE bool operator==(const ValueBase &other) const
Compare this value to another for equality.
Definition json.hpp:2782
GREM_ALWAYS_INLINE const ValueBase< Allocator > && getItem(size_t index) const &&
Get an item of the Array in this value, throwing an exception if it is not actually an array or if th...
Definition json.hpp:1919
GREM_ALWAYS_INLINE const Null & getNull() const &
Get this value as Null, throwing an exception if it is not actually null.
Definition json.hpp:1246
GREM_ALWAYS_INLINE Null & getNullItem(size_t index) &
Get an item of the Array in this value as Null, throwing an exception if this value is not actually a...
Definition json.hpp:2004
GREM_ALWAYS_INLINE const Object & getObjectProperty(StringView key) const &&
Get a property of the Object in this value as an Object, throwing an exception if this value is not a...
Definition json.hpp:2564
static ValueBase parse(StringView jsonString, const SourceLocation &source={}, const allocator_type &allocator=allocator_type())
Parse a value of any JSON type from a JSON string interpreted as UTF-8.
Definition json.hpp:8286
GREM_ALWAYS_INLINE const ValueBase< Allocator > * findProperty(StringView key) const noexcept
Get a property of the Object in this value, returning nullptr if it is not actually an object or if t...
Definition json.hpp:1709
GREM_ALWAYS_INLINE const Boolean & getBooleanProperty(StringView key) const &&
Get a property of the Object in this value as a Boolean, throwing an exception if this value is not a...
Definition json.hpp:2121
JSON value type.
Definition json.hpp:538
VariantBase(std::nullptr_t, const allocator_type &allocator) noexcept
Construct a Null value.
Definition json.hpp:621
VariantBase(StringBase< Allocator > &&value, const allocator_type &allocator) noexcept
Construct a String value from the given underlying value.
Definition json.hpp:677
VariantBase & operator=(VariantBase &&other) noexcept(std::allocator_traits< allocator_type >::propagate_on_container_move_assignment::value||//NOLINT(cppcoreguidelines-noexcept-move-operations, performance-noexcept-move-constructor) std::allocator_traits< allocator_type >::is_always_equal::value)
Move assignment.
Definition json.hpp:1005
VariantBase(const VariantBase &other)
Copy constructor.
Definition json.hpp:960
VariantBase(const ArrayBase< Allocator > &value)
Construct an Array value with the given underlying value.
Definition json.hpp:920
VariantBase(const ObjectBase< Allocator > &value, const allocator_type &allocator)
Construct an Object value with the given underlying value.
Definition json.hpp:867
VariantBase(ArrayBase< Allocator > &&value) noexcept
Construct an Array value from the given underlying value.
Definition json.hpp:939
VariantBase(ObjectBase< Allocator > &&value, const allocator_type &allocator) noexcept
Construct an Object value from the given underlying value.
Definition json.hpp:888
GREM_ALWAYS_INLINE bool operator==(const VariantBase &other) const
Compare this value to another for equality.
Definition json.hpp:1072
VariantBase(ArrayBase< Allocator > &&value, const allocator_type &allocator) noexcept
Construct an Array value from the given underlying value.
Definition json.hpp:930
StringBase< Allocator > toString(const SerializationOptions &options={}, const allocator_type &stringAllocator=allocator_type()) const
Get a JSON string representation of the value.
Definition json.hpp:8275
VariantBase(StringBase< Allocator > &&value) noexcept
Construct a String value from the given underlying value.
Definition json.hpp:686
VariantBase(Null, const allocator_type &allocator) noexcept
Construct a Null value.
Definition json.hpp:607
VariantBase(Boolean value) noexcept
Construct a Boolean value with the given underlying value.
Definition json.hpp:645
VariantBase(UTF8CStringView value, const allocator_type &allocator)
Construct a String value with the given underlying value.
Definition json.hpp:824
VariantBase(const StringBase< Allocator > &value, const allocator_type &allocator)
Construct a String value with the given underlying value.
Definition json.hpp:656
VariantBase(const char8_t *value)
Construct a String value with the given underlying value.
Definition json.hpp:786
VariantBase(const StringBase< Allocator > &value)
Construct a String value with the given underlying value.
Definition json.hpp:667
VariantBase(const VariantBase &other, const allocator_type &allocator) noexcept
Copy constructor.
Definition json.hpp:947
static ValueBase< Allocator > parse(UTF8StringView jsonString, const SourceLocation &source={}, const allocator_type &allocator=allocator_type())
Parse a value of any JSON type from a UTF-8 JSON string.
Definition json.hpp:8263
VariantBase(UTF8StringView value, const allocator_type &allocator)
Construct a String value with the given underlying value.
Definition json.hpp:799
GREM_ALWAYS_INLINE std::partial_ordering operator<=>(const VariantBase &other) const
Compare this value to another.
Definition json.hpp:1083
VariantBase(Null) noexcept
Construct a Null value.
Definition json.hpp:613
VariantBase(CStringView value, const allocator_type &allocator)
Construct a String value with the given underlying value.
Definition json.hpp:747
VariantBase(UTF8StringView value)
Construct a String value with the given underlying value.
Definition json.hpp:811
Allocator< VariantBase > allocator_type
Allocator type used by the value.
Definition json.hpp:544
VariantBase(strict_arithmetic auto value) noexcept
Construct a Number value with the given underlying value.
Definition json.hpp:856
VariantBase(StringView value)
Construct a String value with the given underlying value.
Definition json.hpp:735
VariantBase(VariantBase &&other) noexcept
Move constructor.
Definition json.hpp:977
VariantBase(ObjectBase< Allocator > &&value) noexcept
Construct an Object value from the given underlying value.
Definition json.hpp:897
VariantBase(const ArrayBase< Allocator > &value, const allocator_type &allocator)
Construct an Array value with the given underlying value.
Definition json.hpp:909
VariantBase(UTF8CStringView value)
Construct a String value with the given underlying value.
Definition json.hpp:836
allocator_type get_allocator() const noexcept
Definition json.hpp:1044
VariantBase(const ObjectBase< Allocator > &value)
Construct an Object value with the given underlying value.
Definition json.hpp:878
static ValueBase< Allocator > parse(StringView jsonString, const SourceLocation &source={}, const allocator_type &allocator=allocator_type())
Parse a value of any JSON type from a JSON string interpreted as UTF-8.
Definition json.hpp:8268
VariantBase() noexcept
Construct a Null value.
Definition json.hpp:591
~VariantBase()=default
Destructor.
VariantBase(CStringView value)
Construct a String value with the given underlying value.
Definition json.hpp:758
VariantBase(Boolean value, const allocator_type &allocator) noexcept
Construct a Boolean value with the given underlying value.
Definition json.hpp:636
VariantBase(std::nullptr_t) noexcept
Construct a Null value.
Definition json.hpp:627
VariantBase(const char8_t *value, const allocator_type &allocator)
Construct a String value with the given underlying value.
Definition json.hpp:771
VariantBase(const char *value)
Construct a String value with the given underlying value.
Definition json.hpp:712
VariantBase(const allocator_type &allocator) noexcept
Construct a Null value.
Definition json.hpp:599
VariantBase(StringView value, const allocator_type &allocator)
Construct a String value with the given underlying value.
Definition json.hpp:724
VariantBase(VariantBase &&other, const allocator_type &allocator) noexcept
Move constructor.
Definition json.hpp:964
VariantBase(strict_arithmetic auto value, const allocator_type &allocator) noexcept
Construct a Number value with the given underlying value.
Definition json.hpp:846
VariantBase & operator=(const VariantBase &other)
Copy assignment.
Definition json.hpp:981
VariantBase(const char *value, const allocator_type &allocator)
Construct a String value with the given underlying value.
Definition json.hpp:700
Iterator type for decoding Unicode code points from a UTF-8 string, wrapping an existing iterator for...
Definition unicode.hpp:176
Non-owning view type for decoding Unicode code points from a contiguous UTF-8 string.
Definition unicode.hpp:317
constexpr sentinel end() const noexcept
Definition unicode.hpp:342
constexpr const iterator & begin() const noexcept
Definition unicode.hpp:338
Definition concepts.hpp:100
Definition concepts.hpp:47
Definition concepts.hpp:94
Definition concepts.hpp:67
Definition concepts.hpp:106
Definition concepts.hpp:35
Definition concepts.hpp:91
@ U
'u'
Definition keyboard.hpp:91
@ T
't'
Definition keyboard.hpp:90
Definition aliases.hpp:15
constexpr bool isPunctuationCharacter(char32_t codePoint) noexcept
Check if a Unicode code point is considered to be punctuation in JSON5.
Definition json.hpp:2816
auto onNumber(Callback callback)
Build a Parser::ValueVisitor that handles Number values with a given callback function.
Definition json.hpp:7005
void deserialize(std::istream &stream, T &value, const DeserializationOptions &options={}, DeserializerOverride deserializerOverride={}, const SourceLocation &source={})
Deserialize a value of any JSON-serializable type from an input stream.
Definition json.hpp:6743
StreamParserBase< std::allocator > StreamParser
Parser for reading UTF-8-encoded JSON input stream buffers using the default allocator.
Definition json.hpp:4525
void swap(ObjectBase< Allocator > &a, ObjectBase< Allocator > &b) noexcept
Definition json.hpp:7816
json::VariantBase< std::allocator > Variant
JSON value type using the default allocator.
Definition json.hpp:1094
ArrayBase< Allocator >::size_type erase(ArrayBase< Allocator > &container, const U &value)
Definition json.hpp:8131
constexpr bool isWhitespace(char32_t codePoint) noexcept
Check if a Unicode code point is considered to be whitespace in JSON5.
Definition json.hpp:2803
json::ObjectBase< std::allocator > Object
JSON object type using the default allocator.
Definition json.hpp:389
StringParserBase< std::allocator > StringParser
Parser for reading contiguous UTF-8-encoded JSON strings using the default allocator.
Definition json.hpp:4513
auto onArray(Callback callback)
Build a Parser::ValueVisitor that handles arrays with a given callback function.
Definition json.hpp:7059
auto onProperty(Callback callback)
Build a Parser::PropertyVisitor that handles object properties with a given callback function.
Definition json.hpp:7079
Parser< std::istreambuf_iterator< char >, Allocator > StreamParserBase
Parser for reading UTF-8-encoded JSON input stream buffers.
Definition json.hpp:4519
Parser< const char8_t *, Allocator > StringParserBase
Parser for reading contiguous UTF-8-encoded JSON strings.
Definition json.hpp:4507
double Number
JSON number type.
Definition json.hpp:250
TokenType
Type of a scanned JSON5 token.
Definition json.hpp:2836
@ PUNCTUATOR_OPEN_CURLY_BRACE
Open curly brace '{' symbol.
Definition json.hpp:2846
@ NUMBER_OCTAL
Octal number literal, e.g. 0777.
Definition json.hpp:2850
@ IDENTIFIER_FALSE
Keyword false.
Definition json.hpp:2839
@ PUNCTUATOR_CLOSE_CURLY_BRACE
Closing curly brace '}' symbol.
Definition json.hpp:2847
@ NUMBER_BINARY
Binary number literal, e.g. 0b0000000111111111.
Definition json.hpp:2849
@ PUNCTUATOR_COLON
Colon ':' symbol.
Definition json.hpp:2843
@ NUMBER_NEGATIVE_INFINITY
Keyword -Infinity.
Definition json.hpp:2854
@ END_OF_FILE
End-of-file marker.
Definition json.hpp:2837
@ PUNCTUATOR_CLOSE_SQUARE_BRACKET
Closing square bracket ']' symbol.
Definition json.hpp:2845
@ STRING
Quoted string literal, e.g. "abc".
Definition json.hpp:2848
@ NUMBER_POSITIVE_NAN
Keyword NaN.
Definition json.hpp:2855
@ IDENTIFIER_NAME
Unquoted identifier, e.g. abc.
Definition json.hpp:2841
@ NUMBER_DECIMAL
Decimal number literal, e.g. 511.
Definition json.hpp:2851
@ IDENTIFIER_NULL
Keyword null.
Definition json.hpp:2838
@ NUMBER_POSITIVE_INFINITY
Keyword Infinity.
Definition json.hpp:2853
@ IDENTIFIER_TRUE
Keyword true.
Definition json.hpp:2840
@ NUMBER_NEGATIVE_NAN
Keyword -NaN.
Definition json.hpp:2856
@ NUMBER_HEXADECIMAL
Hexadecimal number literal, e.g. 0x01FF.
Definition json.hpp:2852
@ PUNCTUATOR_OPEN_SQUARE_BRACKET
Open square bracket '[' symbol.
Definition json.hpp:2844
@ PUNCTUATOR_COMMA
Comma ',' symbol.
Definition json.hpp:2842
json::ArrayBase< std::allocator > Array
JSON array type using the default allocator.
Definition json.hpp:522
std::istream & operator>>(std::istream &stream, ObjectBase< Allocator > &value)
Read a JSON object from an input stream using the default deserialization options.
Definition json.hpp:4665
void deserializeFromString(grem::StringBase< char, std::char_traits< char >, Allocator > string, T &value, const DeserializationOptions &options={}, DeserializerOverride deserializerOverride={}, const SourceLocation &source={})
Deserialize a value of any JSON-serializable type from a string.
Definition json.hpp:4881
std::ostream & operator<<(std::ostream &stream, const ObjectBase< Allocator > &value)
Write a JSON object to an output stream using the default serialization options.
Definition json.hpp:4641
auto onNull(Callback callback)
Build a Parser::ValueVisitor that handles Null values with a given callback function.
Definition json.hpp:6924
grem::StringBase< char, std::char_traits< char >, Allocator< char > > StringBase
JSON string type.
Definition json.hpp:240
Monostate Null
JSON null type.
Definition json.hpp:227
auto onObject(Callback callback)
Build a Parser::ValueVisitor that handles objects with a given callback function.
Definition json.hpp:7032
void serialize(std::ostream &stream, const T &value, const SerializationOptions &options={}, SerializerOverride serializerOverride={})
Serialize a value of any JSON-serializable type to an output stream.
Definition json.hpp:6738
StringBase< std::allocator > String
JSON string type using the default allocator.
Definition json.hpp:245
json::ValueBase< std::allocator > Value
JSON value type with an associated SourceLocation using the default allocator.
Definition json.hpp:2794
bool Boolean
JSON boolean type.
Definition json.hpp:232
grem::StringBase< char, std::char_traits< char >, Allocator > serializeToString(const T &value, const SerializationOptions &options={}, SerializerOverride serializerOverride={}, const Allocator &allocator=Allocator())
Serialize a value of any JSON-serializable type to a string.
Definition json.hpp:4847
constexpr bool isLineTerminatorCharacter(char32_t codePoint) noexcept
Check if a Unicode code point marks the beginning of a line terminator sequence in JSON5.
Definition json.hpp:2829
auto onString(Callback callback)
Build a Parser::ValueVisitor that handles String values with a given callback function.
Definition json.hpp:6978
auto onBoolean(Callback callback)
Build a Parser::ValueVisitor that handles Boolean values with a given callback function.
Definition json.hpp:6951
ObjectBase< Allocator >::size_type erase_if(ObjectBase< Allocator > &container, Predicate predicate)
Definition json.hpp:7890
constexpr void forEachField(Aggregate &&value, auto fn)
Execute a function for each field of an aggregate.
Definition metaprogramming.hpp:1297
constexpr bool always_false_v
Type-dependent boolean that always evaluates to false.
Definition metaprogramming.hpp:61
constexpr void forEachNamedField(Aggregate &&value, auto fn)
Execute a function for each field of an aggregate, also including the field name.
Definition metaprogramming.hpp:1664
constexpr std::size_t aggregate_size_v
The number of fields in a given aggregate type.
Definition metaprogramming.hpp:921
constexpr void forEachNamedEnumerand(auto fn)
Execute a function for each consecutive valid enumerand starting at value 0 in a given enum type,...
Definition metaprogramming.hpp:1878
grem::json::ArrayBase< std::pmr::polymorphic_allocator > Array
Definition json.hpp:8300
grem::json::StringParserBase< std::pmr::polymorphic_allocator > StringParser
Definition json.hpp:8303
grem::json::StreamParserBase< std::pmr::polymorphic_allocator > StreamParser
Definition json.hpp:8304
grem::json::ValueBase< std::pmr::polymorphic_allocator > Value
Definition json.hpp:8302
grem::json::ObjectBase< std::pmr::polymorphic_allocator > Object
Definition json.hpp:8299
grem::json::StringBase< std::pmr::polymorphic_allocator > String
Definition json.hpp:8298
grem::json::VariantBase< std::pmr::polymorphic_allocator > Variant
Definition json.hpp:8301
Definition Allocation.hpp:554
Definition aliases.hpp:21
constexpr bool isValidCodePoint(char32_t codePoint) noexcept
Check if a 32-bit unsigned integer value falls within the valid ranges for a Unicode code point.
Definition unicode.hpp:28
constexpr InplaceBuffer< char8_t, 4 > encodeUTF8FromCodePoint(char32_t codePoint) noexcept
Encode a Unicode code point into a sequence of UTF-8 code units.
Definition unicode.hpp:136
Definition aliases.hpp:9
String toString(int value)
Definition String.hpp:23
CStringViewBase< char8_t, std::char_traits< char8_t > > UTF8CStringView
Definition CStringView.hpp:636
constexpr auto find(input_range auto &&range, const auto &value)
Definition algorithms.hpp:242
constexpr auto unique(forward_range auto &&range)
Definition algorithms.hpp:577
constexpr auto count(input_range auto &&range, const auto &value)
Definition algorithms.hpp:234
constexpr auto lowerBound(forward_range auto &&sortedRange, const auto &value, auto compare)
Definition algorithms.hpp:426
constexpr auto inplaceMerge(bidirectional_range auto &&sortedRange, auto middleIterator)
Definition algorithms.hpp:497
constexpr auto equalRange(forward_range auto &&sortedRange, const auto &value, auto compare)
Definition algorithms.hpp:465
std::ratio< Num, Den > Ratio
Definition time.hpp:19
constexpr auto move(input_range auto &&range, auto outputIterator)
Definition algorithms.hpp:669
String formatString(FormatString< Args... > format, const Args &... args)
Format specification syntax examples:
Definition formatting.hpp:448
GREM_ALWAYS_INLINE constexpr vec< 1, T > GREM_VECTORCALL operator|(vec< 1, T > a, vec< 1, T > b)
Definition math.hpp:1752
constexpr void sort(random_access_range auto &&range)
Definition algorithms.hpp:505
constexpr auto upperBound(forward_range auto &&sortedRange, const auto &value)
Definition algorithms.hpp:457
std::chrono::duration< Rep, Period > DurationBase
Definition time.hpp:39
constexpr bool equal(input_range auto &&rangeA, input_range auto &&rangeB)
Definition algorithms.hpp:358
GREM_ALWAYS_INLINE constexpr vec< N, T > GREM_VECTORCALL trunc(vec< N, T > a)
Definition math.hpp:1420
StringBase< char, std::char_traits< char >, std::allocator< char > > String
Definition String.hpp:17
constexpr bool contains(input_range auto &&range, const auto &value)
Definition algorithms.hpp:299
constexpr detail::Matcher< V > match(V &&variant)
Choose a function overload to execute based on the active alternative of a variant.
Definition Variant.hpp:1922
StringBase< char8_t, std::char_traits< char8_t >, std::allocator< char8_t > > UTF8String
Definition String.hpp:18
StringViewBase< char, std::char_traits< char > > StringView
Definition StringView.hpp:16
std::basic_string< CharT, Traits, Allocator > StringBase
Definition String.hpp:15
GREM_ALWAYS_INLINE constexpr bool GREM_VECTORCALL all(bool a)
Definition math.hpp:1285
StringViewBase< char8_t, std::char_traits< char8_t > > UTF8StringView
Definition StringView.hpp:17
CStringViewBase< char, std::char_traits< char > > CStringView
Definition CStringView.hpp:635
Definition fundamentals.hpp:27
static constexpr T MAX
Definition fundamentals.hpp:29
static constexpr T MIN
Definition fundamentals.hpp:28
Unit type for representing an empty alternative in Variant.
Definition Variant.hpp:242
Definition Pair.hpp:53
T1 first
Definition Pair.hpp:57
Options for JSON deserialization.
Definition json.hpp:214
Base template to specialize in order to implement JSON deserialization for a specific type.
Definition json.hpp:4569
Exception type for errors originating from the JSON API.
Definition json.hpp:103
size_t lineNumber
Line number, starting at 1 for the first line.
Definition json.hpp:108
SourceLocation getSource() const noexcept
Definition json.hpp:138
Error(const auto &message, const SourceLocation &source)
Definition json.hpp:116
bool messageAttachesToPrecedingFilepath() const noexcept override
Definition json.hpp:134
size_t columnNumber
Column number, starting at 1 for the first column.
Definition json.hpp:114
void writeMessage(String &output) const override
Definition json.hpp:121
void visitProperty(const SourceLocation &source, StringBase< Allocator > &&key, Parser &parser) override
Callback for each object property.
Definition json.hpp:3588
Visitor visitor
Definition json.hpp:3583
ConcretePropertyVisitor(Visitor visitor)
Definition json.hpp:3585
void visitString(const SourceLocation &source, StringBase< Allocator > &&value) override
Callback for values of type String.
Definition json.hpp:3514
void visitNull(const SourceLocation &source, Null value) override
Callback for values of type Null.
Definition json.hpp:3498
Visitor visitor
Definition json.hpp:3493
void visitObject(const SourceLocation &source, Parser &parser) override
Callback for objects.
Definition json.hpp:3530
void visitArray(const SourceLocation &source, Parser &parser) override
Callback for arrays.
Definition json.hpp:3538
ConcreteValueVisitor(Visitor visitor)
Definition json.hpp:3495
void visitNumber(const SourceLocation &source, Number value) override
Callback for values of type Number.
Definition json.hpp:3522
void visitBoolean(const SourceLocation &source, Boolean value) override
Callback for values of type Boolean.
Definition json.hpp:3506
Implementation of PropertyVisitor that skips over the parsed property and discards the result.
Definition json.hpp:3614
void visitProperty(const SourceLocation &source, StringBase< Allocator > &&key, Parser &parser) override
Callback for each object property.
Definition json.hpp:3616
Implementation of ValueVisitor that skips over the parsed value and discards the result.
Definition json.hpp:3599
void visitBoolean(const SourceLocation &source, Boolean value) override
Callback for values of type Boolean.
Definition json.hpp:3602
void visitNumber(const SourceLocation &source, Number value) override
Callback for values of type Number.
Definition json.hpp:3604
void visitArray(const SourceLocation &source, Parser &parser) override
Callback for arrays.
Definition json.hpp:3606
void visitObject(const SourceLocation &source, Parser &parser) override
Callback for objects.
Definition json.hpp:3605
void visitString(const SourceLocation &source, StringBase< Allocator > &&value) override
Callback for values of type String.
Definition json.hpp:3603
void visitNull(const SourceLocation &source, Null value) override
Callback for values of type Null.
Definition json.hpp:3601
Stateful wrapper object of an input stream for JSON deserialization.
Definition json.hpp:5525
bool nextIsString() const
Check if the next value of the input is a JSON value of type String.
Definition json.hpp:5750
String readString()
Read a single JSON value of type String from the input.
Definition json.hpp:5730
Optional< SourceLocation > readAggregateField(StringView fieldName, Aggregate &aggregate, DeserializerOverride deserializerOverride={})
Read a single JSON value from the input into any value into a specific named field of an aggregate wh...
Definition json.hpp:6505
Optional< Number > readNumberOrNull()
Read a single nullable JSON value of type Number from the input.
Definition json.hpp:5899
Aggregate readAggregateObject(DeserializerOverride deserializerOverride={})
Read a single JSON value from the input into any value of aggregate type whose fields are deserializa...
Definition json.hpp:6580
bool nextIsArray() const
Check if the next value of the input is a JSON value of type Array.
Definition json.hpp:6350
SourceLocation readBoolean(Boolean &value)
Read a single JSON value of type Boolean from the input.
Definition json.hpp:5608
Optional< Array > readArrayOrNull()
Read a single nullable JSON value of type Array from the input.
Definition json.hpp:6365
Reader(std::istream &stream, const SourceLocation &source={}, const DeserializationOptions &options={})
Construct a reader with an input stream as input.
Definition json.hpp:5548
SourceLocation readValue(Value &value)
Read a single JSON value from the input.
Definition json.hpp:6411
Array readArray()
Read a single JSON array from the input into any container of elements that are default-constructible...
Definition json.hpp:6330
SourceLocation readCustomArray(auto readItem)
Read a single JSON array from the input, using a callback function for reading its items.
Definition json.hpp:6171
bool nextIsNull() const
Check if the next value of the input is a JSON value of type Null.
Definition json.hpp:5586
Object readObject()
Read a single JSON object from the input into any container of key-value pairs where the key and valu...
Definition json.hpp:6109
Aggregate readAggregateArray(DeserializerOverride deserializerOverride={})
Read a single JSON value from the input into any value of aggregate type whose fields are deserializa...
Definition json.hpp:6675
T readNumber()
Read a single JSON value of type Number from the input.
Definition json.hpp:5882
bool nextIsBoolean() const
Check if the next value of the input is a JSON value of type Boolean.
Definition json.hpp:5648
DeserializationOptions options
The current options of the deserialization process.
Definition json.hpp:5538
T deserialize(DeserializerOverride deserializerOverride={})
Read a JSON value from the input into any value that is deserializable from JSON using its correspond...
Definition json.hpp:6717
SourceLocation readNumber(T &value)
Read a single JSON value of type Number from the input into any value that Number can be explicitly c...
Definition json.hpp:5812
Optional< Boolean > readBooleanOrNull()
Read a single nullable JSON value of type Boolean from the input.
Definition json.hpp:5663
SourceLocation readAggregateObject(Aggregate &value, DeserializerOverride deserializerOverride={})
Read a single JSON value from the input into any value of aggregate type whose fields are deserializa...
Definition json.hpp:6549
SourceLocation readNumber(Number &value)
Read a single JSON value of type Number from the input.
Definition json.hpp:5789
SourceLocation readArray(Array &value)
Read a single JSON value of type Array from the input.
Definition json.hpp:6220
Optional< Object > readObjectOrNull()
Read a single nullable JSON value of type Object from the input.
Definition json.hpp:6144
Array readArray()
Read a single JSON value of type Array from the input.
Definition json.hpp:6300
typename Parser< It >::Token Token
Token type of the reader's parser.
Definition json.hpp:5533
SourceLocation readString(String &value)
Read a single JSON value of type String from the input.
Definition json.hpp:5687
SourceLocation readArray(auto &value, DeserializerOverride deserializerOverride={})
Read a single JSON array from the input into any container of elements that are default-constructible...
Definition json.hpp:6256
Value readValue()
Read a single JSON value from the input.
Definition json.hpp:6430
SourceLocation readObject(Object &value)
Read a single JSON value of type Object from the input.
Definition json.hpp:5986
bool nextIsObject() const
Check if the next value of the input is a JSON value of type Object.
Definition json.hpp:6129
void deserialize(T &value, DeserializerOverride deserializerOverride={})
Read a JSON value from the input into any value that is deserializable from JSON using its correspond...
Definition json.hpp:7464
Number readNumber()
Read a single JSON value of type Number from the input.
Definition json.hpp:5841
Object readObject()
Read a single JSON value of type Object from the input.
Definition json.hpp:6077
bool nextIsNumber() const
Check if the next value of the input is a JSON value of type Number.
Definition json.hpp:5861
SourceLocation readString(auto &value)
Read a single JSON value of type String from the input into any value that can be assigned from a sta...
Definition json.hpp:5709
SourceLocation readAggregateArray(Aggregate &value, DeserializerOverride deserializerOverride={})
Read a single JSON value from the input into any value of aggregate type whose fields are deserializa...
Definition json.hpp:6615
SourceLocation readCustomObject(auto readProperty)
Read a single JSON object from the input, using a callback function for reading its properties.
Definition json.hpp:5928
Boolean readBoolean()
Read a single JSON value of type Boolean from the input.
Definition json.hpp:5628
SourceLocation readOptional(T &value, DeserializerOverride deserializerOverride={})
Read a single nullable JSON value from the input into any value that is default-constructible,...
Definition json.hpp:6466
SourceLocation readNull()
Read a single JSON value of type Null from the input.
Definition json.hpp:5566
SourceLocation readObject(auto &value, DeserializerOverride deserializerOverride={})
Read a single JSON object from the input into any container of key-value pairs where the key and valu...
Definition json.hpp:6024
SourceLocation readValue(Variant &value)
Read a single JSON value from the input.
Definition json.hpp:6388
Optional< String > readStringOrNull()
Read a single nullable JSON value of type String from the input.
Definition json.hpp:5765
Options for JSON serialization.
Definition json.hpp:146
size_t relativeIndentation
The number of indentation characters that each new level of indentation will add.
Definition json.hpp:157
CStringView newlineString
Null-terminated ASCII string representing the newline sequence to use when performing line breaks.
Definition json.hpp:208
char indentationCharacter
The character to use when performing indentation.
Definition json.hpp:162
size_t indentation
The starting indentation level, expressed as the number of indentation characters.
Definition json.hpp:151
bool prettyPrint
Format the output in a way that is nicely human-readable.
Definition json.hpp:172
size_t prettyPrintMaxSingleLineObjectPropertyCount
Maximum size of an object before it is split into multiple lines when pretty printing.
Definition json.hpp:186
size_t prettyPrintMaxSingleLineArrayItemCount
Maximum size of an array before it is split into multiple lines when pretty printing.
Definition json.hpp:200
Base template to specialize in order to implement JSON serialization for a specific type.
Definition json.hpp:4551
Line and column numbers of a location in a JSON source string.
Definition json.hpp:77
size_t lineNumber
Line number, starting at 1 for the first line.
Definition json.hpp:82
size_t columnNumber
Column number, starting at 1 for the first column.
Definition json.hpp:88
constexpr bool operator==(const SourceLocation &other) const =default
Compare this source location to another for equality.
Token data scanned from JSON.
Definition json.hpp:2863
SourceLocation source
Location of the scanned string in the JSON source string.
Definition json.hpp:2865
StringBase< Allocator > string
Scanned string.
Definition json.hpp:2864
TokenType type
Scanned token type.
Definition json.hpp:2866
Stateful wrapper object of an output stream for JSON serialization.
Definition json.hpp:4925
void writeNewline()
Write a newline sequence to the output.
Definition json.hpp:4989
void writeCustomArray(size_t itemCountHint, auto callback)
Write a single JSON array to the output, using a callback function for writing out the items.
Definition json.hpp:5225
SerializationOptions options
The current options of the serialization process.
Definition json.hpp:4933
void writeNumber(Number value)
Write a single JSON value of type Number to the output.
Definition json.hpp:5091
void writeIndentation()
Write a sequence of indentation characters to the output.
Definition json.hpp:4978
void writeOptional(const auto &value, SerializerOverride serializerOverride={})
Write a single JSON value to the output from any value that supports conversion to bool and the deref...
Definition json.hpp:5321
void writeCustomObject(size_t propertyCountHint, auto callback)
Write a single JSON object to the output, using a callback function for writing out the properties.
Definition json.hpp:5134
void writeAggregateArray(const Aggregate &value, SerializerOverride serializerOverride={})
Write a single JSON value to the output from any value of aggregate type.
Definition json.hpp:5371
void serialize(const T &value, SerializerOverride serializerOverride={})
Write any JSON-serializable value to the output using its corresponding implementation of Serializer.
Definition json.hpp:7410
void writeNull()
Write a single JSON value of type Null to the output.
Definition json.hpp:4998
void writeAggregateObject(const Aggregate &value, SerializerOverride serializerOverride={})
Write a single JSON value to the output from any value of aggregate type.
Definition json.hpp:5346
Writer(std::ostream &stream, const SerializationOptions &options={})
Construct a writer with an output stream as output.
Definition json.hpp:4941
void writeBoolean(Boolean value)
Write a single JSON value of type Boolean to the output.
Definition json.hpp:5009
void writeString(UTF8StringView value)
Write a single JSON value of type String to the output from a raw UTF8 string.
Definition json.hpp:5057
void writeArray(const auto &value, SerializerOverride serializerOverride={})
Write a single JSON array to the output from any range of JSON-serializable values.
Definition json.hpp:5283
void writeString(const auto &value)
Write a single JSON value of type String to the output from any string-view-like or JSON-serializable...
Definition json.hpp:5072
void writeCustomArray(auto callback)
Write a single JSON array to the output, using a callback function for writing out the items.
Definition json.hpp:5264
void write(char ch)
Write a single raw char to the output without any extra formatting.
Definition json.hpp:4952
void writeObject(const auto &value, SerializerOverride serializerOverride={})
Write a single JSON object to the output from any range of JSON-serializable key-value pairs.
Definition json.hpp:5196
void writeCustomObject(auto callback)
Write a single JSON object to the output, using a callback function for writing out the properties.
Definition json.hpp:5177
void write(StringView raw)
Write a raw sequence of chars to the output without any extra formatting.
Definition json.hpp:4963
void writeString(StringView value)
Write a single JSON value of type String to the output from a raw string.
Definition json.hpp:5020
Sentinel type for UTF8Iterator.
Definition unicode.hpp:166