#close constant dir

1 messages · Page 1 of 1 (latest)

rare thunder
#

Hey guys, just looking for hints as to avoiding needing to put this value in a variable to call close()


pub fn getXdgConfigHomeDir() !?std.fs.Dir {
    return try std.fs.openDirAbsolute(std.posix.getenv("XDG_CONFIG_HOME") orelse {
        return null;
    }, .{ .iterate = true });
}

// ...
if (try environment.getXdgConfigHomeDir()) |home_dir| {
    const path = try std.fs.path.join(
        alloc,
        &.{ "zfe", "config.json" },
    );
    if (environment.fileExists(home_dir, path)) {
        break :lbl .{
            .home_dir = home_dir,
            .path = path,
        };
    }
    alloc.free(path);
    
    // TODO(18-12-24): Hack to call `.close()` as `home_dir` is a
    // constant.
    var dir = home_dir;
    dir.close();
}
src/config.zig:31:25: error: expected type '*fs.Dir', found '*const fs.Dir'
                home_dir.close();
fallow juniper
#

Try using a pointer capture instead: |*home_dir|. Then dereference it wherever you use it inside the if block: home_dir.*. And then home_dir.*.close()

vivid arrow
crisp jetty
#

afaik there is no way around this, close takes a mutable pointer so it needs a mutable variable. you'll also need an errdefer for closing the dir if join fails

#

iirc this is fine to do, if just a bit awkward. all Dir.close needs the mutability for is to set it to undefined

#

could always just errdefer std.posix.close(home_dir.fd); :P

#

altho why even have that join happen at runtime, why not just const path = "zfe" ++ std.fs.path_str ++ "config.json"; so you dont need an errdefer

rare thunder
#

I assume you meant std.fs.path.sep_str?

crisp jetty
#

oh yea always forget theres a path namespace lol

rare thunder
crisp jetty
#

this is the entirety of Dir.close :P

pub fn close(self: *Dir) void {
    posix.close(self.fd);
    self.* = undefined;
}

there are definitely instances where copying something to var to call a mutable method is wrong, but this is ok (in the current implementation :P)

rare thunder
#

ah, lol. that seems fairly straight forward