decode method

BchDecodeResult decode(
  1. BigInt received, {
  2. int? correctionCapacity,
})

Decodes up to the BCH correction capacity using Berlekamp--Massey and Chien search.

The default capacity is the guaranteed BCH capacity floor((designedDistance - 1) / 2). Patterns with too many errors or with an invalid locator are returned as uncorrectable.

Implementation

BchDecodeResult decode(BigInt received, {int? correctionCapacity}) {
  final capacity = correctionCapacity ?? (designedDistance - 1) ~/ 2;
  if (capacity < 1) {
    throw ArgumentError.value(correctionCapacity, 'correctionCapacity');
  }
  final receivedSyndromes = [
    for (var index = 0; index < capacity * 2; index++)
      _evaluateAt(received, (firstRoot + index) % fullLength),
  ];
  if (receivedSyndromes.every((syndrome) => syndrome.isZero)) {
    return BchDecodeResult(
      codeword: received,
      message: received >> parityBits,
      status: const CodecOracleStatus(),
    );
  }

  final locator = _berlekampMassey(receivedSyndromes);
  final errorCount = locator.length - 1;
  if (errorCount < 1 || errorCount > capacity) {
    return _uncorrectableResult(received);
  }

  final errorPositions = <int>[];
  for (var position = 0; position < length; position++) {
    final inverseRoot =
        field.x.pow(BigInt.from((fullLength - position) % fullLength));
    var value = field.zero;
    for (var coefficient = locator.length - 1;
        coefficient >= 0;
        coefficient--) {
      value *= inverseRoot;
      value += locator[coefficient];
    }
    if (value.isZero) {
      errorPositions.add(position);
    }
  }
  if (errorPositions.length != errorCount) {
    return _uncorrectableResult(received);
  }

  var corrected = received;
  for (final position in errorPositions) {
    corrected ^= BigInt.one << position;
  }
  return BchDecodeResult(
    codeword: corrected,
    message: corrected >> parityBits,
    status: const CodecOracleStatus(errorDetected: true, corrected: true),
  );
}