dicer

dicer: Dice roll app
Log | Files | Refs | README

commit 6700b341468b219f2cfc748fa59a9e38367aea7d
parent 78859e9353d148fbf0e72d6d7379884b1484634f
Author: Martin Ashby <martin@ashbysoft.com>
Date:   Fri,  9 Aug 2024 23:04:49 +0100

Improved error handling

Diffstat:
Msrc/main.zig | 37+++----------------------------------
Msrc/root.zig | 41+++++++++++++++++++++++++++++++++++++----
2 files changed, 40 insertions(+), 38 deletions(-)

diff --git a/src/main.zig b/src/main.zig @@ -1,40 +1,9 @@ const std = @import("std"); - -const usage = - \\Usage: - \\ dicer XdY - \\ - \\Rolls X dice with Y - \\ -; +const dicer = @import("root.zig").dicer; pub fn main() !void { var args = std.process.args(); _ = args.skip(); // program name - const dice_str = args.next() orelse { - try printUsage(); - return; - }; - - var spl = std.mem.splitScalar(u8, dice_str, 'd'); - const count = try std.fmt.parseInt(u64, spl.first(), 10); - const sides = try std.fmt.parseInt(u64, spl.next() orelse "6", 10); - var wtr = std.io.getStdOut().writer(); - try wtr.writeAll("Dice roll: "); - var total: u64 = 0; - for (0..count) |_| { - const res = roll(sides); - try std.fmt.format(wtr, "{} ", .{res}); - total += res; - } - try std.fmt.format(wtr, " total: {}", .{total}); - try wtr.writeByte('\n'); -} - -fn roll(dsize: u64) u64 { - return (std.crypto.random.int(u64) % dsize) + 1; -} - -fn printUsage() !void { - try std.fmt.format(std.io.getStdOut(), usage, .{}); + const wtr = std.io.getStdOut().writer(); + try dicer(&args, wtr); } diff --git a/src/root.zig b/src/root.zig @@ -1,10 +1,43 @@ const std = @import("std"); const testing = std.testing; -export fn add(a: i32, b: i32) i32 { - return a + b; +pub fn dicer(args: anytype, wtr: anytype) !void { + doDicer(args, wtr) catch |e| switch (e) { + error.MissingArg, error.InvalidCharacter => { + try printUsage(wtr); + return; + }, + else => return e, + }; } -test "basic add functionality" { - try testing.expect(add(3, 7) == 10); +fn doDicer(args: anytype, wtr: anytype) !void { + const dice_str = args.next() orelse return error.MissingArg; + var spl = std.mem.splitScalar(u8, dice_str, 'd'); + const count = try std.fmt.parseInt(u64, spl.first(), 10); + const sides = try std.fmt.parseInt(u64, spl.next() orelse "6", 10); + + try wtr.writeAll("Dice roll: "); + var total: u64 = 0; + for (0..count) |_| { + const res = roll(sides); + try std.fmt.format(wtr, "{} ", .{res}); + total += res; + } + try std.fmt.format(wtr, " total: {}", .{total}); + try wtr.writeByte('\n'); +} + +fn roll(dsize: u64) u64 { + return (std.crypto.random.int(u64) % dsize) + 1; +} + +fn printUsage(wtr: anytype) !void { + try std.fmt.format(wtr, + \\Usage: + \\ dicer XdY + \\ + \\Rolls X dice with Y + \\ + , .{}); }