aboutsummaryrefslogtreecommitdiff
path: root/std
diff options
context:
space:
mode:
authorAndrew Kelley <superjoe30@gmail.com>2017-09-26 19:40:51 -0400
committerAndrew Kelley <superjoe30@gmail.com>2017-09-26 19:40:51 -0400
commit224cd8a01eff193e7683362c7743b939b392c75a (patch)
treed0787e85d6bdbc4e36c2c50ed7538aac05ad6c6c /std
parent768af66977df40529e7639cd531deb49f6e500ae (diff)
downloadzig-224cd8a01eff193e7683362c7743b939b392c75a.tar.gz
zig-224cd8a01eff193e7683362c7743b939b392c75a.zip
add fmt.parseInt
Diffstat (limited to 'std')
-rw-r--r--std/fmt/index.zig20
1 files changed, 20 insertions, 0 deletions
diff --git a/std/fmt/index.zig b/std/fmt/index.zig
index 050914d2c4..27ab3dd0dd 100644
--- a/std/fmt/index.zig
+++ b/std/fmt/index.zig
@@ -364,6 +364,26 @@ fn formatIntCallback(context: &FormatIntBuf, bytes: []const u8) -> bool {
return true;
}
+pub fn parseInt(comptime T: type, buf: []const u8, radix: u8) -> %T {
+ if (!T.is_signed)
+ return parseUnsigned(T, buf, radix);
+ if (buf.len == 0)
+ return T(0);
+ if (buf[0] == '-') {
+ return math.negate(%return parseUnsigned(T, buf[1..], radix));
+ } else if (buf[0] == '+') {
+ return parseUnsigned(T, buf[1..], radix);
+ } else {
+ return parseUnsigned(T, buf, radix);
+ }
+}
+
+test "fmt.parseInt" {
+ assert(%%parseInt(i32, "-10", 10) == -10);
+ assert(%%parseInt(i32, "+10", 10) == 10);
+ assert(if (parseInt(i32, " 10", 10)) |_| false else |err| err == error.InvalidChar);
+}
+
pub fn parseUnsigned(comptime T: type, buf: []const u8, radix: u8) -> %T {
var x: T = 0;