From 9730164613aab8c3dffb12e32d31833d390d21cc Mon Sep 17 00:00:00 2001 From: penguindark <57967770+penguindark@users.noreply.github.com> Date: Sun, 8 Dec 2019 21:22:33 +0100 Subject: [PATCH] atoi: fix leading zeros in string to int conversion --- vlib/builtin/string_int_test.v | 16 ++++++++++++++++ vlib/strconv/atoi.v | 5 +++++ 2 files changed, 21 insertions(+) diff --git a/vlib/builtin/string_int_test.v b/vlib/builtin/string_int_test.v index 5e969832a4..9d5b7df3a6 100644 --- a/vlib/builtin/string_int_test.v +++ b/vlib/builtin/string_int_test.v @@ -1,9 +1,25 @@ fn test_common_atoi() { + // test common cases assert "70zzz".int() == 70 assert "2901issue".int() == 2901 assert '234232w'.int() == 234232 assert '-9009x'.int() == -9009 assert '0y'.int() == 0 + + // test lead zeros + assert '0000012'.int() == 12 + assert '-0000012'.int() == -12 + assert '0x001F'.int() == 31 + assert '-0x001F'.int() == -31 + assert '0x001f'.int() == 31 + assert '0o00011'.int() == 9 + assert '0b00001001'.int() == 9 + + // test underscore in string + assert '-10_000'.int() == -10000 + assert '-0x00_0_f_ff'.int() == -0xfff + assert '10_000_000'.int() == 10000000 + for n in -10000 .. 100000 { s := n.str()+"z" assert s.int() == n diff --git a/vlib/strconv/atoi.v b/vlib/strconv/atoi.v index b1861249de..da8c20f87e 100644 --- a/vlib/strconv/atoi.v +++ b/vlib/strconv/atoi.v @@ -50,6 +50,11 @@ pub fn common_parse_uint(s string, _base int, _bit_size int, error_on_non_digit base = 16 start_index += 2 } + // manage leading zeros in decimal base's numbers + else if s.len >=2 && ( s[1] >= `0` && s[1] <= `9`) { + base = 10 + start_index ++ + } else { base = 8 start_index++