1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00
v/vlib/strings/strings.c.v

39 lines
879 B
V
Raw Normal View History

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 := unsafe { malloc(n + 1) }
unsafe {
2020-12-21 23:00:32 +03:00
C.memset(bytes, c, n)
bytes[n] = `0`
}
return unsafe { bytes.vstring_with_len(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
2020-12-21 23:00:32 +03:00
blen := slen * n
mut bytes := unsafe { malloc(blen + 1) }
2020-12-21 23:00:32 +03:00
for bi in 0 .. n {
bislen := bi * slen
for si in 0 .. slen {
unsafe {
2020-12-21 23:00:32 +03:00
bytes[bislen + si] = s[si]
}
}
}
unsafe {
bytes[blen] = `0`
}
return unsafe { bytes.vstring_with_len(blen) }
}