json::parse() takes a string_view as input. It takes an optional callback to use for error reporting, which defaults to a no-op that ignores all errors. It also takes an optional max recursion depth limit, which defaults to the one from the JSON spec, 512.
| 272 | // ignores all errors. It also takes an optional max recursion depth |
| 273 | // limit, which defaults to the one from the JSON spec, 512. |
| 274 | std::optional<value> parse( |
| 275 | std::string_view str, |
| 276 | diagnostic_function errors_callback = diagnostic_function(), |
| 277 | int max_recursion = 512) |
| 278 | { |
| 279 | // Turn the input range into a UTF-32 range, so that we can be sure |
| 280 | // that we fall into the Unicode-aware parsing path inside parse() |
| 281 | // below. |
| 282 | auto const range = boost::parser::as_utf32(str); |
| 283 | using iter_t = decltype(range.begin()); |
| 284 | |
| 285 | if (max_recursion <= 0) |
| 286 | max_recursion = INT_MAX; |
| 287 | |
| 288 | // Initialize our globals to the current depth (0), and the max depth |
| 289 | // (max_recursion). |
| 290 | global_state globals{0, max_recursion}; |
| 291 | bp::callback_error_handler error_handler(errors_callback); |
| 292 | // Make a new parser that includes the globals and error handler. |
| 293 | auto const parser = bp::with_error_handler( |
| 294 | bp::with_globals(value_p, globals), error_handler); |
| 295 | |
| 296 | try { |
| 297 | // Parse. If no exception is thrown, due to: a failed expectation |
| 298 | // (such as foo > bar, where foo matches the input, but then bar |
| 299 | // cannot); or because the nesting depth is exceeded; we simply |
| 300 | // return the result of the parse. The result will contextually |
| 301 | // convert to false if the parse failed. Note that the |
| 302 | // failed-expectation exception is caught internally, and used to |
| 303 | // generate an error message. |
| 304 | return bp::parse(range, parser, ws); |
| 305 | } catch (excessive_nesting<iter_t> const & e) { |
| 306 | // If we catch an excessive_nesting exception, just report it |
| 307 | // and return an empty/failure result. |
| 308 | if (errors_callback) { |
| 309 | std::string const message = "error: Exceeded maximum number (" + |
| 310 | std::to_string(max_recursion) + |
| 311 | ") of open arrays and/or objects"; |
| 312 | std::stringstream ss; |
| 313 | bp::write_formatted_message( |
| 314 | ss, "", range.begin(), e.iter, range.end(), message); |
| 315 | errors_callback(ss.str()); |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | return {}; |
| 320 | } |
| 321 | |
| 322 | } |
| 323 |
no test coverage detected