private static int NormalizeIndex <T>(int index, List <T> collection, EBias bias) { if (index > 0) { return(index); } index = ~index; if (index == collection.Count) { return(-1); } return(bias == EBias.GREATEST_LOWER_BOUND ? index - 1 : index); }
/** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ protected int FindMapping( MappingItemIndexed needle, List <MappingItemIndexed> aMappings, Func <MappingItemIndexed, int?> line, Func <MappingItemIndexed, int?> column, Func <MappingItemIndexed, MappingItemIndexed, int> aComparator, EBias aBias) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (line(needle) <= 0) { throw new ArgumentException($"Line must be greater than or equal to 1, got {line(needle)}"); } if (column(needle) < 0) { throw new ArgumentException($"Column must be greater than or equal to 0, got {column(needle)}"); } return(BinarySearch.Search <MappingItemIndexed>(needle, aMappings, aComparator, aBias)); }
public static int Search <T>(T term, List <T> collection, Func <T, T, int> comparer, EBias bias) { var index = collection.BinarySearch(term, new Comaprer <T>(comparer)); return(NormalizeIndex(index, collection, bias)); }
public static int Search <TTerm, T>(TTerm term, List <T> collection, Func <TTerm, T, int> comparer, EBias bias) where T : new() { var marker = new T(); var index = collection.BinarySearch(marker, new Comaprer <TTerm, T>(term, comparer, marker)); return(NormalizeIndex(index, collection, bias)); }