ensureAvailableLength method

void ensureAvailableLength(
  1. int length
)

Ensures the buffer has space for at least length more bytes.

If the buffer is full and isExpanding is false, a RawWriterException is thrown.

Implementation

void ensureAvailableLength(int length) {
  final oldBuffer = _byteData;
  final required = _length + length;

  // Enough space already
  if (oldBuffer.lengthInBytes >= required) return;

  if (!isExpanding) {
    throw RawWriterException(
      "ensureAvailableLength($length) called, but only "
      "${oldBuffer.lengthInBytes - _length} bytes available",
    );
  }

  // Compute new capacity (power of two growth)
  var newCapacity = 64;
  while (newCapacity < required) {
    newCapacity *= 2;
  }

  // Copy only the used bytes (_length) to the new buffer
  final newBuffer = ByteData(newCapacity);
  for (var i = 0; i < _length; i++) {
    newBuffer.setUint8(i, oldBuffer.getUint8(i));
  }

  _byteData = newBuffer;
}