mirror of
https://github.com/ziglang/zig.git
synced 2024-11-27 07:32:44 +00:00
std: make parsing an unsigned number generic
This commit is contained in:
parent
b68aee4f34
commit
6a7f3c8df7
@ -23,7 +23,7 @@ pub fn main(args: [][]u8) -> %void {
|
||||
return err;
|
||||
};
|
||||
|
||||
const guess = io.parse_u64(line_buf[0...line_len - 1], 10) %% {
|
||||
const guess = io.parse_unsigned(u8)(line_buf[0...line_len - 1], 10) %% {
|
||||
%%io.stdout.printf("Invalid number.\n");
|
||||
continue;
|
||||
};
|
||||
|
10
std/io.zig
10
std/io.zig
@ -211,8 +211,8 @@ pub struct InStream {
|
||||
pub error InvalidChar;
|
||||
pub error Overflow;
|
||||
|
||||
pub fn parse_u64(buf: []u8, radix: u8) -> %u64 {
|
||||
var x : u64 = 0;
|
||||
pub fn parse_unsigned(T: type)(buf: []u8, radix: u8) -> %T {
|
||||
var x: T = 0;
|
||||
|
||||
for (buf) |c| {
|
||||
const digit = char_to_digit(c);
|
||||
@ -222,12 +222,12 @@ pub fn parse_u64(buf: []u8, radix: u8) -> %u64 {
|
||||
}
|
||||
|
||||
// x *= radix
|
||||
if (@mul_with_overflow(u64, x, radix, &x)) {
|
||||
if (@mul_with_overflow(T, x, radix, &x)) {
|
||||
return error.Overflow;
|
||||
}
|
||||
|
||||
// x += digit
|
||||
if (@add_with_overflow(u64, x, digit, &x)) {
|
||||
if (@add_with_overflow(T, x, digit, &x)) {
|
||||
return error.Overflow;
|
||||
}
|
||||
}
|
||||
@ -404,7 +404,7 @@ pub fn buf_print_f64(out_buf: []u8, x: f64, decimals: isize) -> isize {
|
||||
|
||||
#attribute("test")
|
||||
fn parse_u64_digit_too_big() {
|
||||
parse_u64("123a", 10) %% |err| {
|
||||
parse_unsigned(u64)("123a", 10) %% |err| {
|
||||
if (err == error.InvalidChar) return;
|
||||
unreachable{};
|
||||
};
|
||||
|
Loading…
Reference in New Issue
Block a user