summaryrefslogtreecommitdiff
path: root/clap/args.zig
diff options
context:
space:
mode:
authorGravatar Jimmi Holst Christensen2019-10-06 17:20:56 +0200
committerGravatar Jimmi Holst Christensen2019-10-06 17:20:56 +0200
commitf3eb797336c1bbdae391657ef6ac54e4015b5fde (patch)
tree0f99b8a43adddcadca24a2ec0b47b779ef923904 /clap/args.zig
parentDelete download-zig.sh (diff)
downloadzig-clap-f3eb797336c1bbdae391657ef6ac54e4015b5fde.tar.gz
zig-clap-f3eb797336c1bbdae391657ef6ac54e4015b5fde.tar.xz
zig-clap-f3eb797336c1bbdae391657ef6ac54e4015b5fde.zip
fmt, mv src/ clap/ and run fmt on build
Diffstat (limited to 'clap/args.zig')
-rw-r--r--clap/args.zig71
1 files changed, 71 insertions, 0 deletions
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 @@
1const builtin = @import("builtin");
2const std = @import("std");
3
4const debug = std.debug;
5const heap = std.heap;
6const mem = std.mem;
7const process = std.process;
8
9/// An example of what methods should be implemented on an arg iterator.
10pub const ExampleArgIterator = struct {
11 const Error = error{};
12
13 pub fn next(iter: *ExampleArgIterator) Error!?[]const u8 {
14 return "2";
15 }
16};
17
18/// An argument iterator which iterates over a slice of arguments.
19/// This implementation does not allocate.
20pub const SliceIterator = struct {
21 const Error = error{};
22
23 args: []const []const u8,
24 index: usize = 0,
25
26 pub fn next(iter: *SliceIterator) Error!?[]const u8 {
27 if (iter.args.len <= iter.index)
28 return null;
29
30 defer iter.index += 1;
31 return iter.args[iter.index];
32 }
33};
34
35test "clap.args.SliceIterator" {
36 const args = [_][]const u8{ "A", "BB", "CCC" };
37 var iter = SliceIterator{ .args = args };
38
39 for (args) |a| {
40 const b = try iter.next();
41 debug.assert(mem.eql(u8, a, b.?));
42 }
43}
44
45/// An argument iterator which wraps the ArgIterator in ::std.
46/// On windows, this iterator allocates.
47pub const OsIterator = struct {
48 const Error = process.ArgIterator.NextError;
49
50 arena: heap.ArenaAllocator,
51 args: process.ArgIterator,
52
53 pub fn init(allocator: *mem.Allocator) OsIterator {
54 return OsIterator{
55 .arena = heap.ArenaAllocator.init(allocator),
56 .args = process.args(),
57 };
58 }
59
60 pub fn deinit(iter: *OsIterator) void {
61 iter.arena.deinit();
62 }
63
64 pub fn next(iter: *OsIterator) Error!?[]const u8 {
65 if (builtin.os == builtin.Os.windows) {
66 return try iter.args.next(&iter.arena.allocator) orelse return null;
67 } else {
68 return iter.args.nextPosix();
69 }
70 }
71};