zig-clap icon indicating copy to clipboard operation
zig-clap copied to clipboard

Allow parser to take optional secondary std.mem.Allocator parameter

Open maxbol opened this issue 8 months ago • 3 comments

Not sure if this would be interesting for merging into the main tree, but I wrote a little wrapper to allow parsing functions to take the parser allocator as a secondary parameter. Potential use case: washing strings, reordering lists etc.

Of course the pitfall here is that the main program must remember to deallocate these values at some point.

Parsers are still allowed to take ONLY the value parameter. Not sure how zig-ish this is, but at least it doesn't break backward compat.

Merge only if this speaks to you, and lmk if there is something I clean up/rename/make more idiomatic (not a prof zig developer by any means :))

fn parseLowercaseString(value: []const u8, allocator: std.mem.Allocator) ![]const u8 {
    return std.ascii.allocLowerString(allocator, value);
}

fn parseSomethingElse(value: u32) i32 {
    // Still allowed to only take the value as parameter
    ...
}

...

const params = comptime clap.parseParamsComptime(
    \\--to-lower <raw_str>
);

const parsers = comptime {
    .raw_str = parseLowercaseString,
};

maxbol avatar Apr 30 '25 12:04 maxbol

Removed nix crud that was added by mistake

maxbol avatar Apr 30 '25 17:04 maxbol

Yea, giving an allocator to the value parsers is pretty useful. Instead of allowing both signature fn ([]const u8) !T and fn (std.mem.Allocator, []const u8) !T, I'd prefer to always just take the latter. If the function doesn't need the allocator argument it can remove it.

Hejsil avatar Apr 30 '25 18:04 Hejsil

Sounds just fine by me but also like it's going to break current consumers with custom parsers. I'll stick to my own branch for now and let you cook on this 🔥

maxbol avatar Apr 30 '25 20:04 maxbol