83 lines
2.5 KiB
Zig
83 lines
2.5 KiB
Zig
const c = @cImport({
|
|
@cInclude("json.h");
|
|
});
|
|
const std = @import("std");
|
|
|
|
pub const Obj = struct {
|
|
obj: *c.json_object,
|
|
|
|
// TODO: Port type attribute to a zig enum and assign it upon creation
|
|
|
|
///////////////////////////////////
|
|
// ** General functions **
|
|
/////////////////////////////////
|
|
|
|
pub fn newObject() Obj {
|
|
return Obj{ .obj = c.json_object_new_object().? };
|
|
}
|
|
pub fn newArray() Obj {
|
|
return Obj{ .obj = c.json_object_new_array().? };
|
|
}
|
|
pub fn newString(s: [*c]const u8) Obj {
|
|
return Obj{ .obj = c.json_object_new_string(s).? };
|
|
}
|
|
pub fn newInt32(i: i32) Obj {
|
|
return Obj{ .obj = c.json_object_new_int(i).? };
|
|
}
|
|
pub fn newInt64(i: i64) Obj {
|
|
return Obj{ .obj = c.json_object_new_int64(i).? };
|
|
}
|
|
pub fn newFromString(s: [*c]const u8) Obj {
|
|
return Obj{ .obj = c.json_tokener_parse(s).? };
|
|
}
|
|
|
|
pub fn deinit(self: *Obj) void {
|
|
_ = c.json_object_put(self.obj);
|
|
}
|
|
|
|
// Not *const Obj because the json_object retains ownership of the string
|
|
pub fn toString(self: *Obj) []const u8 {
|
|
// TODO: Allow passing of flags as an enum like the SDL2 binding
|
|
return std.mem.sliceTo(c.json_object_to_json_string(self.obj), 0);
|
|
}
|
|
|
|
///////////////////////////////////
|
|
// ** Object functions **
|
|
/////////////////////////////////
|
|
|
|
// TODO: Create an error for type checking.
|
|
|
|
pub fn objectGet(self: *const Obj, key: [*c]const u8) Obj {
|
|
// TODO: Check type and null return as errors
|
|
var obj: ?*c.json_object = undefined;
|
|
_ = c.json_object_object_get_ex(self.obj, key, &obj);
|
|
return Obj{ .obj = c.json_object_get(obj).? };
|
|
}
|
|
|
|
pub fn objectAdd(self: *Obj, key: [*c]const u8, value: ?*Obj) void {
|
|
// TODO: Check type and error return
|
|
|
|
// We need the json-c object or null, not the zig object
|
|
const o = if (value) |i| i.obj else null;
|
|
|
|
_ = c.json_object_object_add(self.obj, key, o);
|
|
}
|
|
|
|
///////////////////////////////////
|
|
// ** Array functions **
|
|
/////////////////////////////////
|
|
|
|
pub fn arrayAdd(self: *Obj, value: ?*Obj) void {
|
|
// TODO: Check type and error return
|
|
// TODO: Check if it can accept a null value
|
|
|
|
// We need the json-c object or null, not the zig object
|
|
const o = if (value) |i| i.obj else null;
|
|
|
|
_ = c.json_object_array_add(self.obj, o);
|
|
}
|
|
};
|
|
|
|
// TODO: Create wrapper types that statically check and know there
|
|
// won't be any problems
|