read method Null safety

Uint8List read(
  1. int length,
  2. {bool? copy}
)

Implementation

Uint8List read(int length, {bool? copy}) {
  if (length == 0) {
    return Uint8List(0);
  }
  if (_queue.isEmpty || _queueCurrentLength - _offset < length) {
    throw StateError('Not enough bytes to read.');
  }
  _clearQueue();
  final shouldCopy = copy ?? _copy;
  if (!shouldCopy && (_offset + length <= _queue.first.length)) {
    final value = Uint8List.view(
        _queue.first.buffer, _queue.first.offsetInBytes + _offset, length);
    _offset += length;
    return value;
  }
  final bb = BytesBuffer(copy: copy ?? _copy);
  while (bb.length < length) {
    _clearQueue();
    final remaining = length - bb.length;
    if (_offset + remaining <= _queue.first.length) {
      bb.add(Uint8List.view(_queue.first.buffer,
          _queue.first.offsetInBytes + _offset, remaining));
      _offset += remaining;
    } else {
      final first = _queue.removeFirst();
      _queueCurrentLength -= first.length;
      if (_offset == 0) {
        bb.add(first, copy: false);
      } else {
        bb.add(Uint8List.view(first.buffer, first.offsetInBytes + _offset));
      }
      _data = null;
      _offset = 0;
    }
  }
  return bb.toBytes();
}