string: faster int()

pull/2356/head
Alexander Medvednikov 2019-10-25 23:41:18 +03:00
parent 5510327d70
commit dc2c62807a
3 changed files with 31 additions and 0 deletions

View File

@ -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

View File

@ -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 {

View File

@ -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
}
}