getVariableEncInt method

Tuple2<BigInt, int> getVariableEncInt(
  1. int startOffset
)

Decodes a MySQL length-encoded integer (packet length) starting at startOffset.

Returns a tuple of (value, bytesConsumed).

MySQL length encoding:

  • 0x00–0xfa (0–250): value = firstByte, size = 1
  • 0xfb (251) : NULL marker, value = 0 (caller should check separately), size = 1
  • 0xfc (252) : next 2 bytes little-endian, size = 3
  • 0xfd (253) : next 3 bytes little-endian, size = 4
  • 0xfe (254) : next 8 bytes little-endian, size = 9
  • 0xff (255) : invalid

Implementation

Tuple2<BigInt, int> getVariableEncInt(int startOffset) {
  final firstByte = getUint8(startOffset);

  if (firstByte <= 0xfa) {
    return Tuple2(BigInt.from(firstByte), 1);
  }

  if (firstByte == 0xfb) {
    // NULL marker
    return Tuple2(BigInt.zero, 1);
  }

  if (firstByte == 0xfc) {
    final value = getUint16(startOffset + 1, Endian.little);
    return Tuple2(BigInt.from(value), 3);
  }

  if (firstByte == 0xfd) {
    final value = getUint24(startOffset + 1);
    return Tuple2(BigInt.from(value), 4);
  }

  if (firstByte == 0xfe) {
    final value = getUint64(startOffset + 1, Endian.little);
    return Tuple2(BigInt.from(value), 9);
  }

  // 0xff is invalid for length-encoded integers
  throw MySQLProtocolException(
      "Wrong first byte 0xff, while decoding getVariableEncInt");
}