Changeset 90811 in webkit for trunk/Source/JavaScriptCore/wtf/StdLibExtras.h
- Timestamp:
- Jul 12, 2011, 3:14:30 AM (14 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/Source/JavaScriptCore/wtf/StdLibExtras.h
r90117 r90811 124 124 } 125 125 126 enum BinarySearchMode { 127 KeyMustBePresentInArray, 128 KeyMustNotBePresentInArray 129 }; 130 126 131 // Binary search algorithm, calls extractKey on pre-sorted elements in array, 127 132 // compares result with key (KeyTypes should be comparable with '--', '<', '>'). 128 // Optimized for cases where the array contains the key, checked by assertions.129 133 template<typename ArrayType, typename KeyType, KeyType(*extractKey)(ArrayType*)> 130 inline ArrayType* binarySearch(ArrayType* array, size_t size, KeyType key )134 inline ArrayType* binarySearch(ArrayType* array, size_t size, KeyType key, BinarySearchMode mode = KeyMustBePresentInArray) 131 135 { 132 // The array must contain at least one element (pre-condition, array does con atin key).133 // If the array only containsone element, no need to do the comparison.136 // The array must contain at least one element (pre-condition, array does contain key). 137 // If the array contains only one element, no need to do the comparison. 134 138 while (size > 1) { 135 139 // Pick an element to check, half way through the array, and read the value. 136 140 int pos = (size - 1) >> 1; 137 141 KeyType val = extractKey(&array[pos]); 138 142 139 143 // If the key matches, success! 140 144 if (val == key) … … 150 154 } 151 155 152 // 'size' should never reach zero. 153 ASSERT(size); 156 // In case of BinarySearchMode = KeyMustBePresentInArray 'size' should never reach zero. 157 if (mode == KeyMustBePresentInArray) 158 ASSERT(size); 154 159 } 155 156 // If we reach this point we've chopped down to one element, no need to check it matches 157 ASSERT(size == 1); 158 ASSERT(key == extractKey(&array[0])); 160 161 // In case of BinarySearchMode = KeyMustBePresentInArray if we reach this point 162 // we've chopped down to one element, no need to check it matches 163 if (mode == KeyMustBePresentInArray) { 164 ASSERT(size == 1); 165 ASSERT(key == extractKey(&array[0])); 166 } 167 159 168 return &array[0]; 160 169 }
Note:
See TracChangeset
for help on using the changeset viewer.