findUnsafe method

  1. @override
int? findUnsafe(
  1. F target,
  2. num? tolerance,
  3. int start,
  4. int end,
)
override

Internal implementation for find, which does not do any validity checks on its arguments. Not to be called directly.

Implementation

@override
int? findUnsafe(F target, num? tolerance, final int start, final int end) {
  var localStart = start;
  var localEnd = end;

  while (true) {
    // Have not found anything.
    if (localStart == localEnd) {
      return _findNearestMatchWithinTolerance(
          target, tolerance, start, end, localStart);
    }

    // Only one option -> either it's a match, or there's no match.
    if (localStart == localEnd - 1) {
      if (compareDiff.compareFunc(collection, localStart, target) == 0) {
        return localStart;
      } else {
        return _findNearestMatchWithinTolerance(
            target, tolerance, start, end, localStart);
      }
    }

    // Can't tell yet -> subdivide and look in the upper/lower half depending
    // on how the midpoint works out.
    final mid = localStart + (localEnd - localStart) ~/ 2;
    final midComparison = compareDiff.compareFunc(collection, mid, target);
    if (midComparison == 0) {
      return mid;
    } else {
      if (midComparison < 0) {
        // mid is before the item we're looking for -> look from mid+1 to end
        localStart = mid + 1;
      } else {
        // mid is after the item we're looking for -> look from start to mid (excluding mid)
        localEnd = mid;
      }
    }
  }
}