From 53760b4a74c440b05cf97db5e53f32d66ed47807 Mon Sep 17 00:00:00 2001 From: "Ben L. Titzer" Date: Tue, 23 Jan 2024 11:13:42 -0500 Subject: [PATCH] [lib/util] Add StringBuilder.resize method --- lib/util/StringBuilder.v3 | 5 +++++ test/lib/StringBuilderTest.v3 | 17 +++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/lib/util/StringBuilder.v3 b/lib/util/StringBuilder.v3 index ddba50da0..a210f236f 100644 --- a/lib/util/StringBuilder.v3 +++ b/lib/util/StringBuilder.v3 @@ -268,6 +268,11 @@ class StringBuilder { def outr(f: Range -> 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.new(n); diff --git a/test/lib/StringBuilderTest.v3 b/test/lib/StringBuilderTest.v3 index bfb32b9be..c69a5cdf6 100644 --- a/test/lib/StringBuilderTest.v3 +++ b/test/lib/StringBuilderTest.v3 @@ -19,6 +19,7 @@ def X = [ T("repeat", test_repeat), T("rjustify", test_rjustify), T("center", test_center), + T("resize", test_resize), () ]; @@ -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"); +}