I'm attempting to write a JSON parser in Zig. Parsing is going reasonably well but I can't print the structured types out. The issue I'm having is with the nested types "Array" and "Object". I want to return a []const u8 (so I can print it) but I'm running into issues I don't know how to debug.
This is the type I've made:
pub const Value = union(enum) {
null,
true,
false,
integer: []const u8,
string: []const u8,
array: std.ArrayList(Value),
// object: std.ArrayList(Object),
};
And this is the type to string conversion code.
fn value_to_string(value: Value) []const u8 {
return switch (value) {
.false => |_| "false",
.null => |_| "null",
.true => |_| "true",
.integer => |v| v,
.string => |v| v,
.array => |vs| {
const out = array_list_to_string(vs) catch |e| {
std.debug.panic("some error {s}", .{e});
};
return out;
},
};
}
fn array_list_to_string(values: std.ArrayList(Value)) Error![][]const u8 {
var allocator = std.heap.page_allocator;
var array_list = std.ArrayList([]const u8).init(allocator);
try array_list.append("[");
const i = 0;
for (values.items) |value| {
if (i > 0) array_list.append(",");
try array_list.append(value_to_string(value));
}
try array_list.append("]");
return array_list.toOwnedSlice();
}
What I want is a contiguous sequence of bytes. What I have are different sequences of bytes allocated on the heap somewhere. So I'm trying to take this heap allocated array of []u8 and mash them all together into a single, stack allocated []u8 (right?). But I'm having trouble mashing them all together. Am I having trouble because I don't know some technique or is this not an allowable thing and there's a different way to print these heap allocated slices?
I exceeded the character limit so hopefully this is enough context!