Skip to content

Instantly share code, notes, and snippets.

@ssteinbach
Created August 2, 2023 04:34
Show Gist options
  • Save ssteinbach/e2868d650b5d2484d55f445230b01608 to your computer and use it in GitHub Desktop.
Save ssteinbach/e2868d650b5d2484d55f445230b01608 to your computer and use it in GitHub Desktop.
Zig based JSON serializer/deserializer for Playdate
/// Module that wraps up the zig json system for use in playdate
const std = @import("std");
const pdapi = @import("playdate_api_definitions.zig");
pub fn read_from_json_str(
input: []const u8,
comptime thing_to_read: type,
allocator: std.mem.Allocator,
) !thing_to_read
{
const read_it = try std.json.parseFromSlice(
thing_to_read,
allocator,
input,
.{}
);
defer read_it.deinit();
return read_it.value;
}
pub fn read_from_json_file(
filepath: [:0]const u8,
comptime thing_to_read: type,
allocator: std.mem.Allocator,
playdate: *pdapi.PlaydateAPI,
) !thing_to_read
{
var buf2:[2048:0]u8 = undefined;
var fh = playdate.file.open(filepath, pdapi.FILE_READ_DATA);
if (fh == null) {
return error.JsonFileOpenError;
}
const bits_read = playdate.file.read(fh, &buf2, 1024);
const read_buf = buf2[0..@intCast(bits_read)];
return try read_from_json_str(
read_buf,
thing_to_read,
allocator,
);
}
pub fn write_to_json_str(
thing_to_write: anytype,
output: []u8,
allocator: std.mem.Allocator,
) ![]u8
{
var string = std.ArrayList(u8).init(allocator);
defer string.deinit();
try std.json.stringify(thing_to_write, .{}, string.writer());
return try std.fmt.bufPrintZ(output, "{s}\n", .{string.items});
}
pub fn write_to_json_file(
thing_to_write: anytype,
filepath: [:0]const u8,
allocator: std.mem.Allocator,
playdate: *pdapi.PlaydateAPI,
) !void
{
var buf2:[2048:0]u8 = undefined;
const result = try write_to_json_str(thing_to_write, &buf2, allocator);
var fh = playdate.file.open(filepath, pdapi.FILE_WRITE);
_ = playdate.file.write(fh, result.ptr, @intCast(result.len));
_ = playdate.file.close(fh);
_ = playdate.file.flush(fh);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment