public static < T extends Range > T findRange ( List < T > ranges , long value , int arraySize ) { if ( ranges . size ( ) < 1 ) return null ; T first = ranges . get ( 0 ) ; T last = ranges . get ( arraySize - 1 ) ; // check out of bounds if ( value < first . start ( ) || value > last . start ( ) + last . size ( ) ) { throw new OffsetOutOfRangeException ( format ( "offset %s is out of range (%s, %s)" , // value , first . start ( ) , last . start ( ) + last . size ( ) ) ) ; } // check at the end if ( value == last . start ( ) + last . size ( ) ) return null ; int low = 0 ; int high = arraySize - 1 ; while ( low <= high ) { int mid = ( high + low ) / 2 ; T found = ranges . get ( mid ) ; if ( found . contains ( value ) ) { return found ; } else if ( value < found . start ( ) ) { high = mid - 1 ; } else { low = mid + 1 ; } } return null ; }
Find a given range object in a list of ranges by a value in that range . Does a binary search over the ranges but instead of checking for equality looks within the range . Takes the array size as an option in case the array grows while searching happens