aboutsummaryrefslogtreecommitdiff
path: root/test/standalone/windows_argv/lib.zig
blob: 4171d13dab40f06b0308bf7c7f0a3ceb8eb88293 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const std = @import("std");

/// Returns 1 on success, 0 on failure
export fn verify(argc: c_int, argv: [*]const [*:0]const u16) c_int {
    const argv_slice = argv[0..@intCast(argc)];
    testArgv(argv_slice) catch |err| switch (err) {
        error.OutOfMemory => @panic("oom"),
        error.Overflow => @panic("bytes needed to contain args would overflow usize"),
        error.ArgvMismatch => return 0,
    };
    return 1;
}

fn testArgv(expected_args: []const [*:0]const u16) !void {
    var arena_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena_state.deinit();
    const allocator = arena_state.allocator();

    const args = try std.process.argsAlloc(allocator);
    var wtf8_buf = std.array_list.Managed(u8).init(allocator);

    var eql = true;
    if (args.len != expected_args.len) eql = false;

    const min_len = @min(expected_args.len, args.len);
    for (expected_args[0..min_len], args[0..min_len], 0..) |expected_arg, arg_wtf8, i| {
        wtf8_buf.clearRetainingCapacity();
        try std.unicode.wtf16LeToWtf8ArrayList(&wtf8_buf, std.mem.span(expected_arg));
        if (!std.mem.eql(u8, wtf8_buf.items, arg_wtf8)) {
            std.debug.print("{}: expected: \"{f}\"\n", .{ i, std.zig.fmtString(wtf8_buf.items) });
            std.debug.print("{}:   actual: \"{f}\"\n", .{ i, std.zig.fmtString(arg_wtf8) });
            eql = false;
        }
    }
    if (!eql) {
        for (expected_args[min_len..], min_len..) |arg, i| {
            wtf8_buf.clearRetainingCapacity();
            try std.unicode.wtf16LeToWtf8ArrayList(&wtf8_buf, std.mem.span(arg));
            std.debug.print("{}: expected: \"{f}\"\n", .{ i, std.zig.fmtString(wtf8_buf.items) });
        }
        for (args[min_len..], min_len..) |arg, i| {
            std.debug.print("{}:   actual: \"{f}\"\n", .{ i, std.zig.fmtString(arg) });
        }
        const peb = std.os.windows.peb();
        const lpCmdLine: [*:0]u16 = @ptrCast(peb.ProcessParameters.CommandLine.Buffer);
        wtf8_buf.clearRetainingCapacity();
        try std.unicode.wtf16LeToWtf8ArrayList(&wtf8_buf, std.mem.span(lpCmdLine));
        std.debug.print("command line: \"{f}\"\n", .{std.zig.fmtString(wtf8_buf.items)});
        std.debug.print("expected argv:\n", .{});
        std.debug.print("&.{{\n", .{});
        for (expected_args) |arg| {
            wtf8_buf.clearRetainingCapacity();
            try std.unicode.wtf16LeToWtf8ArrayList(&wtf8_buf, std.mem.span(arg));
            std.debug.print("    \"{f}\",\n", .{std.zig.fmtString(wtf8_buf.items)});
        }
        std.debug.print("}}\n", .{});
        return error.ArgvMismatch;
    }
}