readLineFromUint8List method

List<String> readLineFromUint8List(
  1. Uint8List uint8List, {
  2. Encoding encoding = utf8,
})

Reads lines from a Uint8List and decodes them to a list of String.

Handles both LF and CRLF line endings.

Implementation

List<String> readLineFromUint8List(
  Uint8List uint8List, {
  Encoding encoding = utf8,
}) {
  final lines = <String>[];
  final buffer = StringBuffer();
  bool isCarriageReturn = false;

  for (var i = 0; i < uint8List.length; i++) {
    final codeUnit = uint8List[i];
    if (codeUnit == 10) {
      // LF (0x0A)
      // If the previous character is CR, combine to CRLF
      if (isCarriageReturn) {
        buffer.writeCharCode(13);
        isCarriageReturn = false;
      }
      lines.add(buffer.toString());
      buffer.clear();
    } else if (codeUnit == 13) {
      // CR (0x0D)
      // Alone CR or part of CRLF
      isCarriageReturn = true;
      // Check if the next character is LF
      if (i + 1 < uint8List.length && uint8List[i + 1] == 10) {
        // Is part of CRLF, wait for LF processing
      } else {
        // Single CR, treated as line break
        lines.add(buffer.toString());
        buffer.clear();
        isCarriageReturn = false;
      }
    } else {
      // Ordinary character
      if (isCarriageReturn) {
        buffer.writeCharCode(13);
        isCarriageReturn = false;
      }
      buffer.writeCharCode(codeUnit);
    }
  }

  // Add the last line (if there is remaining content)
  if (buffer.isNotEmpty || isCarriageReturn) {
    if (isCarriageReturn) {
      buffer.writeCharCode(13);
    }
    lines.add(buffer.toString());
  }
  return lines.map((line) => encoding.decode(line.codeUnits)).toList();
}