Learning Zig from the official language reference.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
zig-langref/errdefer.zig

52 lines
1.2 KiB

const std = @import("std");
const math = std.math;
const debug = std.debug;
const testing = std.testing;
// inferred error set
fn parseU64(buf: []const u8, radix: u8) !u64 {
var res: u64 = 0;
errdefer {
debug.print("There was an error\n", .{});
}
for (buf) |c| {
const digit = charToDigit(c);
if (digit >= radix) {
return error.InvalidChar;
}
if (@mulWithOverflow(u64, res, radix, &res)) {
return error.Overflow;
}
if (@addWithOverflow(u64, res, digit, &res)) {
return error.Overflow;
}
}
return res;
}
fn charToDigit(c: u8) u8 {
return switch (c) {
'0'...'9' => c - '0',
'a'...'z' => c - 'a' + 10,
'A'...'Z' => c - 'A' + 10,
else => math.maxInt(u8),
};
}
test "errdefer" {
const valid_res = try parseU64("12345", 10);
testing.expectEqual(valid_res, 12345);
if (parseU64("abc123", 10)) |_| {
unreachable;
} else |err| switch (err) {
error.InvalidChar => debug.print("input contains an invalid character for the radix\n", .{}),
error.Overflow => debug.print("input is too big for the given radix\n", .{}),
}
}