pub const Wasi = struct allocator: Allocatorindex: usizeargs: [][:0]u8pub fn init(allocator: Allocator) Wasi.InitError!WasiYou must call deinit to free the internal buffer of the iterator after you are done.
fn internalInit(allocator: Allocator) Wasi.InitError![][: 0]u8pub fn next(self: *Wasi) ?[: 0]const u8pub fn skip(self: *Wasi) boolpub fn deinit(self: *Wasi) voidCall to free the internal buffer of the iterator.
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451 pub const Wasi = struct {
allocator: Allocator,
index: usize,
args: [][:0]u8,
pub const InitError = error{OutOfMemory} || std.posix.UnexpectedError;
/// You must call deinit to free the internal buffer of the
/// iterator after you are done.
pub fn init(allocator: Allocator) Wasi.InitError!Wasi {
const fetched_args = try Wasi.internalInit(allocator);
return Wasi{
.allocator = allocator,
.index = 0,
.args = fetched_args,
};
}
fn internalInit(allocator: Allocator) Wasi.InitError![][:0]u8 {
var count: usize = undefined;
var buf_size: usize = undefined;
switch (std.os.wasi.args_sizes_get(&count, &buf_size)) {
.SUCCESS => {},
else => |err| return std.posix.unexpectedErrno(err),
}
if (count == 0) {
return &[_][:0]u8{};
}
const argv = try allocator.alloc([*:0]u8, count);
defer allocator.free(argv);
const argv_buf = try allocator.alloc(u8, buf_size);
switch (std.os.wasi.args_get(argv.ptr, argv_buf.ptr)) {
.SUCCESS => {},
else => |err| return std.posix.unexpectedErrno(err),
}
var result_args = try allocator.alloc([:0]u8, count);
var i: usize = 0;
while (i < count) : (i += 1) {
result_args[i] = std.mem.sliceTo(argv[i], 0);
}
return result_args;
}
pub fn next(self: *Wasi) ?[:0]const u8 {
if (self.index == self.args.len) return null;
const arg = self.args[self.index];
self.index += 1;
return arg;
}
pub fn skip(self: *Wasi) bool {
if (self.index == self.args.len) return false;
self.index += 1;
return true;
}
/// Call to free the internal buffer of the iterator.
pub fn deinit(self: *Wasi) void {
// Nothing is allocated when there are no args
if (self.args.len == 0) return;
const last_item = self.args[self.args.len - 1];
const last_byte_addr = @intFromPtr(last_item.ptr) + last_item.len + 1; // null terminated
const first_item_ptr = self.args[0].ptr;
const len = last_byte_addr - @intFromPtr(first_item_ptr);
self.allocator.free(first_item_ptr[0..len]);
self.allocator.free(self.args);
}
}