MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
JsonUtils.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Contributors to the Media eXchange Layer project.
2// SPDX-License-Identifier: Apache-2.0
3
4#pragma once
5
6#include <cmath>
7#include <concepts>
8#include <cstddef>
9#include <cstdint>
10#include <algorithm>
11#include <limits>
12#include <stdexcept>
13#include <string>
14#include <string_view>
15#include <fmt/format.h>
16#include <picojson/wrapper.h>
17#include "StringUtils.hpp"
18
19namespace mxl::lib
20{
23 {
25 std::size_t maxInputSize = std::size_t{64} * 1024U;
27 std::size_t maxDepth = 32U;
29 std::size_t maxContainerSize = 1024U;
30 };
31
32 namespace detail
33 {
37 {
38 public:
42 LimitedJsonParseContext(picojson::value* out, JsonLimits const& limits, std::string& error, std::size_t depth) noexcept
43 : _out{out}
44 , _limits{&limits}
45 , _error{&error}
46 , _depth{depth}
47 {}
48
51
53 bool set_null()
54 {
55 *_out = picojson::value{};
56 return true;
57 }
58
60 bool set_bool(bool value)
61 {
62 *_out = picojson::value{value};
63 return true;
64 }
65
66#ifdef PICOJSON_USE_INT64
68 bool set_int64(std::int64_t value)
69 {
70 *_out = picojson::value{value};
71 return true;
72 }
73#endif
74
76 bool set_number(double value)
77 {
78 // picojson::value throws std::overflow_error for these. Report them as a parse error instead.
79 if (!std::isfinite(value))
80 {
81 *_error = "JSON number is out of range.";
82 return false;
83 }
84 *_out = picojson::value{value};
85 return true;
86 }
87
89 template<typename Iter>
90 bool parse_string(picojson::input<Iter>& in)
91 {
92 *_out = picojson::value{picojson::string_type, false};
93 return picojson::_parse_string(_out->get<std::string>(), in);
94 }
95
98 {
99 if (!checkDepth())
100 {
101 return false;
102 }
103 *_out = picojson::value{picojson::array_type, false};
104 return true;
105 }
106
108 template<typename Iter>
109 bool parse_array_item(picojson::input<Iter>& in, std::size_t index)
110 {
111 if (index >= _limits->maxContainerSize)
112 {
113 *_error = fmt::format("JSON array has more than {} items.", _limits->maxContainerSize);
114 return false;
115 }
116 auto& array = _out->get<picojson::array>();
117 array.emplace_back();
118 auto child = LimitedJsonParseContext{&array.back(), *_limits, *_error, _depth + 1U};
119 return picojson::_parse(child, in);
120 }
121
123 bool parse_array_stop(std::size_t)
124 {
125 return true;
126 }
127
130 {
131 if (!checkDepth())
132 {
133 return false;
134 }
135 *_out = picojson::value{picojson::object_type, false};
136 return true;
137 }
138
141 template<typename Iter>
142 bool parse_object_item(picojson::input<Iter>& in, std::string const& key)
143 {
144 auto& object = _out->get<picojson::object>();
145 if (object.size() >= _limits->maxContainerSize)
146 {
147 *_error = fmt::format("JSON object has more than {} members.", _limits->maxContainerSize);
148 return false;
149 }
150 // picojson keeps the last of several equal keys. Reject them, because other parsers may keep the first.
151 auto const [it, inserted] = object.try_emplace(key);
152 if (!inserted)
153 {
154 *_error = fmt::format("JSON object has the key '{}' more than once.", key);
155 return false;
156 }
157 auto child = LimitedJsonParseContext{&it->second, *_limits, *_error, _depth + 1U};
158 return picojson::_parse(child, in);
159 }
160
161 private:
164 {
165 if (_depth >= _limits->maxDepth)
166 {
167 *_error = fmt::format("JSON nesting is deeper than {} levels.", _limits->maxDepth);
168 return false;
169 }
170 return true;
171 }
172
173 private:
174 picojson::value* _out;
176 std::string* _error;
178 std::size_t _depth;
179 };
180 }
181
193 inline std::string parseJson(picojson::value& out, std::string_view text, JsonLimits const& limits = {})
194 {
195 if (text.size() > limits.maxInputSize)
196 {
197 return fmt::format("JSON input has {} bytes, the limit is {}.", text.size(), limits.maxInputSize);
198 }
199
200 auto limitError = std::string{};
201 auto syntaxError = std::string{};
202 auto ctx = detail::LimitedJsonParseContext{&out, limits, limitError, 0U};
203 auto const end = picojson::_parse(ctx, text.begin(), text.end(), &syntaxError);
204 if (!limitError.empty())
205 {
206 return limitError;
207 }
208 if (!syntaxError.empty())
209 {
210 return syntaxError;
211 }
212
213 auto const isWhitespace = [](char c) noexcept
214 {
215 return (c == ' ') || (c == '\t') || (c == '\n') || (c == '\r');
216 };
217 if (!std::all_of(end, text.end(), isWhitespace))
218 {
219 return "Unexpected content after the JSON value.";
220 }
221 return {};
222 }
223
235 template<std::integral T>
236 inline T jsonToInteger(picojson::value const& value, std::string_view name)
237 {
238 if (!value.is<double>())
239 {
240 throw std::invalid_argument{fmt::format("'{}' must be a number.", name)};
241 }
242
243 auto const number = value.get<double>();
244
245 // 2^digits is the first value past the range of T. It is exact as a double, while numeric_limits<T>::max() may
246 // round up to it.
247 auto const upper = std::ldexp(1.0, std::numeric_limits<T>::digits);
248 auto const lower = std::numeric_limits<T>::is_signed ? -upper : 0.0;
249 if ((std::trunc(number) != number) || (number < lower) || (number >= upper))
250 {
251 throw std::invalid_argument{fmt::format(
252 "'{}' must be a whole number between {} and {}, got {}.", name, std::numeric_limits<T>::min(), std::numeric_limits<T>::max(), number)};
253 }
254 return static_cast<T>(number);
255 }
256
269 template<std::integral T>
270 inline T jsonStringToInteger(picojson::value const& value, std::string_view name)
271 {
272 if (!value.is<std::string>())
273 {
274 throw std::invalid_argument{fmt::format("'{}' must be a string.", name)};
275 }
276 return stringToInteger<T>(value.get<std::string>(), name);
277 }
278}
LimitedJsonParseContext(picojson::value *out, JsonLimits const &limits, std::string &error, std::size_t depth) noexcept
Construct a new LimitedJsonParseContext for a value, with given limits. Refuses to parse any contexts...
Definition JsonUtils.hpp:42
bool parse_array_start()
Start parsing an array. Called by picojson. Throws an error if already nested to the configured limit...
Definition JsonUtils.hpp:97
bool set_null()
Set the current value to null. Called by picojson when parsing.
Definition JsonUtils.hpp:53
bool parse_array_item(picojson::input< Iter > &in, std::size_t index)
Parse an array item. Called by picojson. Throws an error if index exceeded the configured maximum con...
LimitedJsonParseContext(LimitedJsonParseContext const &)=delete
bool parse_object_item(picojson::input< Iter > &in, std::string const &key)
bool set_number(double value)
Set the current value to a numerical value value. Called by picojson when parsing.
Definition JsonUtils.hpp:76
std::size_t _depth
Number of arrays and objects that enclose the value this context parses.
bool set_bool(bool value)
Set the current value to the boolean value value. Called by picojson when parsing.
Definition JsonUtils.hpp:60
LimitedJsonParseContext & operator=(LimitedJsonParseContext const &)=delete
bool parse_string(picojson::input< Iter > &in)
Start parsing a string. Called by picojson, delegates to picojsons internal string parser.
Definition JsonUtils.hpp:90
std::size_t size() const noexcept
Returns the total number of writers that are registered in the DomainWatcher.
T stringToInteger(std::string_view text, std::string_view name)
T jsonStringToInteger(picojson::value const &value, std::string_view name)
T jsonToInteger(picojson::value const &value, std::string_view name)
std::string parseJson(picojson::value &out, std::string_view text, JsonLimits const &limits={})
Limits applied by parseJson().
Definition JsonUtils.hpp:23
std::size_t maxDepth
Largest number of nested arrays and objects. picojson parses recursively, so this also bounds stack u...
Definition JsonUtils.hpp:27
std::size_t maxContainerSize
Largest number of items in one array or members in one object.
Definition JsonUtils.hpp:29
std::size_t maxInputSize
Largest accepted input in bytes. This also bounds the length of any string in the document.
Definition JsonUtils.hpp:25
uint64_t index