capacity property

int capacity

The available capacity (in elements) for storage.

Not all the space is necessarily currently used (used space is indicated by the length property). Capacity may be increased manually for efficiency (pre-allocating the required memory), and will be grown automatically if elements are added without explicit pre-allocation of capacity. Capacity cannot be decreased to less than the current length, since that might invalidate any pre-existing views on this collection.

Implementation

int get capacity => _rawData.lengthInBytes ~/ elementSizeInBytes;
void capacity=(int newCapacity)

Implementation

set capacity(int newCapacity) {
  // Don't allow deleting any currently in-use elements, for it could invalidate
  // existing views.
  newCapacity = max(length, newCapacity);

  // If there's no change, stop.
  if (newCapacity == capacity) {
    return;
  }

  // Capacity needs to change -> rebuild the list
  final newData = ByteData(_elementNrToByteOffset(newCapacity));
  // Even though currently we don't alow decreasing capacity below length,
  // keep in a safeguard that we won't copy more than the capacity.
  final bytesToCopy = _elementNrToByteOffset(min(newCapacity, length));
  // do a hopefully optimized memcopy
  newData.buffer
      .asUint8List()
      .setRange(0, bytesToCopy, _rawData.buffer.asUint8List());
  // Replace the buffer with the one with different capacity
  _rawData = newData;
}