strings: optimization of repeat + repeat_string()

pull/3852/head
Delyan Angelov 2020-02-26 14:22:12 +02:00 committed by GitHub
parent 39429f7ac9
commit 7a72167eb7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 59 additions and 11 deletions

View File

@ -1,11 +0,0 @@
module strings
pub fn repeat(c byte, n int) string {
if n <= 0 {
return ''
}
mut arr := [c].repeat(n + 1)
arr[n] = `\0`
return string(arr,n)
}

View File

@ -0,0 +1,34 @@
module strings
// strings.repeat - fill a string with `n` repetitions of the character `c`
pub fn repeat(c byte, n int) string {
if n <= 0 {
return ''
}
mut bytes := &byte(0)
unsafe { bytes = malloc(n + 1) }
C.memset( bytes, c, n )
bytes[n] = `0`
return string( bytes, n )
}
// strings.repeat_string - gives you `n` repetitions of the substring `s`
// NB: strings.repeat, that repeats a single byte, is between 2x
// and 24x faster than strings.repeat_string called for a 1 char string.
pub fn repeat_string(s string, n int) string {
if n <= 0 || s.len == 0 {
return ''
}
slen := s.len
blen := slen*n
mut bytes := &byte(0)
unsafe { bytes = malloc(blen + 1) }
for bi in 0..n {
bislen := bi*slen
for si in 0..slen {
bytes[bislen+si] = s[si]
}
}
bytes[blen] = `0`
return string( bytes, blen )
}

View File

@ -0,0 +1,18 @@
module strings
pub fn repeat(c byte, n int) string {
if n <= 0 {
return ''
}
mut arr := [c].repeat(n + 1)
arr[n] = `\0`
return string(arr,n)
}
pub fn repeat_string(s string, n int) string {
/*
// TODO: uncomment this. It is commented for now, so that `v doc strings` works
res := # s.repeat(n)
return res
*/
}

View File

@ -5,3 +5,10 @@ fn test_repeat() {
assert strings.repeat(`a`, 1) == 'a'
assert strings.repeat(`a`, 0) == ''
}
fn test_repeat_string() {
assert strings.repeat_string('abc', 3) == 'abcabcabc'
assert strings.repeat_string('abc', 1) == 'abc'
assert strings.repeat_string('abc', 0) == ''
assert strings.repeat_string('', 200) == ''
}