readVersion method

Version readVersion()

Reads version information from one of its two locations within the QR Code.

@return Version encapsulating the QR Code's version @throws FormatException if both version information locations cannot be parsed as the valid encoding of version information

Implementation

Version readVersion() {
  if (_parsedVersion != null) {
    return _parsedVersion!;
  }

  final dimension = _bitMatrix.height;

  final provisionalVersion = (dimension - 17) ~/ 4;
  if (provisionalVersion <= 6) {
    return Version.getVersionForNumber(provisionalVersion);
  }

  // Read top-right version info: 3 wide by 6 tall
  int versionBits = 0;
  final ijMin = dimension - 11;
  for (int j = 5; j >= 0; j--) {
    for (int i = dimension - 9; i >= ijMin; i--) {
      versionBits = _copyBit(i, j, versionBits);
    }
  }

  Version? theParsedVersion = Version.decodeVersionInformation(versionBits);
  if (theParsedVersion != null &&
      theParsedVersion.dimensionForVersion == dimension) {
    _parsedVersion = theParsedVersion;
    return theParsedVersion;
  }

  // Hmm, failed. Try bottom left: 6 wide by 3 tall
  versionBits = 0;
  for (int i = 5; i >= 0; i--) {
    for (int j = dimension - 9; j >= ijMin; j--) {
      versionBits = _copyBit(i, j, versionBits);
    }
  }

  theParsedVersion = Version.decodeVersionInformation(versionBits);
  if (theParsedVersion != null &&
      theParsedVersion.dimensionForVersion == dimension) {
    _parsedVersion = theParsedVersion;
    return theParsedVersion;
  }
  throw FormatsException.instance;
}