Fix #62883 String buffer clear()

Closes https://github.com/dart-lang/sdk/pull/62931

GitOrigin-RevId: 00a2f30d0906758176575a615d57fdb6c517e23a
Change-Id: I636770b919f3f2358136d05fc373cbd53e88e4ce
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/489040
Reviewed-by: Slava Egorov <vegorov@google.com>
Commit-Queue: Slava Egorov <vegorov@google.com>
Reviewed-by: Alexander Aprelev <aam@google.com>
This commit is contained in:
D.ildo
2026-03-25 02:48:45 -07:00
committed by Commit Queue
parent d05a0c6996
commit f76fc366de
2 changed files with 33 additions and 1 deletions
@@ -123,7 +123,8 @@ class StringBuffer {
@patch
void clear() {
_parts = null;
_partsCodeUnits = _bufferPosition = _bufferCodeUnitMagnitude = 0;
_partsCodeUnits = _bufferPosition = _bufferCodeUnitMagnitude =
_partsCompactionIndex = _partsCodeUnitsSinceCompaction = 0;
}
/** Returns the contents of buffer as a string. */
@@ -175,6 +176,7 @@ class StringBuffer {
} else {
localParts.add(str);
int partsSinceCompaction = localParts.length - _partsCompactionIndex;
assert(partsSinceCompaction > 0);
if (partsSinceCompaction == _PARTS_TO_COMPACT) {
_compact();
}
@@ -0,0 +1,30 @@
// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// VMOptions=--enable-asserts
import "package:expect/expect.dart";
const int _iterations = 10000;
final String _expected = List.generate(
_iterations,
(int i) => i.isEven ? "foo " : "bar ",
).join();
void writeFooBar(StringBuffer buffer) {
for (int i = 0; i < _iterations; i++) {
buffer.write(i.isEven ? "foo" : "bar");
buffer.write(" ");
}
}
void main() {
final buffer = StringBuffer();
writeFooBar(buffer);
buffer.clear();
writeFooBar(buffer);
Expect.equals(_expected.length, buffer.length);
Expect.equals(_expected, buffer.toString());
}