Skip to content

Commit e782ea2

Browse files
authored
fix: no segment fault when no env (#8)
1 parent 303a130 commit e782ea2

File tree

2 files changed

+20
-9
lines changed

2 files changed

+20
-9
lines changed

examples/build.zig

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,11 @@ pub fn build(b: *std.Build) void {
2121

2222
const exe = b.addExecutable(.{
2323
.name = exe_name,
24-
.root_source_file = b.path(example_path),
25-
.target = target,
26-
.optimize = optimize,
24+
.root_module = b.createModule(.{
25+
.root_source_file = b.path(example_path),
26+
.target = target,
27+
.optimize = optimize,
28+
}),
2729
});
2830
const mod = b.addModule("struct-env", .{
2931
.root_source_file = b.path("../src/lib.zig"),

src/lib.zig

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ pub const StructEnv = struct {
3030
allocator: std.mem.Allocator,
3131
/// Common Prefix
3232
prefix: ?[]const u8,
33+
/// Whether env_map has been initialized and must be deinitialized
34+
env_inited: bool,
3335

3436
const Self = @This();
3537

@@ -42,21 +44,27 @@ pub const StructEnv = struct {
4244
.env_map = undefined,
4345
.allocator = allocator,
4446
.prefix = prefix,
47+
.env_inited = false,
4548
};
4649
}
4750

4851
pub fn deinit(self: *Self) void {
49-
self.env_map.deinit();
52+
if (self.env_inited) {
53+
self.env_map.deinit();
54+
self.env_inited = false;
55+
}
5056
}
5157

5258
pub fn fromEnv(self: *Self, comptime T: type) !T {
53-
var env_map = try std.process.getEnvMap(self.allocator);
54-
errdefer env_map.deinit();
55-
59+
const env_map = try std.process.getEnvMap(self.allocator);
5660
self.env_map = env_map;
61+
self.env_inited = true;
5762

5863
var value: T = undefined;
59-
try self.deserializeInto(&value, null);
64+
self.deserializeInto(&value, null) catch |e| {
65+
self.deinit();
66+
return e;
67+
};
6068

6169
return value;
6270
}
@@ -68,6 +76,7 @@ pub const StructEnv = struct {
6876
/// This is for unittest mock!
6977
fn fromEnvMock(self: *Self, comptime T: type, env_map: std.process.EnvMap) !T {
7078
self.env_map = env_map;
79+
self.env_inited = true;
7180

7281
var value: T = undefined;
7382
try self.deserializeInto(&value, null);
@@ -205,7 +214,7 @@ pub const StructEnv = struct {
205214
else => switch (@typeInfo(C)) {
206215
.bool => try utils.str2bool(self.allocator, s),
207216
.int => try std.fmt.parseInt(C, s, 0),
208-
.float => try std.fmt.parseFloat(C, s, 0),
217+
.float => try std.fmt.parseFloat(C, s),
209218
else => @compileError("Unsupported deserialization type" ++ @typeName(C) ++ "\n"),
210219
},
211220
};

0 commit comments

Comments
 (0)