Skip to content

Commit

Permalink
builtin: add byte.repeat() and rune.repeat() (#12007)
Browse files Browse the repository at this point in the history
  • Loading branch information
Wertzui123 committed Sep 30, 2021
1 parent f9ceb12 commit e3d379a
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
22 changes: 22 additions & 0 deletions vlib/builtin/int.v
Expand Up @@ -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')

This comment has been minimized.

Copy link
@elimisteve

elimisteve Oct 1, 2021

Member

Maybe this should return empty string? A panic seems unnecessarily destabilizing.

This comment has been minimized.

Copy link
@JalonSolov

JalonSolov Oct 1, 2021

Contributor

It should return an optional rather than a panic. There should not be any panics in vlib code unless absolutely necessary to prevent catastrophe.

} 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) }
}
7 changes: 7 additions & 0 deletions vlib/builtin/int_test.v
Expand Up @@ -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) == ''
}
14 changes: 14 additions & 0 deletions vlib/builtin/rune.v
Expand Up @@ -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)
}
13 changes: 13 additions & 0 deletions vlib/builtin/rune_test.v
@@ -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) == ''
}

0 comments on commit e3d379a

Please sign in to comment.