compareTo method

  1. @override
int compareTo(
  1. Object other
)
override

Floating point comparison to implement Comparable.

Implementation

@override
int compareTo(Object other) {
  if (other is! FloatingPointValue) {
    throw Exception('Input must be of type FloatingPointValue ');
  }
  if ((exponent.width != other.exponent.width) |
      (mantissa.width - (explicitJBit ? 1 : 0) !=
          other.mantissa.width - (other.explicitJBit ? 1 : 0))) {
    throw Exception('FloatingPointValue widths must match for comparison');
  }

  // IEEE 754: -0 an +0 are considered equal
  if ((exponent.isZero && mantissa.isZero) &&
      (other.exponent.isZero && other.mantissa.isZero)) {
    return 0;
  }
  final signCompare = -sign.compareTo(other.sign);

  final canonical = canonicalize();
  final otherCanonical = other.canonicalize();

  final canonicalMantissa = canonical.explicitJBit
      ? canonical.mantissa.getRange(0, -1)
      : canonical.mantissa;

  final otherCanonicalMantissa = otherCanonical.explicitJBit
      ? otherCanonical.mantissa.getRange(0, -1)
      : otherCanonical.mantissa;

  final expCompare = canonical.exponent.compareTo(otherCanonical.exponent);
  final mantCompare = canonicalMantissa.compareTo(otherCanonicalMantissa);
  if ((signCompare != 0) &&
      !(exponent.isZero &&
          mantissa.isZero &&
          other.exponent.isZero &&
          other.mantissa.isZero)) {
    return signCompare; // IEEE 754: -0 and +0 are considered equal.
  }
  if (expCompare != 0) {
    return sign.isZero ? expCompare : -expCompare;
  } else if (mantCompare != 0) {
    return sign.isZero ? mantCompare : -mantCompare;
  }
  return 0;
}