MySQLPacketAuthSwitchRequest.decode constructor

MySQLPacketAuthSwitchRequest.decode(
  1. Uint8List buffer
)

Decodifica um Uint8List recebido do servidor e cria uma instância de MySQLPacketAuthSwitchRequest.

O formato esperado do buffer é:

  1. Header: 1 byte.
  2. authPluginName: string terminada em null (utiliza getUtf8NullTerminatedString).
  3. authPluginData: o restante do buffer.

Implementation

factory MySQLPacketAuthSwitchRequest.decode(Uint8List buffer) {
  if (buffer.isEmpty) {
    throw const MySQLProtocolException(
      'Truncated MySQLPacketAuthSwitchRequest: empty buffer',
    );
  }
  final byteData = ByteData.sublistView(buffer);
  int offset = 0;

  // 1) Leitura do header (1 byte)
  final header = byteData.getUint8(offset);
  if (header != 0xfe) {
    throw MySQLProtocolException(
      'Invalid MySQLPacketAuthSwitchRequest header: '
      'expected 0xfe, got 0x${header.toRadixString(16)}',
    );
  }
  offset += 1;

  // 2) Leitura do nome do plugin de autenticação (string null-terminated)
  final pluginEnd = buffer.indexOf(0, offset);
  if (pluginEnd < 0) {
    throw const MySQLProtocolException(
      'Truncated MySQLPacketAuthSwitchRequest: unterminated authPluginName',
    );
  }
  final authPluginName = utf8.decode(
    Uint8List.sublistView(buffer, offset, pluginEnd),
    allowMalformed: true,
  );
  offset = pluginEnd + 1;

  // 3) O restante do buffer corresponde aos dados do plugin
  final authPluginData = Uint8List.sublistView(buffer, offset);

  return MySQLPacketAuthSwitchRequest(
    header: header,
    authPluginData: authPluginData,
    authPluginName: authPluginName,
  );
}