diff --git a/vlib/strings/strings.v b/vlib/strings/strings.v deleted file mode 100644 index 71f450865c..0000000000 --- a/vlib/strings/strings.v +++ /dev/null @@ -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) -} - diff --git a/vlib/strings/strings_c.v b/vlib/strings/strings_c.v new file mode 100644 index 0000000000..292222cf9b --- /dev/null +++ b/vlib/strings/strings_c.v @@ -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 ) +} diff --git a/vlib/strings/strings_js.v b/vlib/strings/strings_js.v new file mode 100644 index 0000000000..72f66576b4 --- /dev/null +++ b/vlib/strings/strings_js.v @@ -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 +*/ +} diff --git a/vlib/strings/strings_test.v b/vlib/strings/strings_test.v index 1b20d640b6..ff5ddf504a 100644 --- a/vlib/strings/strings_test.v +++ b/vlib/strings/strings_test.v @@ -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) == '' +}