builtin: add byte.repeat() and rune.repeat() (#12007)

pull/12021/head
Wertzui123 2021-09-30 08:32:20 +02:00 committed by GitHub
parent f9ceb12e22
commit e3d379a1eb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 56 additions and 0 deletions

View File

@ -507,3 +507,25 @@ pub fn (b []byte) bytestr() string {
return tos(buf, b.len)
}
}
// repeat returns a new string with `count` number of copies of the byte it was called on.
pub fn (b byte) repeat(count int) string {
if count < 0 {
panic('byte.repeat: count is negative: $count')
} else if count == 0 {
return ''
} else if count == 1 {
return b.ascii_str()
}
mut ret := unsafe { malloc_noscan(count + 1) }
for i in 0 .. count {
unsafe {
ret[i] = b
}
}
new_len := count
unsafe {
ret[new_len] = 0
}
return unsafe { ret.vstring_with_len(new_len) }
}

View File

@ -239,3 +239,10 @@ fn test_int_to_hex() {
assert i64(-1).hex() == 'ffffffffffffffff'
assert u64(18446744073709551615).hex() == 'ffffffffffffffff'
}
fn test_repeat() {
b := byte(`V`)
assert b.repeat(5) == 'VVVVV'
assert b.repeat(1) == b.ascii_str()
assert b.repeat(0) == ''
}

View File

@ -39,3 +39,17 @@ pub fn (ra []rune) string() string {
unsafe { sb.free() }
return res
}
// repeat returns a new string with `count` number of copies of the rune it was called on.
pub fn (c rune) repeat(count int) string {
if count < 0 {
panic('rune.repeat: count is negative: $count')
} else if count == 0 {
return ''
} else if count == 1 {
return c.str()
}
mut buffer := [5]byte{}
res := unsafe { utf32_to_str_no_malloc(u32(c), &buffer[0]) }
return res.repeat(count)
}

View File

@ -0,0 +1,13 @@
fn test_repeat() {
r1 := `V`
r2 := `👋`
assert r1.repeat(5) == 'VVVVV'
assert r2.repeat(5) == '👋👋👋👋👋'
assert r1.repeat(1) == r1.str()
assert r2.repeat(1) == r2.str()
assert r1.repeat(0) == ''
assert r2.repeat(0) == ''
}