decode method

String decode(
  1. List<int> chunk
)

Decode a chunk of bytes, returning only complete UTF-8 strings.

Incomplete UTF-8 sequences are buffered until the next chunk. Returns an empty string if no complete sequences are available.

Implementation

String decode(List<int> chunk) {
  if (chunk.isEmpty) return '';

  // Add new bytes to buffer
  _buffer.addAll(chunk);

  // Find the last complete UTF-8 sequence
  int lastCompleteIndex = _findLastCompleteUtf8Index(_buffer);

  if (lastCompleteIndex == -1) {
    // No complete sequences, keep buffering
    return '';
  }

  // Extract complete bytes for decoding
  final completeBytes = _buffer.sublist(0, lastCompleteIndex + 1);

  // Keep incomplete bytes for next chunk
  final remainingBytes = _buffer.sublist(lastCompleteIndex + 1);
  _buffer.clear();
  _buffer.addAll(remainingBytes);

  try {
    return utf8.decode(completeBytes);
  } catch (e) {
    // This shouldn't happen with our logic, but handle gracefully
    _buffer.clear();
    return '';
  }
}