read method

  1. @override
Future<String> read({
  1. int? length,
  2. int? numBytes,
})

Reads a string that has length number of characters. Read numBytes bytes and convert it into a string.

Implementation

@override
Future<String> read({int? length, int? numBytes}) {
  if ((numBytes != null) == (length != null)) {
    throw ArgumentError("Exactly one of `numBytes` or `length` must be given.");
  }

  final encoding = this.encoding;
  if (isEncodingStatic(encoding)) {
    numBytes = getBytesPerChar(encoding);
  }

  if (numBytes != null) {
    return readBytes(numBytes).then((bytes) => encoding.decode(bytes));
  } else {
    final completer = Completer<String>();
    final buffer = StringBuffer();
    final stringSink = StringConversionSink.fromStringSink(buffer);
    final byteSink = encoding.decoder.startChunkedConversion(stringSink);

    late StreamSubscription<List<int>> sub;
    sub = stream.listen((bytes) {
      byteSink.add(bytes);

      if (buffer.length >= length!) {
        final result = buffer.toString().substring(0, length);
        sub.cancel();
        byteSink.close();
        stringSink.close();
        completer.complete(result);
      }
    }, onError: (error, stackTrace) {
      byteSink.close();
      stringSink.close();
      completer.completeError(error, stackTrace);
    }, onDone: () {
      byteSink.close();
      stringSink.close();
      completer.completeError(StateError("Serial input stream closed prematurely."), StackTrace.current);
    });

    return completer.future;
  }
}