From f3eb797336c1bbdae391657ef6ac54e4015b5fde Mon Sep 17 00:00:00 2001 From: Jimmi Holst Christensen Date: Sun, 6 Oct 2019 17:20:56 +0200 Subject: fmt, mv src/ clap/ and run fmt on build --- clap/args.zig | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 clap/args.zig (limited to 'clap/args.zig') diff --git a/clap/args.zig b/clap/args.zig new file mode 100644 index 0000000..4234ada --- /dev/null +++ b/clap/args.zig @@ -0,0 +1,71 @@ +const builtin = @import("builtin"); +const std = @import("std"); + +const debug = std.debug; +const heap = std.heap; +const mem = std.mem; +const process = std.process; + +/// An example of what methods should be implemented on an arg iterator. +pub const ExampleArgIterator = struct { + const Error = error{}; + + pub fn next(iter: *ExampleArgIterator) Error!?[]const u8 { + return "2"; + } +}; + +/// An argument iterator which iterates over a slice of arguments. +/// This implementation does not allocate. +pub const SliceIterator = struct { + const Error = error{}; + + args: []const []const u8, + index: usize = 0, + + pub fn next(iter: *SliceIterator) Error!?[]const u8 { + if (iter.args.len <= iter.index) + return null; + + defer iter.index += 1; + return iter.args[iter.index]; + } +}; + +test "clap.args.SliceIterator" { + const args = [_][]const u8{ "A", "BB", "CCC" }; + var iter = SliceIterator{ .args = args }; + + for (args) |a| { + const b = try iter.next(); + debug.assert(mem.eql(u8, a, b.?)); + } +} + +/// An argument iterator which wraps the ArgIterator in ::std. +/// On windows, this iterator allocates. +pub const OsIterator = struct { + const Error = process.ArgIterator.NextError; + + arena: heap.ArenaAllocator, + args: process.ArgIterator, + + pub fn init(allocator: *mem.Allocator) OsIterator { + return OsIterator{ + .arena = heap.ArenaAllocator.init(allocator), + .args = process.args(), + }; + } + + pub fn deinit(iter: *OsIterator) void { + iter.arena.deinit(); + } + + pub fn next(iter: *OsIterator) Error!?[]const u8 { + if (builtin.os == builtin.Os.windows) { + return try iter.args.next(&iter.arena.allocator) orelse return null; + } else { + return iter.args.nextPosix(); + } + } +}; -- cgit v1.2.3