Skip to content

Commit

Permalink
[lib/util] Add StringBuilder.resize method
Browse files Browse the repository at this point in the history
  • Loading branch information
titzer committed Jan 23, 2024
1 parent 6a0d50b commit 53760b4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/util/StringBuilder.v3
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,11 @@ class StringBuilder {
def outr<R>(f: Range<byte> -> R) -> R {
return if(buf != null, f(buf[0 ... length]));
}
// Resizes the string being built to {nlength}.
def resize(nlength: int) -> this {
if (nlength > length) grow(nlength);
length = nlength;
}
// Acquire {n} more bytes of internal storage, growing if necessary.
private def acquire(n: int) -> int {
if (buf == null) buf = Array<byte>.new(n);
Expand Down
17 changes: 17 additions & 0 deletions test/lib/StringBuilderTest.v3
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def X = [
T("repeat", test_repeat),
T("rjustify", test_rjustify),
T("center", test_center),
T("resize", test_resize),
()
];

Expand Down Expand Up @@ -383,3 +384,19 @@ def test_center(t: LibTest) {
buf.center('*', 2, 2);
t.assert_string(buf.extract(), "bug");
}

def test_resize(t: LibTest) {
var buf = StringBuilder.new();

buf.puts("FooBar").resize(3);
t.assert_string(buf.extract(), "Foo");

buf.puts("bank_roll");
buf.resize(4).resize(9);
t.assert_string(buf.extract(), "bank_roll");


buf.puts("bank");
buf.resize(6);
t.assert_string(buf.extract(), "bank\x00\x00");
}

0 comments on commit 53760b4

Please sign in to comment.