fix allocation bug and add test for json file to sim config
This commit is contained in:
parent
085deafc74
commit
46067abda5
1 changed files with 53 additions and 33 deletions
28
src/io.zig
28
src/io.zig
|
|
@ -20,18 +20,19 @@ const JsonSim = struct {
|
|||
};
|
||||
|
||||
pub fn jsonFileToSimConfig(
|
||||
file_path: []u8,
|
||||
file_path: []const u8,
|
||||
allocator: std.mem.Allocator,
|
||||
io: std.Io,
|
||||
) !drone.QuadCopterSim {
|
||||
const cwd = std.Io.Dir.cwd();
|
||||
const file = try cwd.openFile(io, file_path, .{ .mode = .read });
|
||||
const file = try cwd.openFile(io, file_path, .{ .mode = .read_only });
|
||||
defer file.close(io);
|
||||
|
||||
var file_reader = file.reader(io, &.{});
|
||||
const json = try file_reader.interface.allocRemaining(allocator, .unlimited);
|
||||
defer allocator.free(json);
|
||||
|
||||
return jsonStringToSimConfig(json, allocator, io);
|
||||
return jsonStringToSimConfig(json, allocator);
|
||||
}
|
||||
|
||||
pub fn jsonStringToSimConfig(
|
||||
|
|
@ -110,8 +111,10 @@ test "Verify parse from Json String works" {
|
|||
\\}
|
||||
;
|
||||
const gpa = std.testing.allocator;
|
||||
const sim_config = try jsonStringToSimConfig(TEST_JSON_STRING, gpa);
|
||||
const string_sim_config = try jsonStringToSimConfig(TEST_JSON_STRING, gpa);
|
||||
|
||||
const validate_sim_config = struct {
|
||||
pub fn validate(sim_config: drone.QuadCopterSim) !void {
|
||||
try std.testing.expectApproxEqAbs(0.5, sim_config.drone.mass_kg, 1e-12);
|
||||
try std.testing.expectApproxEqAbs(0.25, sim_config.drone.drag_coeff, 1e-12);
|
||||
try std.testing.expect(vec3.mat3ApproxEq(sim_config.drone.moment_of_inertia, vec3.Mat3F64.identity(), 1e-12));
|
||||
|
|
@ -147,3 +150,20 @@ test "Verify parse from Json String works" {
|
|||
try std.testing.expect(sim_config.propellers[i].direction == expected_direction[i]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
try validate_sim_config.validate(string_sim_config);
|
||||
|
||||
{
|
||||
const cwd = std.Io.Dir.cwd();
|
||||
const file = try cwd.createFile(std.testing.io, "/tmp/zig_json_config_test.json", .{});
|
||||
// Don't forget to close the file at the end.
|
||||
defer file.close(std.testing.io);
|
||||
// Do things with the file ...
|
||||
_ = try file.writePositionalAll(std.testing.io, TEST_JSON_STRING, 0);
|
||||
}
|
||||
|
||||
const file_sim_config = try jsonFileToSimConfig("/tmp/zig_json_config_test.json", gpa, std.testing.io);
|
||||
|
||||
try validate_sim_config.validate(file_sim_config);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue