Illustrated C/C++ source sheets, symbol index, API relationship graph, compiler console and debug trace

LIVE AI / FLEXIBLE SENSING / FLIGHT CONTEXT

Sensoraia API

Live AI and sensing, connected to the flight.
See, listen, inspect and return supported results while airborne.

Loading...
Searching...
No Matches
opencv_json.hpp
Go to the documentation of this file.
1/*
2 * Copyright 2026 OpenUAS
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/**
19 * @file opencv_json.hpp
20 * @brief Header-only C++17 value adapter around OpenCV's JSON persistence layer.
21 * @details OpenCV remains the parser and ordinary writer. Normalization carries
22 * null, booleans and 64-bit integers through reserved string markers so those
23 * types are not lost in FileStorage's representation. Nodes are then detached
24 * from FileStorage into a heap-backed tree usable by existing C++ consumers.
25 *
26 * @par Ownership and mutation
27 * Ordinary Value copies recursively clone their trees. Child lookups and items()
28 * initially return shared child handles instead, allowing a selected child's
29 * mutators to affect its parent. Copying such a handle creates an independent
30 * tree; assigning a new Value to the handle rebinds the handle, not the parent slot.
31 *
32 * @par Deliberate limits of this adapter
33 * This is not JSONbourne's bounded arena API: strings, maps, vectors and shared
34 * nodes allocate, while cloning, conversion and serialization recurse. No fixed
35 * nesting or allocation budget is imposed here. Objects use unique sorted map
36 * keys rather than retaining duplicate members or their original source order.
37 * @pre Application string/key data must not use the reserved
38 * __USHER_OPENCV_JSON_ namespace, which belongs to the transport representation.
39 * @note OpenCV acceptance and this adapter's normalization determine accepted
40 * input; this wrapper is not an independent strict RFC 8259 validator.
41 * @see usher_cv_json::Value::parse(), usher_cv_json::Value::dump_sorted()
42 */
43#ifndef USHER_OPENCV_JSON_HPP
44#define USHER_OPENCV_JSON_HPP
45
46#include <opencv2/core.hpp>
47#include <opencv2/core/persistence.hpp>
48
49#include <algorithm>
50#include <array>
51#include <cctype>
52#include <charconv>
53#include <cmath>
54#include <cstddef>
55#include <cstdint>
56#include <cstdlib>
57#include <initializer_list>
58#include <limits>
59#include <map>
60#include <memory>
61#include <stdexcept>
62#include <string>
63#include <string_view>
64#include <system_error>
65#include <type_traits>
66#include <utility>
67#include <vector>
68
69/** @brief OpenCV-backed JSON values and the internal tree supporting them. */
70namespace usher_cv_json {
71
72/**
73 * @brief Heap-backed tagged storage independent of a FileStorage lifetime.
74 * @details Separate signed, unsigned and real fields avoid forcing 64-bit
75 * integers through a double. Only the field selected by kind is semantically
76 * active; mutators need not clear storage belonging to previously selected kinds.
77 */
78struct Node {
79 /** @brief Active payload category; boolean is distinct from integer storage. */
80 enum class Kind {
81 Null, /**< JSON null with no active scalar payload. */
82 Bool, /**< Native boolean. */
83 Signed, /**< Signed 64-bit integer. */
84 Unsigned, /**< Unsigned 64-bit integer. */
85 Real, /**< Double-precision real value. */
86 String, /**< Owned byte string. */
87 Array, /**< Ordered child-node sequence. */
88 Object /**< Unique members in std::map key order. */
89 };
90 Kind kind = Kind::Null; /**< Tag governing interpretation and serialization. */
91 bool boolean = false; /**< Bool payload. */
92 int64_t signed_number = 0; /**< Signed payload. */
93 uint64_t unsigned_number = 0; /**< Unsigned payload. */
94 double real_number = 0; /**< Real payload; construction alone does not reject nonfinite values. */
95 std::string string; /**< String payload with std::string byte-length semantics. */
96 std::vector<std::shared_ptr<Node>> array; /**< Array children in insertion order. */
97 std::map<std::string, std::shared_ptr<Node>> object; /**< Unique keys with shared child ownership. */
98};
99
100/**
101 * @brief C++ value interface with explicit conversions and OpenCV JSON I/O.
102 * @details Copy construction/assignment are deep; lookup-produced handles share
103 * a selected node until copied or rebound. Conversion failures throw rather than
104 * silently turning missing, differently typed or out-of-range data into defaults.
105 * @note Allocation failures may additionally propagate standard-library exceptions.
106 */
107class Value {
108public:
109 /** @brief Adapter errors exposed independently of OpenCV's exception type. */
110 class exception : public std::runtime_error {
111 public:
112 /** @brief Reuse runtime_error constructors to retain descriptive error text. */
113 using std::runtime_error::runtime_error;
114 };
115 /** @brief One named value supplied to an object factory. */
116 using Field = std::pair<std::string, Value>;
117
118 /** @brief Allocate a fresh null node instead of using a shared mutable singleton. */
119 Value() : node_(std::make_shared<Node>()) {}
120 /** @brief Construct null from the C++ nullptr tag. */
121 Value(std::nullptr_t) : Value() {}
122 /**
123 * @brief Construct a boolean without confusing it with an integral payload.
124 * @param[in] value Boolean to store.
125 */
126 Value(bool value) : Value() {
127 node_->kind = Node::Kind::Bool;
128 node_->boolean = value;
129 }
130 /**
131 * @brief Copy a terminated string; a null pointer selects an empty string.
132 * @param[in] value C string, or nullptr; embedded NULs require the std::string overload.
133 */
134 Value(const char *value) : Value(std::string(value ? value : "")) {}
135 /**
136 * @brief Own a complete byte string rather than borrowing external storage.
137 * @param[in] value String copied with its explicit byte length.
138 */
139 Value(const std::string &value) : Value() {
141 node_->string = value;
142 }
143
144 /**
145 * @brief Store native integral input in its signed or unsigned 64-bit category.
146 * @tparam Number Integral source type other than bool.
147 * @param[in] value Number converted to the corresponding 64-bit storage type.
148 * @note bool is excluded so overload resolution preserves boolean semantics.
149 */
150 template <typename Number,
151 typename = std::enable_if_t<std::is_integral_v<Number> &&
152 !std::is_same_v<Number, bool>>>
153 Value(Number value) : Value() {
154 if constexpr (std::is_signed_v<Number>) {
156 node_->signed_number = static_cast<int64_t>(value);
157 } else {
159 node_->unsigned_number = static_cast<uint64_t>(value);
160 }
161 }
162 /**
163 * @brief Store floating-point input as a double, not an integer-shaped value.
164 * @tparam Number Floating-point source type.
165 * @param[in] value Number converted to double; this constructor does not check finiteness.
166 */
167 template <typename Number,
168 typename = std::enable_if_t<std::is_floating_point_v<Number>>,
169 typename = void>
170 Value(Number value) : Value() {
171 node_->kind = Node::Kind::Real;
172 node_->real_number = static_cast<double>(value);
173 }
174
175 /**
176 * @brief Recursively detach a copy so later mutation does not alias the source.
177 * @param[in] other Accessible source value, not a moved-from handle.
178 */
179 Value(const Value &other) : node_(clone(other.node_)) {}
180 /** @brief Transfer node ownership; only destruction/reassignment is assumed for the source. */
181 Value(Value &&) noexcept = default;
182 /**
183 * @brief Deep-copy and rebind this handle without modifying any former parent slot.
184 * @param[in] other Source value; self-assignment is permitted.
185 * @return This handle after assignment.
186 */
187 Value &operator=(const Value &other) {
188 if (this != &other)
189 node_ = clone(other.node_);
190 return *this;
191 }
192 /**
193 * @brief Move/rebind ownership without recursively cloning nodes.
194 * @return This handle; the moved-from source must be reassigned before inspection.
195 */
196 Value &operator=(Value &&) noexcept = default;
197
198 /** @brief Make an empty object. @return Independently owned object value. */
199 static Value object() {
200 Value value;
201 value.node_->kind = Node::Kind::Object;
202 return value;
203 }
204 /**
205 * @brief Build an object by cloning each supplied member value.
206 * @param[in] fields Named values; later repeated keys replace earlier members.
207 * @return Object in map key order rather than initializer/source order.
208 */
209 static Value object(std::initializer_list<Field> fields) {
210 Value value = object();
211 for (const auto &field : fields)
212 value.set(field.first, field.second);
213 return value;
214 }
215 /** @brief Make an empty array. @return Independently owned array value. */
216 static Value array() {
217 Value value;
218 value.node_->kind = Node::Kind::Array;
219 return value;
220 }
221 /**
222 * @brief Build an ordered array by cloning each supplied value.
223 * @param[in] values Elements in their desired order.
224 * @return Independently owned array value.
225 */
226 static Value array(std::initializer_list<Value> values) {
227 Value value = array();
228 for (const auto &item : values)
229 value.push_back(item);
230 return value;
231 }
232
233 /**
234 * @brief Copy a byte range and delegate parsing to the string overload.
235 * @tparam Iterator Iterator type accepted by std::string's range constructor.
236 * @param[in] first Beginning of the input range.
237 * @param[in] last One-past-end iterator.
238 * @return Tree detached from OpenCV's temporary storage.
239 * @throws exception If normalization or OpenCV input processing fails.
240 */
241 template <typename Iterator>
242 static Value parse(Iterator first, Iterator last) {
243 return parse(std::string(first, last));
244 }
245 /**
246 * @brief Parse terminated input; use a range/std::string for an explicit extent.
247 * @param[in] input Terminated bytes; nullptr selects an empty input string.
248 * @return Parsed tree, independent of the input buffer.
249 * @throws exception If the selected input cannot be read.
250 */
251 static Value parse(const char *input) {
252 return parse(std::string(input ? input : ""));
253 }
254 /**
255 * @brief Normalize compatibility tokens, parse with OpenCV and detach the tree.
256 * @param[in] input JSON input whose original bytes remain unchanged.
257 * @return Independently owned tree with restored bool/null/integer categories.
258 * @throws exception For rejected sentinels/escapes, conversion or OpenCV parse errors.
259 * @note cv::Exception is translated at this boundary so callers can use the
260 * adapter's error type without depending on OpenCV's parser diagnostics API.
261 */
262 static Value parse(const std::string &input) {
263 const std::string normalized = normalize_for_opencv(input);
264 try {
265 cv::FileStorage storage(normalized, cv::FileStorage::READ |
266 cv::FileStorage::MEMORY |
267 cv::FileStorage::FORMAT_JSON);
268 if (!storage.isOpened())
269 throw exception("OpenCV FileStorage could not open JSON input");
270 return from_node(storage.root());
271 } catch (const cv::Exception &error) {
272 throw exception(std::string("invalid OpenCV JSON: ") + error.what());
273 }
274 }
275
276 /** @brief Inspect the null tag. @return True only for a null node. */
277 bool is_null() const { return node_->kind == Node::Kind::Null; }
278 /** @brief Inspect the object tag. @return True only for an object node. */
279 bool is_object() const { return node_->kind == Node::Kind::Object; }
280 /** @brief Inspect the array tag. @return True only for an array node. */
281 bool is_array() const { return node_->kind == Node::Kind::Array; }
282 /** @brief Inspect the string tag. @return True only for a string node. */
283 bool is_string() const { return node_->kind == Node::Kind::String; }
284 /** @brief Test all three numeric categories without treating bool as numeric. @return Numeric tag status. */
285 bool is_number() const {
286 return node_->kind == Node::Kind::Signed ||
287 node_->kind == Node::Kind::Unsigned ||
288 node_->kind == Node::Kind::Real;
289 }
290 /** @brief Test signed/unsigned storage without accepting a real such as 1.0. @return Integer tag status. */
291 bool is_number_integer() const {
292 return node_->kind == Node::Kind::Signed ||
294 }
295 /** @brief Inspect unsigned storage rather than testing a number's sign. @return Unsigned tag status. */
296 bool is_number_unsigned() const {
297 return node_->kind == Node::Kind::Unsigned;
298 }
299 /**
300 * @brief Check member presence without interpreting a null value as missing.
301 * @param[in] key Non-null terminated member name.
302 * @return True for an existing object member; false for nonobjects/missing keys.
303 */
304 bool contains(const char *key) const {
305 return is_object() && node_->object.find(key) != node_->object.end();
306 }
307 /**
308 * @brief Check a member name through the C-string lookup interface.
309 * @param[in] key Name; an embedded NUL ends the portion used for lookup.
310 * @return Whether the object contains the selected name.
311 */
312 bool contains(const std::string &key) const { return contains(key.c_str()); }
313 /**
314 * @brief Count container entries, not string bytes or scalar payload size.
315 * @return Array length, object member count, or zero for a scalar/null.
316 */
317 size_t size() const {
318 return is_array() ? node_->array.size()
319 : is_object() ? node_->object.size()
320 : 0;
321 }
322
323 /**
324 * @brief Look up a shared child handle, using null for a missing member.
325 * @param[in] key Non-null terminated name.
326 * @return Handle initially sharing the child, or a fresh null value if absent.
327 * @throws exception If this value is not an object; lookup does not insert.
328 */
329 Value operator[](const char *key) const { return lookup(key, false); }
330 /**
331 * @brief Perform optional lookup through the terminated-name overload.
332 * @param[in] key Name; lookup stops at its first embedded NUL.
333 * @return Shared child handle or a fresh null for a missing member.
334 * @throws exception If this value is not an object.
335 */
336 Value operator[](const std::string &key) const {
337 return lookup(key.c_str(), false);
338 }
339 /**
340 * @brief Require an object member instead of substituting null.
341 * @param[in] key Non-null terminated member name.
342 * @return Handle initially sharing the selected child node.
343 * @throws exception For a nonobject or missing key.
344 */
345 Value at(const char *key) const { return lookup(key, true); }
346 /**
347 * @brief Require a member through the terminated-name interface.
348 * @param[in] key Name; an embedded NUL terminates lookup.
349 * @return Shared child handle.
350 * @throws exception For a nonobject or missing key.
351 */
352 Value at(const std::string &key) const { return at(key.c_str()); }
353 /**
354 * @brief Check signed array indices before conversion to an unsigned extent.
355 * @param[in] index Zero-based array position.
356 * @return Shared child handle.
357 * @throws exception For a negative/out-of-range index or nonarray value.
358 */
359 Value operator[](int index) const { return at(index); }
360 /**
361 * @brief Select an array element with the same bounds policy as at().
362 * @param[in] index Zero-based array position.
363 * @return Shared child handle.
364 * @throws exception For a nonarray or out-of-range position.
365 */
366 Value operator[](size_t index) const { return at(index); }
367 /**
368 * @brief Reject a negative position before any size_t cast can wrap it.
369 * @param[in] index Signed zero-based array position.
370 * @return Shared child handle.
371 * @throws exception For invalid array access.
372 */
373 Value at(int index) const {
374 if (index < 0)
375 throw exception("JSON array index out of range");
376 return at(static_cast<size_t>(index));
377 }
378 /**
379 * @brief Check both the array kind and its actual vector extent.
380 * @param[in] index Zero-based array position.
381 * @return Handle sharing the selected node, not a recursive copy.
382 * @throws exception For a nonarray or out-of-range position.
383 */
384 Value at(size_t index) const {
385 if (!is_array() || index >= node_->array.size())
386 throw exception("JSON array index out of range");
387 return Value(node_->array[index]);
388 }
389
390 /**
391 * @brief Convert explicitly while preserving the distinction between types.
392 * @tparam Type Value, string, bool, arithmetic type, std::array or std::vector;
393 * container elements are converted recursively using their value_type.
394 * @return Converted value; requesting Value makes a deep copy.
395 * @throws exception For incompatible tags, nonfinite/out-of-range numeric
396 * conversion or a fixed-size array whose length does not match.
397 * @note Integer targets reject real-tagged inputs even if mathematically
398 * integral. Floating conversions use double and do not promise integer precision.
399 * Unsupported target types produce a compile-time error, not a runtime fallback.
400 */
401 template <typename Type> Type get() const {
402 if constexpr (std::is_same_v<Type, Value>)
403 return *this;
404 else if constexpr (std::is_same_v<Type, std::string>) {
405 if (!is_string())
406 throw exception("JSON value is not a string");
407 return node_->string;
408 } else if constexpr (std::is_same_v<Type, bool>) {
409 if (node_->kind != Node::Kind::Bool)
410 throw exception("JSON value is not a boolean");
411 return node_->boolean;
412 } else if constexpr (std::is_floating_point_v<Type>) {
413 if (!is_number())
414 throw exception("JSON value is not numeric");
415 const double number = node_->kind == Node::Kind::Real ? node_->real_number
416 : node_->kind == Node::Kind::Signed
417 ? static_cast<double>(node_->signed_number)
418 : static_cast<double>(node_->unsigned_number);
419 if (!std::isfinite(number) ||
420 number < -std::numeric_limits<Type>::max() ||
421 number > std::numeric_limits<Type>::max())
422 throw exception("JSON number is out of range");
423 return static_cast<Type>(number);
424 } else if constexpr (std::is_integral_v<Type> && std::is_signed_v<Type>) {
425 if (!is_number_integer())
426 throw exception("JSON value is not an integer");
427 const long double number =
429 ? static_cast<long double>(node_->signed_number)
430 : static_cast<long double>(node_->unsigned_number);
431 if (number < std::numeric_limits<Type>::min() ||
432 number > std::numeric_limits<Type>::max())
433 throw exception("JSON integer is out of range");
434 return static_cast<Type>(number);
435 } else if constexpr (std::is_integral_v<Type> && std::is_unsigned_v<Type>) {
436 if (!is_number_integer())
437 throw exception("JSON value is not an integer");
438 const long double number =
440 ? static_cast<long double>(node_->signed_number)
441 : static_cast<long double>(node_->unsigned_number);
442 if (number < 0 || number > std::numeric_limits<Type>::max())
443 throw exception("JSON integer is out of range");
444 return static_cast<Type>(number);
445 } else if constexpr (is_std_array<Type>::value) {
446 if (!is_array() || size() != std::tuple_size_v<Type>)
447 throw exception("JSON array has unexpected length");
448 Type result{};
449 for (size_t index = 0; index < result.size(); ++index)
450 result[index] = at(index).template get<typename Type::value_type>();
451 return result;
452 } else if constexpr (is_std_vector<Type>::value) {
453 if (!is_array())
454 throw exception("JSON value is not an array");
455 Type result;
456 result.reserve(size());
457 for (size_t index = 0; index < size(); ++index)
458 result.push_back(at(index).template get<typename Type::value_type>());
459 return result;
460 } else
461 static_assert(!sizeof(Type), "unsupported JSON conversion type");
462 }
463
464 /**
465 * @brief Use a default only for absence, never to hide an invalid present value.
466 * @tparam Type Conversion/default type supported by get().
467 * @param[in] key Non-null terminated member name.
468 * @param[in] fallback Result when no member exists (including on a nonobject).
469 * @return Converted member or fallback.
470 * @throws exception If a present member cannot be converted to Type.
471 */
472 template <typename Type> Type value(const char *key, Type fallback) const {
473 return contains(key) ? at(key).template get<Type>() : std::move(fallback);
474 }
475 /**
476 * @brief Provide a string-valued default rather than returning a borrowed pointer.
477 * @param[in] key Non-null terminated member name.
478 * @param[in] fallback Non-null terminated default string.
479 * @return Owned member/default string.
480 * @throws exception If a present member is not a string.
481 */
482 std::string value(const char *key, const char *fallback) const {
483 return contains(key) ? at(key).get<std::string>() : std::string(fallback);
484 }
485
486 /**
487 * @brief Snapshot object names and shared child handles in map order.
488 * @return Newly allocated member vector; child nodes initially remain shared.
489 * @throws exception If this value is not an object.
490 * @note The vector is detached from later map insertion/removal, but a returned
491 * child's in-place mutation can still affect the source node it shares.
492 */
493 std::vector<std::pair<std::string, Value>> items() const {
494 if (!is_object())
495 throw exception("JSON value is not an object");
496 std::vector<std::pair<std::string, Value>> result;
497 result.reserve(node_->object.size());
498 for (const auto &item : node_->object)
499 result.emplace_back(item.first, Value(item.second));
500 return result;
501 }
502
503 /**
504 * @brief Clone a member value, replace any matching key and select object kind.
505 * @param[in] key Owned member name copied into the map.
506 * @param[in] value Source value cloned rather than linked into this tree.
507 * @throws exception If a directly supplied string uses a reserved bridge marker.
508 * @note Existing other-kind payload storage is not cleared by this operation.
509 */
510 void set(const std::string &key, const Value &value) {
512 node_->object[key] = clone(value.node_);
514 }
515 /**
516 * @brief Construct a supported native value before applying member insertion policy.
517 * @tparam Type Type accepted by a Value constructor.
518 * @param[in] key Member name.
519 * @param[in] value Native value to convert and clone.
520 * @throws exception Under the same reserved-string policy as set().
521 */
522 template <typename Type> void set(const std::string &key, Type value) {
523 set(key, Value(value));
524 }
525 /**
526 * @brief Clone an element, append it in order and select array kind.
527 * @param[in] value Source element, whose later mutation must not alter this copy.
528 * @throws exception If a directly supplied string uses the reserved namespace.
529 * @note Other-kind payload storage is retained but no longer selected by kind.
530 */
531 void push_back(const Value &value) {
533 node_->array.push_back(clone(value.node_));
534 node_->kind = Node::Kind::Array;
535 }
536 /**
537 * @brief Construct a native value before applying array insertion policy.
538 * @tparam Type Type accepted by a Value constructor.
539 * @param[in] value Native element to convert and clone.
540 * @throws exception Under the same reserved-string policy as push_back().
541 */
542 template <typename Type> void push_back(Type value) {
544 }
545 /**
546 * @brief Shallow-merge object members while deep-copying each replacement value.
547 * @param[in] other Object whose keys replace matching keys in this value.
548 * @throws exception If other is not an object or an inserted string is reserved.
549 * @note This merges one member level, not nested objects recursively.
550 */
551 void update(const Value &other) {
552 for (const auto &item : other.items())
553 set(item.first, item.second);
554 }
555
556 /**
557 * @brief Serialize with OpenCV and restore native JSON scalar tokens.
558 * @param[in] indent Negative selects compact output; nonnegative keeps OpenCV
559 * formatting. Its numeric magnitude is not an indentation-width setting.
560 * @return Owned serialized text.
561 * @throws exception For adapter-detected writer or reserved-string failures.
562 * @note The unnamed character/bool arguments are ignored compatibility slots.
563 * OpenCV writer exceptions may propagate as cv::Exception rather than exception.
564 */
565 std::string dump(int indent = -1, char = ' ', bool = false) const {
566 return write_opencv(*this, indent);
567 }
568 /**
569 * @brief Produce compact map-ordered output without FileStorage formatting.
570 * @return Owned text with non-ASCII strings expressed as Unicode escapes.
571 * @throws exception For malformed/truncated UTF-8 sequence shapes or failed number formatting.
572 * @pre Use finite real values and valid Unicode strings when strict JSON is needed.
573 * @note This is deterministic map-key ordering, not RFC 8785 canonicalization.
574 * UTF-8 checks cover lead/continuation shape and truncation, not every scalar
575 * validity rule; real-tagged integral spellings keep a .0 suffix for round trips.
576 */
577 std::string dump_sorted() const {
578 std::string output;
579 const auto append_string = [&output](const std::string &text) {
580 static constexpr char hex[] = "0123456789abcdef";
581 output.push_back('"');
582 for (size_t index = 0; index < text.size();) {
583 const unsigned char first = static_cast<unsigned char>(text[index]);
584 if (first == '"' || first == '\\') {
585 output.push_back('\\');
586 output.push_back(static_cast<char>(first));
587 ++index;
588 } else if (first < 0x20) {
589 const char *escape = first == '\b' ? "\\b"
590 : first == '\f' ? "\\f"
591 : first == '\n' ? "\\n"
592 : first == '\r' ? "\\r"
593 : first == '\t' ? "\\t"
594 : nullptr;
595 if (escape)
596 output += escape;
597 else {
598 output += "\\u00";
599 output.push_back(hex[first >> 4]);
600 output.push_back(hex[first & 0x0f]);
601 }
602 ++index;
603 } else if (first < 0x80) {
604 output.push_back(static_cast<char>(first));
605 ++index;
606 } else {
607 uint32_t codepoint = 0;
608 size_t count = 0;
609 if ((first & 0xe0) == 0xc0) {
610 codepoint = first & 0x1f;
611 count = 2;
612 } else if ((first & 0xf0) == 0xe0) {
613 codepoint = first & 0x0f;
614 count = 3;
615 } else if ((first & 0xf8) == 0xf0) {
616 codepoint = first & 0x07;
617 count = 4;
618 } else
619 throw exception("invalid UTF-8 in JSON string");
620 if (index + count > text.size())
621 throw exception("truncated UTF-8 in JSON string");
622 for (size_t offset = 1; offset < count; ++offset) {
623 const unsigned char next =
624 static_cast<unsigned char>(text[index + offset]);
625 if ((next & 0xc0) != 0x80)
626 throw exception("invalid UTF-8 in JSON string");
627 codepoint = (codepoint << 6) | (next & 0x3f);
628 }
629 const auto append_hex = [&output](uint16_t unit) {
630 output += "\\u";
631 output.push_back(hex[(unit >> 12) & 0xf]);
632 output.push_back(hex[(unit >> 8) & 0xf]);
633 output.push_back(hex[(unit >> 4) & 0xf]);
634 output.push_back(hex[unit & 0xf]);
635 };
636 /* Supplementary scalars need UTF-16 pairs because JSON escapes encode 16-bit units. */
637 if (codepoint <= 0xffff)
638 append_hex(static_cast<uint16_t>(codepoint));
639 else {
640 codepoint -= 0x10000;
641 append_hex(static_cast<uint16_t>(0xd800 + (codepoint >> 10)));
642 append_hex(static_cast<uint16_t>(0xdc00 + (codepoint & 0x3ff)));
643 }
644 index += count;
645 }
646 }
647 output.push_back('"');
648 };
649 const auto append = [&](auto &&self,
650 const std::shared_ptr<Node> &node) -> void {
651 switch (node->kind) {
652 case Node::Kind::Null:
653 output += "null";
654 break;
655 case Node::Kind::Bool:
656 output += node->boolean ? "true" : "false";
657 break;
659 output += std::to_string(node->signed_number);
660 break;
662 output += std::to_string(node->unsigned_number);
663 break;
664 case Node::Kind::Real: {
665 char buffer[64];
666 const auto result =
667 std::to_chars(buffer, buffer + sizeof(buffer), node->real_number,
668 std::chars_format::general);
669 if (result.ec != std::errc{})
670 throw exception("cannot format JSON number");
671 const std::string formatted(buffer, result.ptr);
672 output += formatted;
673 /* Preserve the Real category instead of reparsing an integer-shaped spelling as an integer. */
674 if (formatted.find_first_of(".eE") == std::string::npos)
675 output += ".0";
676 break;
677 }
679 append_string(node->string);
680 break;
682 output.push_back('[');
683 for (size_t index = 0; index < node->array.size(); ++index) {
684 if (index)
685 output.push_back(',');
686 self(self, node->array[index]);
687 }
688 output.push_back(']');
689 break;
690 case Node::Kind::Object: {
691 output.push_back('{');
692 bool first = true;
693 for (const auto &item : node->object) {
694 if (!first)
695 output.push_back(',');
696 first = false;
697 append_string(item.first);
698 output.push_back(':');
699 self(self, item.second);
700 }
701 output.push_back('}');
702 break;
703 }
704 }
705 };
706 append(append, node_);
707 return output;
708 }
709
710 /**
711 * @brief Compare tree contents rather than shared-pointer identity.
712 * @param[in] left First value.
713 * @param[in] right Second value.
714 * @return Structural equality with numeric cross-category comparison.
715 * @note Real/integer comparisons use native long double precision, not an
716 * arbitrary-precision decimal equivalence relation.
717 */
718 friend bool operator==(const Value &left, const Value &right) {
719 return equal_nodes(left.node_, right.node_);
720 }
721 /**
722 * @brief Negate structural equality using the same numeric policy.
723 * @param[in] left First value.
724 * @param[in] right Second value.
725 * @return True exactly when equality returns false.
726 */
727 friend bool operator!=(const Value &left, const Value &right) {
728 return !(left == right);
729 }
730 /**
731 * @brief Order string values only, rather than inventing an ordering across JSON kinds.
732 * @param[in] left First string value.
733 * @param[in] right Second string value.
734 * @return Lexicographic std::string comparison result.
735 * @throws exception If either operand is not a string.
736 */
737 friend bool operator<(const Value &left, const Value &right) {
738 if (!left.is_string() || !right.is_string())
739 throw exception("JSON values are not strings");
740 return left.node_->string < right.node_->string;
741 }
742
743private:
744 /** @brief False primary trait; unsupported conversions must not masquerade as arrays.
745 * @tparam Type Candidate conversion type.
746 */
747 template <typename Type> struct is_std_array : std::false_type {};
748 /** @brief Recognize fixed arrays so get() can require their exact length.
749 * @tparam Type Array element type.
750 * @tparam Count Required element count.
751 */
752 template <typename Type, size_t Count>
753 struct is_std_array<std::array<Type, Count>> : std::true_type {};
754 /** @brief False primary trait for dynamic-vector conversion detection.
755 * @tparam Type Candidate conversion type.
756 */
757 template <typename Type> struct is_std_vector : std::false_type {};
758 /** @brief Recognize vectors without fixing their element allocator.
759 * @tparam Type Element type.
760 * @tparam Allocator Vector allocator type.
761 */
762 template <typename Type, typename Allocator>
763 struct is_std_vector<std::vector<Type, Allocator>> : std::true_type {};
764 /**
765 * @brief Construct a shared child view without invoking public deep-copy semantics.
766 * @param[in] node Existing child ownership transferred into this handle.
767 */
768 explicit Value(std::shared_ptr<Node> node) : node_(std::move(node)) {}
769 std::shared_ptr<Node> node_; /**< Current owned/shared node; may be empty after a move. */
770
771 /**
772 * @brief Recursively detach a FileNode and restore compatibility sentinel types.
773 * @param[in] source OpenCV node valid for the duration of conversion.
774 * @return Independent native tree, with later duplicate map keys replacing earlier ones.
775 * @throws exception For unsupported nodes or invalid/out-of-range integer markers.
776 */
777 static Value from_node(const cv::FileNode &source);
778 /**
779 * @brief Adapt tokens outside strings and decode string escapes for FileStorage.
780 * @param[in] input Original bytes, left unchanged.
781 * @return OpenCV-readable text with typed scalar markers.
782 * @throws exception For reserved raw marker text or invalid Unicode/string escapes.
783 * @note This is a compatibility pass, not a complete JSON grammar validator;
784 * OpenCV processes the resulting document structure.
785 */
786 static std::string normalize_for_opencv(const std::string &input);
787 /**
788 * @brief Write through FileStorage, restore marked scalars and optionally compact.
789 * @param[in] value Tree to serialize.
790 * @param[in] indent Negative removes insignificant whitespace; otherwise OpenCV formats.
791 * @return Owned output text.
792 * @throws exception For adapter-detected writer/marker failures.
793 */
794 static std::string write_opencv(const Value &value, int indent);
795 /**
796 * @brief Recursively emit containers and protect types unsupported by FileStorage.
797 * @param[in,out] storage Active OpenCV JSON writer.
798 * @param[in] key Name used when has_key is true.
799 * @param[in] value Current value to emit.
800 * @param[in] has_key Distinguishes named object members from anonymous array elements.
801 * @throws exception For reserved string payloads.
802 */
803 static void write_node(cv::FileStorage &storage, const std::string &key,
804 const Value &value, bool has_key);
805 /**
806 * @brief Reject the marker namespace in a directly supplied string value.
807 * @param[in] value Value checked only if its active kind is String.
808 * @throws exception If that string contains the reserved prefix.
809 * @note This helper is not a recursive tree or object-key validator.
810 */
811 static void require_unreserved(const Value &value);
812 /**
813 * @brief Clone child nodes recursively to implement ordinary value-copy semantics.
814 * @param[in] source Non-null source node and its accessible descendants.
815 * @return Independent node tree, not shared child pointers from source.
816 */
817 static std::shared_ptr<Node> clone(const std::shared_ptr<Node> &source);
818 /**
819 * @brief Compare active payloads and recursively compare container contents.
820 * @param[in] left Non-null first node.
821 * @param[in] right Non-null second node.
822 * @return Equality under the adapter's numeric/structural comparison rules.
823 */
824 static bool equal_nodes(const std::shared_ptr<Node> &left,
825 const std::shared_ptr<Node> &right);
826 /**
827 * @brief Centralize required/optional member policy without copying a found child.
828 * @param[in] key Non-null terminated member name.
829 * @param[in] required Whether absence is an error instead of a fresh null value.
830 * @return Shared child view, or fresh null for an optional missing member.
831 * @throws exception For a nonobject or a missing required member.
832 */
833 Value lookup(const char *key, bool required) const;
834};
835
836inline std::shared_ptr<Node> Value::clone(const std::shared_ptr<Node> &source) {
837 auto result = std::make_shared<Node>(*source);
838 /* Copy scalar/string storage first, then replace copied child pointers with detached trees. */
839 result->array.clear();
840 result->object.clear();
841 for (const auto &item : source->array)
842 result->array.push_back(clone(item));
843 for (const auto &item : source->object)
844 result->object.emplace(item.first, clone(item.second));
845 return result;
846}
847
848inline bool Value::equal_nodes(const std::shared_ptr<Node> &left,
849 const std::shared_ptr<Node> &right) {
850 const auto integer = [](Node::Kind kind) {
851 return kind == Node::Kind::Signed || kind == Node::Kind::Unsigned;
852 };
853 const auto numeric = [&](Node::Kind kind) {
854 return integer(kind) || kind == Node::Kind::Real;
855 };
856 if (numeric(left->kind) && numeric(right->kind)) {
857 /* Negative signed values must never wrap into an apparently equal unsigned magnitude. */
858 if (left->kind == Node::Kind::Signed && right->kind == Node::Kind::Unsigned)
859 return left->signed_number >= 0 &&
860 static_cast<uint64_t>(left->signed_number) ==
861 right->unsigned_number;
862 if (left->kind == Node::Kind::Unsigned && right->kind == Node::Kind::Signed)
863 return right->signed_number >= 0 &&
864 left->unsigned_number ==
865 static_cast<uint64_t>(right->signed_number);
866 const long double left_number =
867 left->kind == Node::Kind::Signed
868 ? static_cast<long double>(left->signed_number)
869 : left->kind == Node::Kind::Unsigned
870 ? static_cast<long double>(left->unsigned_number)
871 : static_cast<long double>(left->real_number);
872 const long double right_number =
873 right->kind == Node::Kind::Signed
874 ? static_cast<long double>(right->signed_number)
875 : right->kind == Node::Kind::Unsigned
876 ? static_cast<long double>(right->unsigned_number)
877 : static_cast<long double>(right->real_number);
878 return left_number == right_number;
879 }
880 if (left->kind != right->kind)
881 return false;
882 switch (left->kind) {
883 case Node::Kind::Null:
884 return true;
885 case Node::Kind::Bool:
886 return left->boolean == right->boolean;
888 return left->signed_number == right->signed_number;
890 return left->unsigned_number == right->unsigned_number;
891 case Node::Kind::Real:
892 return left->real_number == right->real_number;
894 return left->string == right->string;
896 if (left->array.size() != right->array.size())
897 return false;
898 for (size_t i = 0; i < left->array.size(); ++i)
899 if (!equal_nodes(left->array[i], right->array[i]))
900 return false;
901 return true;
903 if (left->object.size() != right->object.size())
904 return false;
905 for (const auto &item : left->object) {
906 auto found = right->object.find(item.first);
907 if (found == right->object.end() ||
908 !equal_nodes(item.second, found->second))
909 return false;
910 }
911 return true;
912 }
913 return false;
914}
915
916inline Value Value::lookup(const char *key, bool required) const {
917 if (!is_object())
918 throw exception("JSON value is not an object");
919 auto found = node_->object.find(key);
920 if (found == node_->object.end()) {
921 if (required)
922 throw exception(std::string("missing JSON field: ") + key);
923 return Value();
924 }
925 return Value(found->second);
926}
927
929 if (value.is_string() &&
930 value.node_->string.find("__USHER_OPENCV_JSON_") != std::string::npos)
931 throw exception("JSON string uses a reserved OpenCV bridge token");
932}
933
934inline std::string Value::normalize_for_opencv(const std::string &input) {
935 /* Raw marker rejection reserves an internal transport namespace, not a user data format. */
936 if (input.find("__USHER_OPENCV_JSON_") != std::string::npos)
937 throw exception("JSON input uses a reserved OpenCV bridge token");
938 std::string output;
939 output.reserve(input.size() + 32);
940 bool in_string = false;
941 const auto hex_value = [](char character) -> int {
942 if (character >= '0' && character <= '9')
943 return character - '0';
944 if (character >= 'a' && character <= 'f')
945 return character - 'a' + 10;
946 if (character >= 'A' && character <= 'F')
947 return character - 'A' + 10;
948 return -1;
949 };
950 const auto unicode_escape = [&](size_t offset,
951 uint32_t *codepoint) -> size_t {
952 if (offset + 4 > input.size())
953 throw exception("truncated JSON Unicode escape");
954 uint32_t value = 0;
955 for (size_t digit = 0; digit < 4; ++digit) {
956 const int nibble = hex_value(input[offset + digit]);
957 if (nibble < 0)
958 throw exception("invalid JSON Unicode escape");
960 }
961 *codepoint = value;
962 return offset + 4;
963 };
964 const auto append_utf8 = [&output](uint32_t codepoint) {
965 if (codepoint <= 0x7f)
966 output.push_back(static_cast<char>(codepoint));
967 else if (codepoint <= 0x7ff) {
968 output.push_back(static_cast<char>(0xc0 | (codepoint >> 6)));
969 output.push_back(static_cast<char>(0x80 | (codepoint & 0x3f)));
970 } else if (codepoint <= 0xffff) {
971 output.push_back(static_cast<char>(0xe0 | (codepoint >> 12)));
972 output.push_back(static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f)));
973 output.push_back(static_cast<char>(0x80 | (codepoint & 0x3f)));
974 } else {
975 output.push_back(static_cast<char>(0xf0 | (codepoint >> 18)));
976 output.push_back(static_cast<char>(0x80 | ((codepoint >> 12) & 0x3f)));
977 output.push_back(static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f)));
978 output.push_back(static_cast<char>(0x80 | (codepoint & 0x3f)));
979 }
980 };
981 for (size_t i = 0; i < input.size();) {
982 const char c = input[i];
983 if (in_string) {
984 if (c == '"') {
985 in_string = false;
986 output.push_back(c);
987 ++i;
988 continue;
989 }
990 if (c == '\\') {
991 if (i + 1 >= input.size())
992 throw exception("truncated JSON string escape");
993 const char escaped = input[i + 1];
994 if (escaped == '/') {
995 output.push_back('/');
996 i += 2;
997 continue;
998 }
999 if (escaped == 'u') {
1000 uint32_t codepoint = 0;
1001 size_t next = unicode_escape(i + 2, &codepoint);
1002 /* Combine UTF-16 escapes before UTF-8 encoding; isolated halves are not scalars. */
1003 if (codepoint >= 0xd800 && codepoint <= 0xdbff) {
1004 if (next + 6 > input.size() || input[next] != '\\' ||
1005 input[next + 1] != 'u')
1006 throw exception("unpaired JSON high surrogate");
1007 uint32_t low = 0;
1008 next = unicode_escape(next + 2, &low);
1009 if (low < 0xdc00 || low > 0xdfff)
1010 throw exception("invalid JSON surrogate pair");
1011 codepoint = 0x10000 + ((codepoint - 0xd800) << 10) + (low - 0xdc00);
1012 } else if (codepoint >= 0xdc00 && codepoint <= 0xdfff) {
1013 throw exception("unpaired JSON low surrogate");
1014 }
1015 append_utf8(codepoint);
1016 i = next;
1017 continue;
1018 }
1019 if (std::string_view("\\\"nrtbf").find(escaped) ==
1020 std::string_view::npos)
1021 throw exception("invalid JSON string escape");
1022 output.push_back(c);
1023 output.push_back(escaped);
1024 i += 2;
1025 continue;
1026 }
1027 output.push_back(c);
1028 ++i;
1029 continue;
1030 }
1031 if (c == '"') {
1032 in_string = true;
1033 output.push_back(c);
1034 ++i;
1035 continue;
1036 }
1037 const auto token = [&](const char *text, const char *replacement) {
1038 const size_t length = std::char_traits<char>::length(text);
1039 const bool left =
1040 i == 0 || !(std::isalnum(static_cast<unsigned char>(input[i - 1])) ||
1041 input[i - 1] == '_');
1042 const size_t end = i + length;
1043 const bool right =
1044 end >= input.size() ||
1045 !(std::isalnum(static_cast<unsigned char>(input[end])) ||
1046 input[end] == '_');
1047 if (!left || !right || input.compare(i, length, text) != 0)
1048 return false;
1049 output += "\"";
1050 output += replacement;
1051 output += "\"";
1052 i = end;
1053 return true;
1054 };
1055 /* Only outside-string tokens are rewritten; quoted ordinary words keep their meaning. */
1056 if (token("null", "__USHER_OPENCV_JSON_NULL__") ||
1057 token("true", "__USHER_OPENCV_JSON_TRUE__") ||
1058 token("false", "__USHER_OPENCV_JSON_FALSE__"))
1059 continue;
1060 if (c == '-' || std::isdigit(static_cast<unsigned char>(c))) {
1061 size_t end = i;
1062 while (end < input.size() &&
1063 (std::isdigit(static_cast<unsigned char>(input[end])) ||
1064 input[end] == '-' || input[end] == '+' || input[end] == '.' ||
1065 input[end] == 'e' || input[end] == 'E'))
1066 ++end;
1067 const std::string number = input.substr(i, end - i);
1068 if (number.find_first_of(".eE") == std::string::npos) {
1069 /* Carry integer digits as text so FileStorage cannot narrow them before from_chars. */
1070 const char *prefix = !number.empty() && number[0] == '-'
1071 ? "\"__USHER_OPENCV_JSON_INT__"
1072 : "\"__USHER_OPENCV_JSON_UINT__";
1073 output += prefix;
1074 output += number;
1075 output += "__\"";
1076 i = end;
1077 continue;
1078 }
1079 output += number;
1080 i = end;
1081 continue;
1082 }
1083 output.push_back(c);
1084 ++i;
1085 }
1086 return output;
1087}
1088
1089inline Value Value::from_node(const cv::FileNode &source) {
1090 if (source.isMap()) {
1091 Value result = object();
1092 for (auto iterator = source.begin(); iterator != source.end(); ++iterator) {
1093 const cv::FileNode child = *iterator;
1094 result.set(child.name(), from_node(child));
1095 }
1096 return result;
1097 }
1098 if (source.isSeq()) {
1099 Value result = array();
1100 for (auto iterator = source.begin(); iterator != source.end(); ++iterator)
1101 result.push_back(from_node(*iterator));
1102 return result;
1103 }
1104 if (source.isString()) {
1105 const std::string text = static_cast<std::string>(source);
1106 if (text == "__USHER_OPENCV_JSON_NULL__")
1107 return Value();
1108 if (text == "__USHER_OPENCV_JSON_TRUE__")
1109 return Value(true);
1110 if (text == "__USHER_OPENCV_JSON_FALSE__")
1111 return Value(false);
1112 const auto parse_integer = [&text](const char *prefix,
1113 bool is_unsigned) -> Value {
1114 const size_t prefix_length = std::char_traits<char>::length(prefix);
1115 if (text.compare(0, prefix_length, prefix) != 0 ||
1116 text.size() < prefix_length + 2 ||
1117 text.compare(text.size() - 2, 2, "__") != 0)
1118 return Value(text);
1119 const std::string digits =
1120 text.substr(prefix_length, text.size() - prefix_length - 2);
1121 /* Require full consumption as well as success; accepting a numeric prefix hides junk. */
1122 if (is_unsigned) {
1123 uint64_t number = 0;
1124 const auto result = std::from_chars(
1125 digits.data(), digits.data() + digits.size(), number);
1126 if (result.ec != std::errc{} ||
1127 result.ptr != digits.data() + digits.size())
1128 throw exception("invalid unsigned JSON integer");
1129 return Value(number);
1130 }
1131 int64_t number = 0;
1132 const auto result =
1133 std::from_chars(digits.data(), digits.data() + digits.size(), number);
1134 if (result.ec != std::errc{} ||
1135 result.ptr != digits.data() + digits.size())
1136 throw exception("invalid signed JSON integer");
1137 return Value(number);
1138 };
1139 if (text.compare(0, 26, "__USHER_OPENCV_JSON_UINT__") == 0)
1140 return parse_integer("__USHER_OPENCV_JSON_UINT__", true);
1141 if (text.compare(0, 25, "__USHER_OPENCV_JSON_INT__") == 0)
1142 return parse_integer("__USHER_OPENCV_JSON_INT__", false);
1143 return Value(text);
1144 }
1145 if (source.isInt())
1146 return Value(static_cast<int>(source));
1147 if (source.isReal())
1148 return Value(static_cast<double>(source));
1149 throw exception("unsupported OpenCV JSON value type");
1150}
1151
1152inline void Value::write_node(cv::FileStorage &storage, const std::string &key,
1153 const Value &value, bool has_key) {
1154 const auto write_key = [&] {
1155 if (has_key)
1156 storage << key;
1157 };
1158 switch (value.node_->kind) {
1159 case Node::Kind::Null:
1160 write_key();
1161 storage << "__USHER_OPENCV_JSON_NULL__";
1162 return;
1163 case Node::Kind::Bool:
1164 write_key();
1165 storage << (value.node_->boolean ? "__USHER_OPENCV_JSON_TRUE__"
1166 : "__USHER_OPENCV_JSON_FALSE__");
1167 return;
1168 case Node::Kind::Signed:
1169 write_key();
1170 /* Mark both integer widths instead of depending on FileStorage's integer overload range. */
1171 storage << ("__USHER_OPENCV_JSON_INT__" +
1172 std::to_string(value.node_->signed_number) + "__");
1173 return;
1175 write_key();
1176 storage << ("__USHER_OPENCV_JSON_UINT__" +
1177 std::to_string(value.node_->unsigned_number) + "__");
1178 return;
1179 case Node::Kind::Real:
1180 write_key();
1181 storage << value.node_->real_number;
1182 return;
1183 case Node::Kind::String:
1185 write_key();
1186 storage << value.node_->string;
1187 return;
1188 case Node::Kind::Object:
1189 storage.startWriteStruct(has_key ? key : "", cv::FileNode::MAP);
1190 for (const auto &item : value.node_->object)
1191 write_node(storage, item.first, Value(item.second), true);
1192 storage.endWriteStruct();
1193 return;
1194 case Node::Kind::Array:
1195 storage.startWriteStruct(has_key ? key : "", cv::FileNode::SEQ);
1196 for (const auto &item : value.node_->array)
1197 write_node(storage, "", Value(item), false);
1198 storage.endWriteStruct();
1199 return;
1200 }
1201}
1202
1203inline std::string Value::write_opencv(const Value &value, int indent) {
1204 cv::FileStorage storage("", cv::FileStorage::WRITE | cv::FileStorage::MEMORY |
1205 cv::FileStorage::FORMAT_JSON);
1206 if (!storage.isOpened())
1207 throw exception("cannot open OpenCV JSON writer");
1208 if (value.is_object()) {
1209 for (const auto &item : value.node_->object)
1210 write_node(storage, item.first, Value(item.second), true);
1211 } else {
1212 write_node(storage, "", value, false);
1213 }
1214 std::string output = storage.releaseAndGetString();
1215 /* Restore markers after serialization, when OpenCV has finished quoting transport strings. */
1216 const auto replace_token = [&output](const std::string &marker,
1217 const std::string &replacement) {
1218 const std::string quoted = "\"" + marker + "\"";
1219 size_t position = 0;
1220 while ((position = output.find(quoted, position)) != std::string::npos) {
1221 output.replace(position, quoted.size(), replacement);
1222 position += replacement.size();
1223 }
1224 };
1225 replace_token("__USHER_OPENCV_JSON_NULL__", "null");
1226 replace_token("__USHER_OPENCV_JSON_TRUE__", "true");
1227 replace_token("__USHER_OPENCV_JSON_FALSE__", "false");
1228 const auto replace_integer = [&output](const char *prefix) {
1229 size_t position = 0;
1230 while ((position = output.find(prefix, position)) != std::string::npos) {
1231 const size_t start = position;
1232 const size_t digits = position + std::char_traits<char>::length(prefix);
1233 const size_t end = output.find("__\"", digits);
1234 if (end == std::string::npos)
1235 break;
1236 const size_t quoted_start = start - 1;
1237 output.replace(quoted_start, end + 3 - quoted_start,
1238 output.substr(digits, end - digits));
1239 position = quoted_start + 1;
1240 }
1241 };
1242 replace_integer("__USHER_OPENCV_JSON_INT__");
1243 replace_integer("__USHER_OPENCV_JSON_UINT__");
1244 if (indent >= 0)
1245 return output;
1246 std::string compact;
1247 compact.reserve(output.size());
1248 /* Whitespace inside quoted strings is data; track escaped quotes before removing trivia. */
1249 bool in_string = false, escaped = false;
1250 for (char character : output) {
1251 if (in_string) {
1252 compact.push_back(character);
1253 if (escaped)
1254 escaped = false;
1255 else if (character == '\\')
1256 escaped = true;
1257 else if (character == '"')
1258 in_string = false;
1259 } else if (character == '"') {
1260 in_string = true;
1261 compact.push_back(character);
1262 } else if (character != ' ' && character != '\t' && character != '\n' &&
1263 character != '\r') {
1264 compact.push_back(character);
1265 }
1266 }
1267 return compact;
1268}
1269
1270} // namespace usher_cv_json
1271
1272#endif
Adapter errors exposed independently of OpenCV's exception type.
Value at(int index) const
Reject a negative position before any size_t cast can wrap it.
std::vector< std::pair< std::string, Value > > items() const
Snapshot object names and shared child handles in map order.
Value(Value &&) noexcept=default
Transfer node ownership; only destruction/reassignment is assumed for the source.
static Value parse(Iterator first, Iterator last)
Copy a byte range and delegate parsing to the string overload.
Value & operator=(Value &&) noexcept=default
Move/rebind ownership without recursively cloning nodes.
Value(std::nullptr_t)
Construct null from the C++ nullptr tag.
Type get() const
Convert explicitly while preserving the distinction between types.
static void write_node(cv::FileStorage &storage, const std::string &key, const Value &value, bool has_key)
Recursively emit containers and protect types unsupported by FileStorage.
static Value object(std::initializer_list< Field > fields)
Build an object by cloning each supplied member value.
Value at(const std::string &key) const
Require a member through the terminated-name interface.
std::pair< std::string, Value > Field
One named value supplied to an object factory.
Value lookup(const char *key, bool required) const
Centralize required/optional member policy without copying a found child.
static Value array(std::initializer_list< Value > values)
Build an ordered array by cloning each supplied value.
void set(const std::string &key, Type value)
Construct a supported native value before applying member insertion policy.
Value at(size_t index) const
Check both the array kind and its actual vector extent.
Value(Number value)
Store floating-point input as a double, not an integer-shaped value.
Value(Number value)
Store native integral input in its signed or unsigned 64-bit category.
Value at(const char *key) const
Require an object member instead of substituting null.
friend bool operator!=(const Value &left, const Value &right)
Negate structural equality using the same numeric policy.
Value(bool value)
Construct a boolean without confusing it with an integral payload.
void update(const Value &other)
Shallow-merge object members while deep-copying each replacement value.
void push_back(const Value &value)
Clone an element, append it in order and select array kind.
bool is_array() const
Inspect the array tag.
void set(const std::string &key, const Value &value)
Clone a member value, replace any matching key and select object kind.
bool is_number_unsigned() const
Inspect unsigned storage rather than testing a number's sign.
Value(const std::string &value)
Own a complete byte string rather than borrowing external storage.
std::string dump_sorted() const
Produce compact map-ordered output without FileStorage formatting.
Value(const Value &other)
Recursively detach a copy so later mutation does not alias the source.
bool contains(const std::string &key) const
Check a member name through the C-string lookup interface.
static Value parse(const std::string &input)
Normalize compatibility tokens, parse with OpenCV and detach the tree.
Value operator[](const std::string &key) const
Perform optional lookup through the terminated-name overload.
bool is_string() const
Inspect the string tag.
std::shared_ptr< Node > node_
Value operator[](size_t index) const
Select an array element with the same bounds policy as at().
static bool equal_nodes(const std::shared_ptr< Node > &left, const std::shared_ptr< Node > &right)
Compare active payloads and recursively compare container contents.
static Value from_node(const cv::FileNode &source)
Recursively detach a FileNode and restore compatibility sentinel types.
static void require_unreserved(const Value &value)
Reject the marker namespace in a directly supplied string value.
size_t size() const
Count container entries, not string bytes or scalar payload size.
static std::string write_opencv(const Value &value, int indent)
Write through FileStorage, restore marked scalars and optionally compact.
Value(const char *value)
Copy a terminated string; a null pointer selects an empty string.
bool is_number() const
Test all three numeric categories without treating bool as numeric.
std::string dump(int indent=-1, char=' ', bool=false) const
Serialize with OpenCV and restore native JSON scalar tokens.
Type value(const char *key, Type fallback) const
Use a default only for absence, never to hide an invalid present value.
static Value array()
Make an empty array.
static Value parse(const char *input)
Parse terminated input; use a range/stdstring for an explicit extent.
friend bool operator==(const Value &left, const Value &right)
Compare tree contents rather than shared-pointer identity.
Value operator[](const char *key) const
Look up a shared child handle, using null for a missing member.
static std::shared_ptr< Node > clone(const std::shared_ptr< Node > &source)
Clone child nodes recursively to implement ordinary value-copy semantics.
Value operator[](int index) const
Check signed array indices before conversion to an unsigned extent.
void push_back(Type value)
Construct a native value before applying array insertion policy.
static Value object()
Make an empty object.
friend bool operator<(const Value &left, const Value &right)
Order string values only, rather than inventing an ordering across JSON kinds.
Value()
Allocate a fresh null node instead of using a shared mutable singleton.
Value(std::shared_ptr< Node > node)
Construct a shared child view without invoking public deep-copy semantics.
bool is_null() const
Inspect the null tag.
std::string value(const char *key, const char *fallback) const
Provide a string-valued default rather than returning a borrowed pointer.
bool contains(const char *key) const
Check member presence without interpreting a null value as missing.
static std::string normalize_for_opencv(const std::string &input)
Adapt tokens outside strings and decode string escapes for FileStorage.
bool is_object() const
Inspect the object tag.
bool is_number_integer() const
Test signed/unsigned storage without accepting a real such as 1.0.
static bool start(uint32_t session)
Admit a nonzero session and discard correlation from the previous one.
static pid_t child
uint8_t marker[LWIR_THERMAL_HEADER_BYTES+LWIR_THERMAL_CHUNK_CAPACITY]
Definition lwir_image.c:62
struct jpeg_error_mgr error
Definition lwir_image.c:60
OpenCV-backed JSON values and the internal tree supporting them.
static size_t count
Definition pose_log.c:79
static FILE * output
Definition pose_log.c:77
Heap-backed tagged storage independent of a FileStorage lifetime.
std::map< std::string, std::shared_ptr< Node > > object
Kind
Active payload category; boolean is distinct from integer storage.
std::vector< std::shared_ptr< Node > > array
False primary trait; unsupported conversions must not masquerade as arrays.
False primary trait for dynamic-vector conversion detection.
struct usher_control_result result
Definition usher.c:377