Put user in control of parser lifetime

dev
Louis Pearson 2022-08-04 17:06:45 -06:00
parent 91d78d9c52
commit e93618602d
2 changed files with 20 additions and 8 deletions

View File

@ -23,14 +23,24 @@
const std = @import("std"); const std = @import("std");
pub fn parse(alloc: std.mem.Allocator, ldtk_file: []const u8) !Root { alloc: std.mem.Allocator,
var parser = std.json.Parser.init(alloc, false); root: Root,
defer parser.deinit(); parser: std.json.Parser,
value_tree: std.json.ValueTree,
var value_tree = try parser.parse(ldtk_file); pub fn parse(alloc: std.mem.Allocator, ldtk_file: []const u8) !@This() {
defer value_tree.deinit(); var this: @This() = undefined;
this.alloc = alloc;
this.parser = std.json.Parser.init(alloc, false);
this.value_tree = try this.parser.parse(ldtk_file);
this.root = try Root.fromJSON(alloc, this.value_tree.root);
return this;
}
return Root.fromJSON(alloc, value_tree.root); pub fn deinit(this: *@This()) void {
this.root.deinit(this.alloc);
this.value_tree.deinit();
this.parser.deinit();
} }
/// 1. LDtk Json root /// 1. LDtk Json root

View File

@ -5,8 +5,10 @@ const LDtk = @import("LDtk.zig");
test "load default/empty ldtk file" { test "load default/empty ldtk file" {
const empty_ldtk = @embedFile("test.ldtk"); const empty_ldtk = @embedFile("test.ldtk");
const ldtk_root = try LDtk.parse(testing.allocator, empty_ldtk); var ldtk = try LDtk.parse(testing.allocator, empty_ldtk);
defer ldtk_root.deinit(testing.allocator); defer ldtk.deinit();
var ldtk_root = ldtk.root;
try testing.expectEqualStrings("1.1.3", ldtk_root.jsonVersion); try testing.expectEqualStrings("1.1.3", ldtk_root.jsonVersion);
try testing.expectEqualStrings("#40465B", ldtk_root.bgColor); try testing.expectEqualStrings("#40465B", ldtk_root.bgColor);