<http://www.gnu.org/licenses/>. */
#include "config.h"
+#define INCLUDE_MEMORY
#include "system.h"
#include "coretypes.h"
#include "json.h"
#include "pretty-print.h"
#include "math.h"
+#include "make-unique.h"
#include "selftest.h"
using namespace json;
ASSERT_PRINT_EQ (literal (false), true, "false");
}
-/* Verify that nested values are formatted correctly when written. */
+/* Verify that nested values are formatted correctly when written.
+
+ Also, make use of array::append(std::unique_ptr<value>) and
+ object::set (const char *key, std::unique_ptr<value> v).*/
static void
test_formatting ()
{
object obj;
object *child = new object;
- object *grandchild = new object;
+ std::unique_ptr<object> grandchild = ::make_unique<object> ();
obj.set_string ("str", "bar");
obj.set ("child", child);
obj.set_integer ("int", 42);
- child->set ("grandchild", grandchild);
- child->set_integer ("int", 1776);
-
array *arr = new array;
for (int i = 0; i < 3; i++)
- arr->append (new integer_number (i));
+ arr->append (::make_unique<integer_number> (i));
grandchild->set ("arr", arr);
grandchild->set_integer ("int", 1066);
+ child->set ("grandchild", std::move (grandchild));
+ child->set_integer ("int", 1776);
+
/* This test relies on json::object writing out key/value pairs
in key-insertion order. */
ASSERT_PRINT_EQ (obj, true,
#ifndef GCC_JSON_H
#define GCC_JSON_H
+/* This header uses std::unique_ptr, but <memory> can't be directly
+ included due to issues with macros. Hence <memory> must be included
+ from system.h by defining INCLUDE_MEMORY in any source file using
+ json.h. */
+
+#ifndef INCLUDE_MEMORY
+# error "You must define INCLUDE_MEMORY before including system.h to use make-unique.h"
+#endif
+
/* Implementation of JSON, a lightweight data-interchange format.
See http://www.json.org/
void print (pretty_printer *pp, bool formatted) const final override;
void set (const char *key, value *v);
+
+ /* Set the property KEY of this object, requiring V
+ to be of a specific json::value subclass.
+
+ This can be used to enforce type-checking, making it easier
+ to comply with a schema, e.g.
+ obj->set<some_subclass> ("property_name", value)
+ leading to a compile-time error if VALUE is not of the
+ appropriate subclass. */
+ template <typename JsonType>
+ void set (const char *key, std::unique_ptr<JsonType> v)
+ {
+ set (key, v.release ());
+ }
+
value *get (const char *key) const;
void set_string (const char *key, const char *utf8_value);
void append (value *v);
void append_string (const char *utf8_value);
+ /* Append V to this array, requiring V
+ to be a specific json::value subclass.
+
+ This can be used to enforce type-checking, making it easier
+ to comply with a schema, e.g.
+ arr->append<some_subclass> (value)
+ leading to a compile-time error if VALUE is not of the
+ appropriate subclass. */
+ template <typename JsonType>
+ void append (std::unique_ptr<JsonType> v)
+ {
+ append (v.release ());
+ }
+
private:
auto_vec<value *> m_elements;
};