浏览代码

Initial migration from Invercargill repo

Billy Barrow 4 月之前
当前提交
ea0c323ae9

+ 7 - 0
.gitignore

@@ -0,0 +1,7 @@
+/lib
+/meson-*
+build.ninja
+compile_commands.json
+/tests
+.ninja_log
+.ninja_deps

+ 165 - 0
LICENSE

@@ -0,0 +1,165 @@
+                   GNU LESSER GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+  This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+  0. Additional Definitions.
+
+  As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+  "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+  An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+  A "Combined Work" is a work produced by combining or linking an
+Application with the Library.  The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+  The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+  The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+  1. Exception to Section 3 of the GNU GPL.
+
+  You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+  2. Conveying Modified Versions.
+
+  If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+   a) under this License, provided that you make a good faith effort to
+   ensure that, in the event an Application does not supply the
+   function or data, the facility still operates, and performs
+   whatever part of its purpose remains meaningful, or
+
+   b) under the GNU GPL, with none of the additional permissions of
+   this License applicable to that copy.
+
+  3. Object Code Incorporating Material from Library Header Files.
+
+  The object code form of an Application may incorporate material from
+a header file that is part of the Library.  You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+   a) Give prominent notice with each copy of the object code that the
+   Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the object code with a copy of the GNU GPL and this license
+   document.
+
+  4. Combined Works.
+
+  You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+   a) Give prominent notice with each copy of the Combined Work that
+   the Library is used in it and that the Library and its use are
+   covered by this License.
+
+   b) Accompany the Combined Work with a copy of the GNU GPL and this license
+   document.
+
+   c) For a Combined Work that displays copyright notices during
+   execution, include the copyright notice for the Library among
+   these notices, as well as a reference directing the user to the
+   copies of the GNU GPL and this license document.
+
+   d) Do one of the following:
+
+       0) Convey the Minimal Corresponding Source under the terms of this
+       License, and the Corresponding Application Code in a form
+       suitable for, and under terms that permit, the user to
+       recombine or relink the Application with a modified version of
+       the Linked Version to produce a modified Combined Work, in the
+       manner specified by section 6 of the GNU GPL for conveying
+       Corresponding Source.
+
+       1) Use a suitable shared library mechanism for linking with the
+       Library.  A suitable mechanism is one that (a) uses at run time
+       a copy of the Library already present on the user's computer
+       system, and (b) will operate properly with a modified version
+       of the Library that is interface-compatible with the Linked
+       Version.
+
+   e) Provide Installation Information, but only if you would otherwise
+   be required to provide such information under section 6 of the
+   GNU GPL, and only to the extent that such information is
+   necessary to install and execute a modified version of the
+   Combined Work produced by recombining or relinking the
+   Application with a modified version of the Linked Version. (If
+   you use option 4d0, the Installation Information must accompany
+   the Minimal Corresponding Source and Corresponding Application
+   Code. If you use option 4d1, you must provide the Installation
+   Information in the manner specified by section 6 of the GNU GPL
+   for conveying Corresponding Source.)
+
+  5. Combined Libraries.
+
+  You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+   a) Accompany the combined library with a copy of the same work based
+   on the Library, uncombined with any other library facilities,
+   conveyed under the terms of this License.
+
+   b) Give prominent notice with the combined library that part of it
+   is a work based on the Library, and explaining where to find the
+   accompanying uncombined form of the same work.
+
+  6. Revised Versions of the GNU Lesser General Public License.
+
+  The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+  Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+  If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.

+ 52 - 0
MANIFEST.usm

@@ -0,0 +1,52 @@
+{
+  "name": "invercargill-json",
+  "version": "0.0.1",
+  "summary": "Json support for Invercargill",
+  "licences": [ {"name": "LGPLv3", "category": "libre", "text": "LICENSE"} ],
+  "flags": [],
+  "provides": {
+    "lib:libinvercargill-json.so": "as-expected",
+    "inc:invercargill-json.h": "as-expected",
+    "vapi:invercargill-json.vapi": "as-expected",
+    "gir:invercargill_json-1.0.gir": "as-expected",
+    "typelib:invercargill_json-1.0.typelib": "as-expected",
+    "pc:invercargill-json.pc": "as-expected"
+  },
+  "depends": {
+    "runtime": [
+      "lib:libinvercargill.so",
+      "lib:libglib-2.0.so.0",
+      "lib:libgobject-2.0.so.0",
+      "lib:libgee-0.8.so.2",
+      "lib:libc.so.6",
+      "lib:libjson-glib-1.0.so",
+      "lib:libgio-2.0.so.0",
+      "lib:libpcre2-8.so.0",
+      "lib:libffi.so.8",
+      "lib:libgmodule-2.0.so.0",
+      "lib:libz.so.1",
+      "lib:libmount.so.1",
+      "lib:libselinux.so.1",
+      "lib:libblkid.so.1"
+    ],
+    "build": [
+      "bin:valac",
+      "bin:meson",
+      "bin:g-ir-compiler",
+      "pc:glib-2.0.pc",
+      "pc:gobject-2.0.pc",
+      "pc:gio-2.0.pc",
+      "pc:gee-0.8.pc",
+      "pc:json-glib-1.0.pc",
+      "pc:invercargill.pc"
+    ],
+    "manage": [
+      "bin:bash"
+    ]
+  },
+  "execs": {
+    "build": "scripts/build.sh",
+    "install": "scripts/install.sh",
+    "post_install": "scripts/post-install.sh"
+  }
+}

+ 6 - 0
README.md

@@ -0,0 +1,6 @@
+# Invercargill
+
+This library provides an Enumerable type that aims to make working with data sets
+much less cogniatively taxing while using Vala.
+
+More to come

+ 11 - 0
scripts/build.sh

@@ -0,0 +1,11 @@
+#!/bin/bash
+set -e
+
+src_dir=$(pwd)
+build_dir=$1
+
+cd ${build_dir}
+
+meson setup ${src_dir}/src --prefix=${PREFIX} --libdir=${LIBDIR} --includedir=${INCLUDEDIR}
+ninja
+

+ 9 - 0
scripts/install.sh

@@ -0,0 +1,9 @@
+#!/bin/bash
+set -e
+
+src_dir=$(pwd)
+build_dir=$1
+
+cd ${build_dir}
+
+meson install --destdir ${DESTDIR}

+ 2 - 0
scripts/post-install.sh

@@ -0,0 +1,2 @@
+#!/bin/bash
+ldconfig

+ 58 - 0
src/lib/Array.vala

@@ -0,0 +1,58 @@
+using Invercargill;
+
+namespace InvercargillJson {
+
+    public class JsonArray : IndexedCollection<JsonElement>, Elements, JsonElements {
+
+        private Json.Array array;
+
+        internal Json.Array json_glib_object { get { return array; } }
+
+        public JsonArray() {
+            array = new Json.Array();
+        }
+
+        internal JsonArray.from_existing(Json.Array array) {
+            this.array = array;
+        }
+
+        public override Tracker<Element> get_tracker() {
+            var i = 0;
+            return new LambdaTracker<Element>(
+                () => {
+                    return i < array.get_length();
+                },
+                () => {
+                    return new JsonElement.from_node(array.get_element(i++));
+                });
+        }
+
+        public new override JsonElement @get(int index) {
+            return new JsonElement.from_node(array.get_element(index));
+        }
+        public override int index_of(PredicateDelegate<Element> predicate) {
+            return with_positions().first_or_default(i => predicate(i.item))?.position ?? -1;
+        }
+        public override void remove(int index) {
+            array.remove_element(index);
+        }
+        public new override void @set(int index, JsonElement item) {
+            assert_not_reached();
+        }
+        public override void add(JsonElement item) {
+            array.add_element(item.assert_as<Json.Node>());
+        }
+        public override void remove_first_where(Invercargill.PredicateDelegate<JsonElement> predicate) {
+            var index = index_of(predicate);
+            if(index >= 0) {
+                array.remove_element(index);
+            }
+        }
+        public override void remove_where(Invercargill.PredicateDelegate<JsonElement> predicate) {
+            with_positions()
+                .where(i => predicate((JsonElement)i.item))
+                .iterate(i => array.remove_element(i.position));
+        }
+    }
+
+}

+ 54 - 0
src/lib/Elements.vala

@@ -0,0 +1,54 @@
+
+using Invercargill;
+namespace InvercargillJson {
+
+    public interface JsonElements : Enumerable<JsonElement>, Elements {
+
+        public virtual Enumerable<JsonArray> as_arrays() {
+            return select<JsonArray>(n => new JsonArray.from_existing(n.assert_as<Json.Node>().get_array()));
+        }
+
+        public virtual Enumerable<bool> as_bools() {
+            return select<bool>(n => n.assert_as<Json.Node>().get_boolean());
+        }
+
+        public virtual Doubles as_doubles() {
+            return select<double?>(n => n.assert_as<Json.Node>().get_double()).promote_to<Doubles>();
+        }
+
+        public virtual Signed64BitIntegers as_integers() {
+            return select<int64?>(n => n.assert_as<Json.Node>().get_int()).promote_to<Signed64BitIntegers>();
+        }
+
+        public virtual Enumerable<string> as_strings() {
+            return select<string>(n => n.assert_as<Json.Node>().get_string());
+        }
+
+        public virtual Enumerable<JsonObject> as_objects() {
+            return select<JsonObject>(n => new JsonObject.from_existing(n.assert_as<Json.Node>().get_object()));
+        }
+
+        public virtual JsonArray to_json_array() {
+            var array = new JsonArray();
+            array.add_all((Enumerable<JsonElement>)this);
+            return array;
+        }
+
+    }
+
+    private class JsonElementsPromotionImplementation : Object, Promotion<Element> {
+        public bool can_wrap(GLib.Type element_type) {
+            return element_type.is_a(typeof(JsonElement));
+        }
+        public Enumerable<Element> wrap(Enumerable<Element> enumerable) {
+            return new JsonElementsProxy(enumerable.cast<JsonElement>());
+        }
+    }
+
+    private class JsonElementsProxy : ProxyEnumerable<JsonElement>, Elements, JsonElements {
+        public JsonElementsProxy(Enumerable<JsonElement> elements) {
+            inner = elements;
+        }
+    }
+
+}

+ 332 - 0
src/lib/Json.vala

@@ -0,0 +1,332 @@
+
+namespace InvercargillJson {
+
+
+    public class JsonElement : Object, Invercargill.Element {
+
+        private Json.Node node;
+
+        public JsonElement.from_string(string json) throws GLib.Error {
+            node = Json.from_string (json);
+        }
+
+        public JsonElement.from_file(string path) throws GLib.Error {
+            var parser = new Json.Parser();
+            parser.load_from_file(path);
+            node = parser.get_root();
+        }
+
+        public JsonElement.from_stream(InputStream stream) throws GLib.Error {
+            var parser = new Json.Parser();
+            parser.load_from_stream(stream);
+            node = parser.get_root();
+        }
+
+        public async JsonElement.from_stream_async(InputStream stream, GLib.Cancellable cancellable) throws GLib.Error {
+            var parser = new Json.Parser();
+            yield parser.load_from_stream_async (stream, cancellable);
+            node = parser.get_root();
+        }
+
+        internal JsonElement.from_node(Json.Node node) {
+            this.node = node;
+        }
+
+        public JsonElement.from_properties(Invercargill.Properties properties) throws Invercargill.ElementError {
+            node = new Json.Node (Json.NodeType.OBJECT);
+            var object = new JsonObject();
+            foreach (var item in properties) {
+                object.set(item.key, new JsonElement.from_element(item.value));
+            }
+            node.set_object (object.json_glib_object);
+        }
+
+        public JsonElement.from_elements(Invercargill.Elements elements) throws Invercargill.ElementError {
+            node = new Json.Node (Json.NodeType.ARRAY);
+            var array = new JsonArray();
+            foreach (var item in elements) {
+                array.add(new JsonElement.from_element (item));
+            }
+            node.set_array (array.json_glib_object);
+        }
+
+        public JsonElement.from_element(Invercargill.Element element) throws Invercargill.ElementError {
+            // Null node is top priority
+            if(element.is_null ()) {
+                node = new Json.Node(Json.NodeType.NULL);
+                node.init_null ();
+                return;
+            }
+
+            // Second priority is creation of arrays and objects
+            if(element.assignable_to<Invercargill.Properties>()) {
+                node = new Json.Node (Json.NodeType.OBJECT);
+                var object = new JsonObject();
+                foreach (var item in element.as<Invercargill.Properties>()) {
+                    object.set(item.key, new JsonElement.from_element(item.value));
+                }
+                node.set_object (object.json_glib_object);
+                return;
+            }
+            if(element.assignable_to<Invercargill.Elements>()) {
+                node = new Json.Node (Json.NodeType.ARRAY);
+                var array = new JsonArray();
+                foreach (var item in element.as<Invercargill.Elements>()) {
+                    array.add(new JsonElement.from_element (item));
+                }
+                node.set_array (array.json_glib_object);
+                return;
+            }
+
+            node = new Json.Node (Json.NodeType.VALUE);
+            var type = element.type();
+
+            // Third priority is conversion of known types
+            if(type == typeof(DateTime)) {
+                node.set_string (element.as<DateTime>().format_iso8601());
+                return;
+            }
+            if(type == typeof(Invercargill.BinaryData)) {
+                node.set_string (element.as<Invercargill.BinaryData>().to_base64());
+                return;
+            }
+            if(type == typeof(string)) {
+                node.set_string (element.as<string>());
+                return;
+            }
+            if(type == typeof(bool)) {
+                node.set_boolean (element.as<bool>());
+                return;
+            }
+            if(type == typeof(double)) {
+                node.set_double (element.as<double?>());
+                return;
+            }
+            if(type == typeof(int64)) {
+                node.set_int (element.as<int64?>());
+                return;
+            }
+            if(type == typeof(uint8)) {
+                node.set_int (element.as<uint>());
+                return;
+            }
+            if(type == typeof(int8)) {
+                node.set_int (element.as<int>());
+                return;
+            }
+            if(type == typeof(uint16)) {
+                node.set_int (element.as<uint16>());
+                return;
+            }
+            if(type == typeof(int16)) {
+                node.set_int (element.as<int16>());
+                return;
+            }
+            if(type == typeof(uint32)) {
+                node.set_int (element.as<uint32>());
+                return;
+            }
+            if(type == typeof(int32)) {
+                node.set_int (element.as<int32>());
+                return;
+            }
+            if(type == typeof(uint64?)) {
+                node.set_int ((int64)element.as<uint64?>());
+                return;
+            }
+            if(type == typeof(float?)) {
+                node.set_double (element.as<float?>());
+                return;
+            }            
+
+            // Last priority is the element's native conversions
+            if(element.assignable_to<string>()) {
+                node.set_string (element.as<string>());
+                return;
+            }
+            if(element.assignable_to<bool> ()) {
+                node.set_boolean(element.as<bool>());
+                return;
+            }
+            if(element.assignable_to<double?>()) {
+                node.set_double(element.as<double?>());
+                return;
+            }
+            if(element.assignable_to<int64?>()) {
+                node.set_int(element.as<int64?>());
+                return;
+            }
+
+            // Could not convert
+            throw new Invercargill.ElementError.INVALID_CONVERSION(@"No way to convert element $(element.get_type ().name()) containing type $(type.name()) to a type suitable for a JsonElement.");
+        }
+
+        public bool assignable_to_type (GLib.Type type) {
+            if(node.is_null() || type == typeof(Json.Node)) {
+                return true;
+            }
+            if(node.get_node_type() == Json.NodeType.ARRAY) {
+                return
+                    type == typeof(JsonArray) || 
+                    type == typeof(JsonElements) || 
+                    type == typeof(Invercargill.Elements) ||
+                    type == typeof(Json.Array);
+            }
+            if(node.get_node_type() == Json.NodeType.OBJECT) {
+                return
+                    type == typeof(JsonObject) || 
+                    type == typeof(Invercargill.Properties) ||
+                    type == typeof(Json.Object);
+            }
+            if(node.get_value_type().is_a(typeof(int64)) || node.get_value_type ().is_a(typeof(double))) {
+                return
+                    type == typeof(uint8) ||
+                    type == typeof(int8) ||
+                    type == typeof(uint16) ||
+                    type == typeof(int16) ||
+                    type == typeof(uint32) ||
+                    type == typeof(int32) ||
+                    type == typeof(uint64) ||
+                    type == typeof(int64) ||
+                    type == typeof(double) ||
+                    type == typeof(float) ||
+                    type == typeof(string);
+            }
+            if(node.get_value_type().is_a(typeof(string))) {
+                return
+                    type == typeof(string) ||
+                    type == typeof(Invercargill.BinaryData) ||
+                    (type == typeof(DateTime) && new DateTime.from_iso8601(node.get_string(), null) != null);
+            }
+            if(node.get_value_type().is_a(typeof(bool))) {
+                return type == typeof(bool);
+            }
+            return false;
+        }
+        public bool is_null () {
+            return node.is_null();
+        }
+        public bool try_get_as<T> (out T result) {
+            if(!assignable_to<T>()) {
+                result = null;
+                return false;
+            }
+            if(typeof(T) == typeof(Json.Node)) {
+                result = node;
+                return true;
+            }
+            if(node.is_null ()) {
+                result = null;
+                return true;
+            }
+            if(typeof(T) == typeof(JsonArray) || typeof(T) == typeof(Invercargill.Elements)) {
+                result = new JsonArray.from_existing (node.get_array ());
+                return true;
+            }
+            if(typeof(T) == typeof(Json.Array)) {
+                result = node.get_array();
+                return true;
+            }
+            if(typeof(T) == typeof(JsonObject) || typeof(T) == typeof(Invercargill.Properties)) {
+                result = new JsonObject.from_existing (node.get_object());
+                return true;
+            }
+            if(typeof(T) == typeof(Json.Object)) {
+                result = node.get_object();
+                return true;
+            }
+            if(typeof(T).is_a(typeof(uint8))) {
+                result = (uint8)node.get_int();
+                return true;
+            }
+            if(typeof(T).is_a(typeof(int8))) {
+                result = (int8)node.get_int();
+                return true;
+            }
+            if(typeof(T).is_a(typeof(uint16))) {
+                result = (uint16)node.get_int();
+                return true;
+            }
+            if(typeof(T).is_a(typeof(int16))) {
+                result = (int16)node.get_int();
+                return true;
+            }
+            if(typeof(T).is_a(typeof(uint32))) {
+                result = (uint32)node.get_int();
+                return true;
+            }
+            if(typeof(T).is_a(typeof(int32))) {
+                result = (int32)node.get_int();
+                return true;
+            }
+            if(typeof(T).is_a(typeof(uint64))) {
+                uint64? r = node.get_int();
+                result = r;
+                return true;
+            }
+            if(typeof(T).is_a(typeof(int64))) {
+                int64? r = node.get_int();
+                result = r;
+                return true;
+            }
+            if(typeof(T).is_a(typeof(double))) {
+                double? r = node.get_double();
+                result = r;
+                return true;
+            }
+            if(typeof(T).is_a(typeof(float))) {
+                float? r = (float)node.get_double();
+                result = r;
+                return true;
+            }
+            if(typeof(T).is_a(typeof(string))) {
+                if(node.get_value_type().is_a (typeof(double))) {
+                    result = node.get_double().to_string();
+                }
+                else if(node.get_value_type().is_a(typeof(int64))) {
+                    result = node.get_int().to_string();
+                }
+                result = node.get_string();
+                return true;
+            }
+            if(typeof(T).is_a(typeof(DateTime))) {
+                result = new DateTime.from_iso8601(node.get_string (), null);
+                return true;
+            }
+            if(typeof(T).is_a(typeof(Invercargill.BinaryData))) {
+                result = new Invercargill.BinaryData.from_base64(node.get_string ());
+                return true;
+            }
+            if(typeof(T).is_a(typeof(bool))) {
+                result = node.get_boolean();
+                return true;
+            }
+
+            warning(@"Type \"$(typeof(T).name())\" passed assignable check but the conversion is not implemented");
+            result = null;
+            return false;
+        }
+
+        public GLib.Type? type () {
+            return typeof(Json.Node);
+        }
+
+        public string stringify(bool pretty = false) {
+            return Json.to_string (node, pretty);
+        }
+
+        public void write_to_stream(OutputStream stream) throws Error {
+            var gen = new Json.Generator();
+            gen.set_root (node);
+            gen.to_stream (stream);
+        }
+
+        public void write_to_file(string path) throws Error {
+            var gen = new Json.Generator();
+            gen.set_root (node);
+            gen.to_file (path);
+        }
+
+    }
+
+}

+ 91 - 0
src/lib/Object.vala

@@ -0,0 +1,91 @@
+using Invercargill;
+
+namespace InvercargillJson {
+
+    public class JsonObject : Associative<string, JsonElement>, Properties {
+
+        private Json.Object object;
+
+        public Json.Object json_glib_object { get { return object; } }
+
+        public JsonObject() {
+            object = new Json.Object();
+        }
+
+        internal JsonObject.from_existing(Json.Object object) {
+            this.object = object;
+        }
+        public override void clear (string key) {
+            object.foreach_member ((o, n) => o.remove_member (n));
+        }
+        public override bool has (string key) {
+            return object.has_member(key);
+        }
+        public new override void @set (string key, JsonElement value) {
+            object.set_member(key, value.assert_as<Json.Node>());
+        }
+        public override bool try_get (string key, out JsonElement value) {
+            if(has(key)) {
+                value = new JsonElement.from_node(object.get_member(key));
+                return true;
+            }
+            value = null;
+            return false;
+        }
+        public override Tracker<KeyValuePair<string, Element>> get_tracker () {
+            var keys = object.get_members ();
+            var i = 0;
+            return new LambdaTracker<KeyValuePair<string, Element>>(
+                () => {
+                    return i < keys.length();
+                },
+                () => {
+                    return new KeyValuePair<string, Element> (keys.nth_data(i), new JsonElement.from_node(object.get_member(keys.nth_data(i++))));
+                });
+        }
+
+        public JsonArray? get_array(string key) {
+            var item = object.get_array_member(key);
+            if(item != null) {
+                return new JsonArray.from_existing(item);
+            }
+            return null;
+        }
+
+        public bool? get_bool(string key) {
+            return object.get_boolean_member(key);
+        }
+
+        public double? get_double(string key) {
+            return object.get_double_member(key);
+        }
+
+        public int64? get_integer(string key) {
+            return object.get_int_member(key);
+        }
+
+        public string? get_string(string key) {
+            return object.get_string_member(key);
+        }
+
+        public JsonObject? get_object(string key) {
+            var item = object.get_object_member(key);
+            if(item != null) {
+                return new JsonObject.from_existing(item);
+            }
+            return null;
+        }
+
+        public void set_native<T>(string key, T value) throws ElementError {
+            set(key, new JsonElement.from_element(new NativeElement<T>(value)));
+        }
+
+        public JsonElement as_element() {
+            var node = new Json.Node(Json.NodeType.OBJECT);
+            node.take_object(object);
+            return new JsonElement.from_node(node);
+        }
+
+    }
+
+}

+ 10 - 0
src/lib/PromotionRegistration.c

@@ -0,0 +1,10 @@
+
+#include "invercargill-json.h"
+#include "invercargill.h"
+
+VALA_EXTERN GType invercargill_json_json_elements_promotion_implementation_get_type (void) G_GNUC_CONST ;
+
+__attribute__((constructor))
+static void register_promotions() {
+    invercargill_register_promotion (INVERCARGILL_JSON_TYPE_JSON_ELEMENTS, invercargill_json_json_elements_promotion_implementation_get_type());
+}

+ 35 - 0
src/lib/meson.build

@@ -0,0 +1,35 @@
+
+dependencies = [
+    dependency('glib-2.0'),
+    dependency('gobject-2.0'),
+    dependency('gee-0.8'),
+    dependency('json-glib-1.0'),
+    dependency('invercargill')
+]
+
+sources = files('Json.vala')
+sources += files('PromotionRegistration.c')
+sources += files('Elements.vala')
+sources += files('Array.vala')
+sources += files('Object.vala')
+
+invercargill_json = shared_library('invercargill-json', sources,
+    dependencies: dependencies,
+    install: true,
+    vala_gir: 'invercargill_json-1.0.gir',
+    install_dir: [true, true, true, true]
+)
+invercargill_json_dep = declare_dependency(link_with: invercargill_json, include_directories: include_directories('.'))
+
+pkg = import('pkgconfig')
+pkg.generate(invercargill_json,
+    version : '0.1',
+    name : 'invercargill-json',)
+    
+g_ir_compiler = find_program('g-ir-compiler')
+custom_target('invercargill-json typelib', command: [g_ir_compiler, '--shared-library=libinvercargill-json.so', '--output', '@OUTPUT@', meson.current_build_dir() / 'invercargill_json-1.0.gir'],
+              output: 'invercargill_json-1.0.typelib',
+              depends: invercargill_json,
+              install: true,
+              install_dir: get_option('libdir') / 'girepository-1.0')
+              

+ 4 - 0
src/meson.build

@@ -0,0 +1,4 @@
+project('invercargill-json', 'vala', 'c')
+subdir('lib')
+dependencies += invercargill_json_dep
+subdir('tests')

+ 35 - 0
src/tests/Integration/Json.vala

@@ -0,0 +1,35 @@
+using Invercargill;
+using Invercargill.Convert;
+using InvercargillJson;
+using Json;
+
+void json_tests() {
+    Test.add_func("/invercargill/json/strings", () => {
+
+        var json_str = """[
+            "Glengarry",
+            "Gladstone",
+            "Strathern",
+            "Richmond",
+            "Georgetown"
+        ]""";
+
+        try {
+            var suburbs = new JsonElement.from_string(json_str)
+                .assert_as<JsonArray>()
+                .as_strings()
+                .to_array();
+            
+            assert_cmpint(5, CompareOperator.EQ, suburbs.length);
+            assert_cmpstr("Glengarry", CompareOperator.EQ, suburbs[0]);
+            assert_cmpstr("Gladstone", CompareOperator.EQ, suburbs[1]);
+            assert_cmpstr("Strathern", CompareOperator.EQ, suburbs[2]);
+            assert_cmpstr("Richmond", CompareOperator.EQ, suburbs[3]);
+            assert_cmpstr("Georgetown", CompareOperator.EQ, suburbs[4]);
+        }
+        catch(Error e) {
+            assert_no_error(e);
+        }
+    });
+
+}

+ 59 - 0
src/tests/Integration/Promotion.vala

@@ -0,0 +1,59 @@
+using Invercargill;
+using Invercargill.Convert;
+using InvercargillJson;
+
+void promotion_tests() {
+
+    Test.add_func("/invercargill/promotions/uint8_to_binarydata", () => {
+
+        var data = new Vector<uint8>();
+        data.add(1);
+        data.add(9);
+        data.add(7);
+
+        var base64 = data.promote_to<BinaryData>().to_base64();
+        
+        assert_cmpstr("AQAA", CompareOperator.EQ, base64);
+
+    });
+
+    Test.add_func("/invercargill/promotions/binarydata_to_binarydata", () => {
+
+        var data = (Enumerable<uint8>)new BinaryData.from_base64("AQAA");
+        var new_data = data.promote_to<BinaryData>();
+        
+        assert_true(data == new_data);
+    });
+
+    Test.add_func("/invercargill/promotion/json", () => {
+
+        var json_str = """[
+            "Glengarry",
+            "Gladstone",
+            "Strathern",
+            "Richmond",
+            "Georgetown"
+        ]""";
+
+        try {
+            var suburbs = new JsonElement.from_string(json_str)
+                .assert_as<JsonArray>()
+                .where(e => e.assert_as<string>().has_prefix("G"))
+                .promote_to<JsonElements>();
+            
+            var names = suburbs
+                .as_strings()
+                .to_array();
+
+            assert_cmpint(3, CompareOperator.EQ, suburbs.count());
+            assert_cmpint(3, CompareOperator.EQ, names.length);
+            assert_cmpstr("Glengarry", CompareOperator.EQ, names[0]);
+            assert_cmpstr("Gladstone", CompareOperator.EQ, names[1]);
+            assert_cmpstr("Georgetown", CompareOperator.EQ, names[2]);
+
+        }
+        catch(Error e) {
+            assert_no_error(e);
+        }
+    });
+}

+ 79 - 0
src/tests/Integration/PropertyMapper.vala

@@ -0,0 +1,79 @@
+using Invercargill;
+using Invercargill.Convert;
+using InvercargillJson;
+using Json;
+
+void property_mapper_tests() {
+
+    Test.add_func("/invercargill/property_mapper/map_class_to_and_from_properties", () => {
+
+        var mapper = new PropertyMapperBuilder<MappedClass>()
+            .set_constructor(() => new MappedClass())
+            .map<string>("name", c => c.name, (c, v) => c.name = v)
+            .map<int>("number", c => c.number, (c, v) => c.number = v)
+            .build();
+
+        var original = new MappedClass() {
+            name = "Billy Barrow",
+            not_mapped = "Invercargill",
+            number = 1999
+        };
+
+        var properties = mapper.map_from(original);
+
+        try {
+            var copy = mapper.materialise(properties);
+    
+            assert(properties.where(p => p.value.assignable_to<string>()).no(p => p.value.assert_as<string>() == "Invercargill"));
+            assert(properties.where(p => p.value.assignable_to<string>()).any(p => p.value.assert_as<string>() == "Billy Barrow"));
+            assert_cmpint(original.number, CompareOperator.EQ, copy.number);
+            assert_cmpstr(original.name, CompareOperator.EQ, copy.name);
+            assert_null(copy.not_mapped);
+        }
+        catch(Error e) {
+            assert_no_error(e);
+        }
+
+    });
+
+    Test.add_func("/invercargill/property_mapper/map_from_json", () => {
+
+        var mapper = new PropertyMapperBuilder<MappedClass>()
+            .set_constructor(() => new MappedClass())
+            .map<string>("name", c => c.name, (c, v) => c.name = v)
+            .map<int>("number", c => c.number, (c, v) => c.number = v)
+            .build();
+
+
+        var json_str = """{
+            "number": 25,
+            "name": "Billy Barrow",
+            "not_mapped": "Invercargill"
+        }""";
+
+        try {
+            var properties = new JsonElement.from_string(json_str)
+                .assert_as<JsonObject>();
+    
+            var copy = mapper.materialise(properties);
+            assert(properties.where(p => p.value.assignable_to<string>()).any(p => p.value.assert_as<string>() == "Billy Barrow"));
+            assert_cmpint(25, CompareOperator.EQ, copy.number);
+            assert_cmpstr("Billy Barrow", CompareOperator.EQ, copy.name);
+            assert_null(copy.not_mapped);
+        }
+        catch(Error e) {
+            assert_no_error(e);
+        }
+
+
+    });
+
+}
+
+private class MappedClass {
+
+    public int number { get; set; }   
+    public string name { get; set; }
+    public string not_mapped { get; set; }
+
+}

+ 14 - 0
src/tests/TestRunner.vala

@@ -0,0 +1,14 @@
+
+public static int main(string[] args) {
+
+    Test.init(ref args);
+
+    promotion_tests();
+    property_mapper_tests();
+    json_tests();
+    
+    Test.run();
+
+
+    return 0;
+}

+ 7 - 0
src/tests/meson.build

@@ -0,0 +1,7 @@
+
+sources = files('TestRunner.vala')
+sources += files('Integration/Promotion.vala')
+sources += files('Integration/PropertyMapper.vala')
+sources += files('Integration/Json.vala')
+
+executable('invercargill-json-test-suite', sources, dependencies: dependencies, install: true)