@@ -51,24 +51,30 @@ 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- // Dupe all string fields so deinit can safely free them all.
61- var settings = Settings {
62- .version_map_url = try allocator .dupe (u8 , default .version_map_url ),
63- .zls_vmu = try allocator .dupe (u8 , default .zls_vmu ),
64- .mirror_list_url = try allocator .dupe (u8 , default .mirror_list_url ),
65- .use_color = default .use_color ,
66- .always_force_install = default .always_force_install ,
67- .preferred_mirror = try allocator .dupe (u8 , default .preferred_mirror ),
68- .mirror_updated_at = default .mirror_updated_at ,
69- .proxy = try allocator .dupe (u8 , default .proxy ),
70- .path = path ,
71- };
75+ // Create new settings file with defaults; all strings must be heap-owned.
76+ var settings = try default .toOwned (allocator );
77+ settings .path = path ;
7278 try settings .save (allocator , io );
7379 return settings ;
7480 },
@@ -87,8 +93,8 @@ pub const Settings = struct {
8793 content ,
8894 .{ .ignore_unknown_fields = true },
8995 ) catch {
90- // If parsing fails, return defaults
91- var settings = default ;
96+ // If parsing fails, return defaults; all strings must be heap-owned.
97+ var settings = try default . toOwned ( allocator ) ;
9298 settings .path = path ;
9399 return settings ;
94100 };
0 commit comments