bind method

  1. @override
Stream<String> bind(
  1. Stream<List<int>> stream
)
override

Transforms the provided stream.

Returns a new stream with events that are computed from events of the provided stream.

The StreamTransformer interface is completely generic, so it cannot say what subclasses do. Each StreamTransformer should document clearly how it transforms the stream (on the class or variable used to access the transformer), as well as any differences from the following typical behavior:

  • When the returned stream is listened to, it starts listening to the input stream.
  • Subscriptions of the returned stream forward (in a reasonable time) a StreamSubscription.pause call to the subscription of the input stream.
  • Similarly, canceling a subscription of the returned stream eventually (in reasonable time) cancels the subscription of the input stream.

"Reasonable time" depends on the transformer and stream. Some transformers, like a "timeout" transformer, might make these operations depend on a duration. Others might not delay them at all, or just by a microtask.

Transformers are free to handle errors in any way. A transformer implementation may choose to propagate errors, or convert them to other events, or ignore them completely, but if errors are ignored, it should be documented explicitly.

Implementation

@override
Stream<String> bind(Stream<List<int>> stream) {
  late StreamSubscription<List<int>> subscription;
  final controller = StreamController<String>(sync: true);

  var initialized = false;
  final initialBuffer = <int>[];
  Sink<List<int>>? standardSink;
  var isUtf16Le = false;
  var isUtf16Be = false;
  int? pendingByte;

  void processUtf16(List<int> bytes) {
    if (bytes.isEmpty) return;
    var offset = 0;
    final codeUnits = <int>[];
    if (pendingByte != null) {
      final b0 = pendingByte!;
      final b1 = bytes[0];
      pendingByte = null;
      offset = 1;
      codeUnits.add(isUtf16Le ? (b1 << 8) | b0 : (b0 << 8) | b1);
    }
    final remaining = bytes.length - offset;
    final pairs = remaining ~/ 2;
    for (var i = 0; i < pairs; i++) {
      final b0 = bytes[offset++];
      final b1 = bytes[offset++];
      codeUnits.add(isUtf16Le ? (b1 << 8) | b0 : (b0 << 8) | b1);
    }
    if (offset < bytes.length) {
      pendingByte = bytes[offset];
    }
    if (codeUnits.isNotEmpty) {
      controller.add(String.fromCharCodes(codeUnits));
    }
  }

  void processBytes(List<int> bytes, [int offset = 0]) {
    if (offset >= bytes.length) return;
    var data = bytes;
    if (offset != 0) {
      // A large Uint8List first chunk should not be copied just to skip
      // the XML declaration.
      if (bytes is Uint8List) {
        data = Uint8List.sublistView(bytes, offset);
      } else {
        data = bytes.sublist(offset);
      }
    }
    if (isUtf16Be || isUtf16Le) {
      processUtf16(data);
    } else {
      standardSink!.add(data);
    }
  }

  void initializeDecoder(List<int> bytes) {
    var sliceOffset = 0;
    if (bytes.length >= 3 &&
        bytes[0] == 0xEF &&
        bytes[1] == 0xBB &&
        bytes[2] == 0xBF) {
      // UTF-8 BOM
      sliceOffset = 3;
      standardSink = utf8.decoder.startChunkedConversion(
        StringConversionSink.from(controller),
      );
    } else if (bytes.length >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF) {
      // UTF-16 BE BOM
      sliceOffset = 2;
      isUtf16Be = true;
    } else if (bytes.length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE) {
      // UTF-16 LE BOM
      sliceOffset = 2;
      isUtf16Le = true;
    } else if (bytes.length >= 4 && bytes[0] == 0x00 && bytes[1] == 0x3C) {
      // UTF-16 BE starts with '<' even without an XML declaration.
      isUtf16Be = true;
    } else if (bytes.length >= 4 &&
        bytes[0] == 0x3C &&
        bytes[1] == 0x00 &&
        (bytes[2] != 0x00 || bytes[3] != 0x00)) {
      // UTF-16 LE starts with '<'. Exclude the UTF-32 LE signature.
      isUtf16Le = true;
    } else {
      // The ASCII XML prolog may be longer than one byte-stream chunk.
      final header = ascii.decode(
        bytes.take(_maxPrologBytes).toList(),
        allowInvalid: true,
      );
      final encodingMatch = _encodingPattern.firstMatch(header);
      final encodingName = encodingMatch?.group(1)?.toLowerCase();
      if (encodingName == 'iso-8859-1' || encodingName == 'latin1') {
        standardSink = latin1.decoder.startChunkedConversion(
          StringConversionSink.from(controller),
        );
      } else if (encodingName == 'us-ascii' || encodingName == 'ascii') {
        standardSink = ascii.decoder.startChunkedConversion(
          StringConversionSink.from(controller),
        );
      } else if (encodingName == 'utf-16' || encodingName == 'utf-16be') {
        isUtf16Be = true;
      } else if (encodingName == 'utf-16le') {
        isUtf16Le = true;
      } else {
        final enc = defaultEncoding ?? utf8;
        standardSink = enc.decoder.startChunkedConversion(
          StringConversionSink.from(controller),
        );
      }
    }

    initialized = true;
    processBytes(bytes, sliceOffset);
  }

  controller.onListen = () {
    subscription = stream.listen(
      (data) {
        if (initialized) {
          processBytes(data);
          return;
        }
        // Copy only as many bytes as are needed to recognize the prolog,
        // not the entire first chunk (which may be several megabytes).
        var index = 0;
        while (!initialized && index < data.length) {
          initialBuffer.add(data[index++]);
          if (_readyToDecode(initialBuffer)) {
            initializeDecoder(initialBuffer);
          }
        }
        if (initialized) processBytes(data, index);
      },
      onError: controller.addError,
      onDone: () {
        if (!initialized) {
          initializeDecoder(initialBuffer);
        }
        if (pendingByte != null) {
          controller.addError(
            const FormatException('Incomplete UTF-16 code unit'),
          );
        }
        if (standardSink != null) {
          standardSink!.close();
        }
        controller.close();
      },
      cancelOnError: false,
    );
  };

  controller.onPause = () => subscription.pause();
  controller.onResume = () => subscription.resume();
  controller.onCancel = () => subscription.cancel();

  return controller.stream;
}