2020-02-26 13:22:12 +01:00
|
|
|
module strings
|
|
|
|
|
|
|
|
// strings.repeat - fill a string with `n` repetitions of the character `c`
|
2022-04-15 17:25:45 +02:00
|
|
|
pub fn repeat(c u8, n int) string {
|
2020-02-26 13:22:12 +01:00
|
|
|
if n <= 0 {
|
|
|
|
return ''
|
|
|
|
}
|
2021-06-15 13:47:11 +02:00
|
|
|
mut bytes := unsafe { malloc_noscan(n + 1) }
|
2020-07-15 21:56:50 +02:00
|
|
|
unsafe {
|
2020-12-21 21:00:32 +01:00
|
|
|
C.memset(bytes, c, n)
|
2020-07-15 21:56:50 +02:00
|
|
|
bytes[n] = `0`
|
|
|
|
}
|
2020-12-23 19:13:42 +01:00
|
|
|
return unsafe { bytes.vstring_with_len(n) }
|
2020-02-26 13:22:12 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// strings.repeat_string - gives you `n` repetitions of the substring `s`
|
2022-03-06 18:01:22 +01:00
|
|
|
// Note: strings.repeat, that repeats a single byte, is between 2x
|
2020-02-26 13:22:12 +01:00
|
|
|
// 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 21:00:32 +01:00
|
|
|
blen := slen * n
|
2021-06-15 13:47:11 +02:00
|
|
|
mut bytes := unsafe { malloc_noscan(blen + 1) }
|
2020-12-21 21:00:32 +01:00
|
|
|
for bi in 0 .. n {
|
|
|
|
bislen := bi * slen
|
|
|
|
for si in 0 .. slen {
|
2020-07-15 21:56:50 +02:00
|
|
|
unsafe {
|
2020-12-21 21:00:32 +01:00
|
|
|
bytes[bislen + si] = s[si]
|
2020-07-15 21:56:50 +02:00
|
|
|
}
|
2020-02-26 13:22:12 +01:00
|
|
|
}
|
|
|
|
}
|
2020-07-15 21:56:50 +02:00
|
|
|
unsafe {
|
|
|
|
bytes[blen] = `0`
|
|
|
|
}
|
2020-12-23 19:13:42 +01:00
|
|
|
return unsafe { bytes.vstring_with_len(blen) }
|
2020-02-26 13:22:12 +01:00
|
|
|
}
|