Last active
January 18, 2020 10:50
-
-
Save metaleap/57ce1abacb28ac755d891b9df0ee2f9f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub fn exprNumListToBytes(mem: *std.mem.Allocator, maybeNumList: ?[]const Expr) !?[]const u8 { | |
if (maybeNumList) |it| { | |
const bytes = try mem.alloc(u8, it.len); | |
for (it) |expr, i| | |
if (expr.is(.NumInt)) |n| { // .is() expands to: switch(expr) { .NumInt => |n| ..., else => ... } | |
if (n >= 0 and n <= 255) | |
bytes[i] = @intCast(u8, n) | |
else { | |
mem.free(bytes); | |
return null; | |
} | |
} else { | |
mem.free(bytes); | |
return null; | |
}; | |
return bytes; | |
} | |
return null; | |
} |
With defer
it becomes more bearable indeed, thx @daurnimator ! The 2 extra line costs of var ok
and ok = true
come out for the current example to the same overall LoC (-1) but at least if additional else
s were to come into play it would amortize decently.
pub fn listToBytes(mem: *std.mem.Allocator, maybeNumList: ?[]const Expr) !?[]const u8 {
if (maybeNumList) |it| {
var ok = false;
const bytes = try mem.alloc(u8, it.len);
defer if (!ok) mem.free(bytes);
for (it) |expr, i|
if (expr.is(.NumInt)) |n| { // .is() expands to: switch(expr) { .NumInt => |n| ..., else => ... }
if (n >= 0 and n <= 255)
bytes[i] = @intCast(u8, n)
else
return null;
} else
return null;
ok = true;
return bytes;
}
return null;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With
goto
could do instead: