[vm/corelib/nnbd] Fix null check in _GrowableList.length=

We should verify that element type is nullable every time length is
increased, not only when capacity is increased.

Fixes https://github.com/dart-lang/sdk/issues/42502

Change-Id: Id91c702a99028634da8c2d41ae0ceac521af2cf5
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/152900
Reviewed-by: Régis Crelier <regis@google.com>
Reviewed-by: Lasse R.H. Nielsen <lrn@google.com>
Commit-Queue: Alexander Markov <alexmarkov@google.com>
This commit is contained in:
Alexander Markov 2020-06-30 17:14:14 +00:00 committed by commit-bot@chromium.org
parent 97ba0acc72
commit e6cbfd71f1
2 changed files with 32 additions and 4 deletions

View file

@ -120,15 +120,16 @@ class _GrowableList<T> extends ListBase<T> {
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).

View file

@ -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<int> 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]);
}