Skip to content

Commit 96590f9

Browse files
committed
feat(settings): add owned string allocation for Settings struct
- Add `toOwned` method to Settings that creates heap-allocated copies of all string fields - Update load function to use heap-owned string allocations by default when creating new settings files - Update error handling to ensure all string fields are heap-owned when parsing fails and defaults are used - Add documentation for the new toOwned method explaining memory ownership requirements
1 parent c6b47c6 commit 96590f9

1 file changed

Lines changed: 20 additions & 4 deletions

File tree

src/settings.zig

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,29 @@ pub const Settings = struct {
5151
proxy: []const u8 = "",
5252
};
5353

54+
/// Return a copy of this Settings with all string fields heap-allocated.
55+
/// The caller owns the returned value and must free all string fields.
56+
fn toOwned(self: Settings, allocator: std.mem.Allocator) !Settings {
57+
return Settings{
58+
.version_map_url = try allocator.dupe(u8, self.version_map_url),
59+
.zls_vmu = try allocator.dupe(u8, self.zls_vmu),
60+
.mirror_list_url = try allocator.dupe(u8, self.mirror_list_url),
61+
.use_color = self.use_color,
62+
.always_force_install = self.always_force_install,
63+
.preferred_mirror = try allocator.dupe(u8, self.preferred_mirror),
64+
.mirror_updated_at = self.mirror_updated_at,
65+
.proxy = try allocator.dupe(u8, self.proxy),
66+
.path = self.path,
67+
};
68+
}
69+
5470
/// Load settings from a JSON file, or create with defaults if not found.
5571
/// Takes ownership of the `path` parameter.
5672
pub fn load(allocator: std.mem.Allocator, io: std.Io, path: []const u8) !Settings {
5773
const file = std.Io.Dir.cwd().openFile(io, path, .{}) catch |err| switch (err) {
5874
error.FileNotFound => {
59-
// Create new settings file with defaults
60-
var settings = default;
75+
// Create new settings file with defaults; all strings must be heap-owned.
76+
var settings = try default.toOwned(allocator);
6177
settings.path = path;
6278
try settings.save(allocator, io);
6379
return settings;
@@ -77,8 +93,8 @@ pub const Settings = struct {
7793
content,
7894
.{ .ignore_unknown_fields = true },
7995
) catch {
80-
// If parsing fails, return defaults
81-
var settings = default;
96+
// If parsing fails, return defaults; all strings must be heap-owned.
97+
var settings = try default.toOwned(allocator);
8298
settings.path = path;
8399
return settings;
84100
};

0 commit comments

Comments
 (0)