From dc2c62807ab7e741599255f7eb5ed6eff0c5cad4 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Fri, 25 Oct 2019 23:41:18 +0300 Subject: [PATCH] string: faster int() --- vlib/builtin/cfns.v | 1 + vlib/builtin/string.v | 20 ++++++++++++++++++++ vlib/builtin/string_test.v | 10 ++++++++++ 3 files changed, 31 insertions(+) diff --git a/vlib/builtin/cfns.v b/vlib/builtin/cfns.v index e5f973af86..39bd9bdac8 100644 --- a/vlib/builtin/cfns.v +++ b/vlib/builtin/cfns.v @@ -10,6 +10,7 @@ fn C.qsort(voidptr, int, int, voidptr) fn C.sprintf(a ...voidptr) byteptr fn C.strlen(s byteptr) int +fn C.isdigit(s byteptr) bool diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index bb51dfb8e5..4418a77215 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -176,9 +176,29 @@ pub fn (s string) replace(rep, with string) string { return tos(b, new_len) } +/* pub fn (s string) int() int { return strconv.parse_int(s, 0, 32) } +*/ + +pub fn (s string) int() int { + mut neg := false + mut i := 0 + if s[0] == `-` { + neg = true + i++ + } + else if s[0] == `+` { + i++ + } + mut n := 0 + for C.isdigit(s[i]) { + n = 10 * n - int(s[i] - `0`) + i++ + } + return if neg { n } else { -n } +} pub fn (s string) i64() i64 { diff --git a/vlib/builtin/string_test.v b/vlib/builtin/string_test.v index 4145aba5cb..7619027940 100644 --- a/vlib/builtin/string_test.v +++ b/vlib/builtin/string_test.v @@ -482,3 +482,13 @@ fn test_escape() { //println("\"$a") } +fn test_atoi() { + assert '234232'.int() == 234232 + assert '-9009'.int() == -9009 + assert '0'.int() == 0 + for n in -10000 .. 100000 { + s := n.str() + assert s.int() == n + } +} +