Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
builtin: add byte.repeat() and rune.repeat() (#12007)
- Loading branch information
1 parent
f9ceb12
commit e3d379a
Showing
4 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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.
Sorry, something went wrong.
This comment has been minimized.
Sorry, something went wrong.
JalonSolov
Contributor
|
||
} 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) } | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) == '' | ||
} |
Maybe this should return empty string? A panic seems unnecessarily destabilizing.