Hi all,
I’m currently trying to parse a JSON file containing an array of CPU tests :
const std = @import("std");
// This file reads a serie of JSON files,
// each containing 1000 tests for a given SM83 instruction.
const CpuState = struct {
pc: u16,
sp: u16,
a: u8,
b: u8,
c: u8,
d: u8,
e: u8,
f: u8,
h: u8,
l: u8,
ime: u8,
ie: ?u8 = null,
ram: [][2]u16,
};
const OpTest = struct {
name: []const u8,
initial: CpuState,
final: CpuState,
};
const test_path = "./tests/sm83/v1";
fn parseJsonFile(allocator: std.mem.Allocator, filename: []const u8) !std.json.Parsed([]*OpTest) {
var file = try std.fs.cwd().openFile(filename, .{});
defer file.close();
const contents = try file.readToEndAlloc(allocator, std.math.maxInt(usize));
defer allocator.free(contents);
std.debug.print("Content {s}\n", .{contents});
const result = try std.json.parseFromSlice([]*OpTest, allocator, contents, .{
.ignore_unknown_fields = true,
.allocate = .alloc_always,
});
return result;
}
test "Open sample file (NOP)" {
const allocator = std.testing.allocator;
const result = try parseJsonFile(allocator, test_path ++ "/00.json");
defer result.deinit();
const opsuite = result.value;
std.debug.print("opsuite: {any}\n", .{opsuite});
std.debug.print("name: {s}\n", .{opsuite[0].name});
std.debug.print("initial: {any}\n", .{opsuite[0].initial});
std.debug.print("final: {any}\n", .{opsuite[0].final});
}
After a long serie of test and tweaks, I can finally run the test without errors.
But I’ve got a serious doubt on the .allocate = .alloc_always
parsing option.
When removing it, of course some of the arrays are not correctly initialized.
But with this option activated, am I sure that the testing allocator is used for all initializations during the construction of OpTest
and CpuState
objects ?
Looking at the source, I’m not really sure, but I’m also a bit lost
If this is the case, the testing allocator should throw errors when a memory leak occurs, correct ?
Thanks in advance for your help.