v / vlib / strings / strings.c.v
40 lines · 38 sloc · 935 bytes · f001561a5833f84ce990d241c1a17cfd7a2bb3dd
Raw
1module strings
2
3// strings.repeat - fill a string with `n` repetitions of the character `c`
4@[direct_array_access]
5pub fn repeat(c u8, n int) string {
6 if n <= 0 {
7 return ''
8 }
9 mut bytes := unsafe { malloc_noscan(n + 1) }
10 unsafe {
11 C.memset(bytes, c, n)
12 bytes[n] = 0
13 }
14 return unsafe { bytes.vstring_with_len(n) }
15}
16
17// strings.repeat_string - gives you `n` repetitions of the substring `s`
18// Note: strings.repeat, that repeats a single byte, is between 2x
19// and 24x faster than strings.repeat_string called for a 1 char string.
20@[direct_array_access]
21pub fn repeat_string(s string, n int) string {
22 if n <= 0 || s.len == 0 {
23 return ''
24 }
25 slen := s.len
26 blen := slen * n
27 mut bytes := unsafe { malloc_noscan(blen + 1) }
28 for bi in 0 .. n {
29 bislen := bi * slen
30 for si in 0 .. slen {
31 unsafe {
32 bytes[bislen + si] = s[si]
33 }
34 }
35 }
36 unsafe {
37 bytes[blen] = 0
38 }
39 return unsafe { bytes.vstring_with_len(blen) }
40}
41