Skip to content

fix: handle empty collection in binarySearch to prevent crash#62

Open
Nepomuk5665 wants to merge 1 commit intoapple:mainfrom
Nepomuk5665:fix/binary-search-empty-collection
Open

fix: handle empty collection in binarySearch to prevent crash#62
Nepomuk5665 wants to merge 1 commit intoapple:mainfrom
Nepomuk5665:fix/binary-search-empty-collection

Conversation

@Nepomuk5665
Copy link

Summary

This PR fixes a runtime crash in LLBCASFileTree.binarySearch when called with an empty collection.

The Bug

The current implementation immediately calls elements.index(before: elements.endIndex) on line 16 without checking if the collection is empty. For an empty collection, startIndex == endIndex, and calling index(before: endIndex) is undefined behavior that causes a crash.

var lo: C.Index = elements.startIndex
var hi: C.Index = elements.index(before: elements.endIndex)  // CRASH if empty!

The Fix

Added an early guard clause to return nil for empty collections before attempting to compute indices:

guard !elements.isEmpty else { return nil }

This is the correct semantic behavior - searching for an element in an empty collection should return nil (not found), not crash.

Impact

  • Prevents runtime crash when binary search is called with empty input
  • No behavioral change for non-empty collections
  • Consistent with Swift standard library conventions where searching empty collections returns nil/not found

@Nepomuk5665 Nepomuk5665 requested a review from dmbryson as a code owner January 23, 2026 11:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant