diff --git a/sdk/lib/_internal/vm/lib/growable_array.dart b/sdk/lib/_internal/vm/lib/growable_array.dart index bca95abd0f4..6176cd8dae5 100644 --- a/sdk/lib/_internal/vm/lib/growable_array.dart +++ b/sdk/lib/_internal/vm/lib/growable_array.dart @@ -120,15 +120,16 @@ class _GrowableList extends ListBase { int get length native "GrowableList_getLength"; void set length(int new_length) { - int old_capacity = _capacity; - int new_capacity = new_length; - if (new_capacity > old_capacity) { + if (new_length > length) { // Verify that element type is nullable. null as T; - _grow(new_capacity); + if (new_length > _capacity) { + _grow(new_length); + } _setLength(new_length); return; } + final int new_capacity = new_length; // We are shrinking. Pick the method which has fewer writes. // In the shrink-to-fit path, we write |new_capacity + new_length| words // (null init + copy). diff --git a/tests/corelib/regress_42502_test.dart b/tests/corelib/regress_42502_test.dart new file mode 100644 index 00000000000..c3bac6770c2 --- /dev/null +++ b/tests/corelib/regress_42502_test.dart @@ -0,0 +1,27 @@ +// Copyright (c) 2020, 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. + +// Regression test for https://github.com/dart-lang/sdk/issues/42502. +// Requirements=nnbd-strong + +import "package:expect/expect.dart"; + +void main() { + List x = []; + Expect.throws(() { + x.length = x.length + 1; + }); + Expect.equals(0, x.length); + x.add(222); + Expect.equals(1, x.length); + Expect.throws(() { + x.length = 2; + }); + Expect.equals(1, x.length); + Expect.throws(() { + x.length = x.length + 1; + }); + Expect.equals(1, x.length); + Expect.equals(222, x[0]); +}