/** * Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved. * 内部基础模块,所有参数合法性由调用者保证 */ #ifndef BINARY_SEARCH_C_ #define BINARY_SEARCH_C_ #include "c_base.h" #ifdef __cplusplus extern "C" { #endif typedef void *(*FnBinaryGet)(void *appInfo, size_t id); typedef int (*FnBinaryCompare)(void *a, void *b, void *appInfo); static inline int BinarySearchClosest( void *appInfo, size_t size, void *key, FnBinaryGet fnBinaryGet, FnBinaryCompare fnComp, size_t *closestIndex) { if (size == 0) { *closestIndex = 0; return -1; } size_t left = 0; size_t right = size - 1; size_t mid; int compRet = 0; while (left <= right) { mid = (left + right) >> 1; void *midData = fnBinaryGet(appInfo, mid); compRet = fnComp(key, midData, appInfo); if (compRet > 0) { left = mid + 1; } else if (compRet < 0) { if (mid == 0) { break; } right = mid - 1; } else { *closestIndex = mid; return 0; } } *closestIndex = mid; return compRet; }; #ifdef __cplusplus } #endif #endif