From fb76e02c59b1502c3be557d6c8c94dba2bf2c829 Mon Sep 17 00:00:00 2001 From: Nick Treleaven Date: Mon, 20 Jul 2020 15:44:35 +0100 Subject: [PATCH] builtin: speed up string.clone() by using C.memcpy (#5837) --- vlib/builtin/string.v | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index 1e2bdb7131..b87f04f11e 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -85,9 +85,6 @@ pub fn tos(s byteptr, len int) string { } pub fn tos_clone(s byteptr) string { - if s == 0 { - panic('tos: nil string') - } return tos2(s).clone() } @@ -131,13 +128,11 @@ fn (a string) clone_static() string { pub fn (a string) clone() string { mut b := string{ - str: malloc(a.len + 1) + str: unsafe {malloc(a.len + 1)} len: a.len } - for i in 0..a.len { - b.str[i] = a.str[i] - } unsafe { + C.memcpy(b.str, a.str, a.len) b.str[a.len] = `\0` } return b @@ -152,12 +147,7 @@ pub fn (s string) cstr() byteptr { // cstring_to_vstring creates a copy of cstr and turns it into a v string pub fn cstring_to_vstring(cstr byteptr) string { - unsafe { - slen := C.strlen(charptr(cstr)) - mut s := byteptr(memdup(cstr, slen + 1)) - s[slen] = `\0` - return tos(s, slen) - } + return tos_clone(cstr) } pub fn (s string) replace_once(rep, with string) string {