|
|
|
|
|
|
|
|
|
|
|
|
|
|
| #include <corecrt_internal.h>
|
| #include <search.h>
|
| #include <cfguard.h>
|
|
|
| #ifdef _M_CEE
|
| #define __fileDECL __clrcall
|
| #else
|
| #define __fileDECL __cdecl
|
| #endif
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
| #ifdef __USE_CONTEXT
|
| #define __COMPARE(context, p1, p2) (*compare)(context, p1, p2)
|
| #else
|
| #define __COMPARE(context, p1, p2) (*compare)(p1, p2)
|
| #endif
|
|
|
| #ifndef _M_CEE
|
| extern "C"
|
| DECLSPEC_GUARDNOCF
|
| #endif
|
|
|
| _CRT_SECURITYSAFECRITICAL_ATTRIBUTE
|
| #ifdef __USE_CONTEXT
|
| void* __fileDECL bsearch_s(
|
| void const* const key,
|
| void const* const base,
|
| size_t num,
|
| size_t const width,
|
| int (__fileDECL* const compare)(void*, void const*, void const*),
|
| void* const context
|
| )
|
| #else
|
| void* __fileDECL bsearch(
|
| void const* const key,
|
| void const* const base,
|
| size_t num,
|
| size_t const width,
|
| int (__fileDECL* const compare)(void const*, void const*)
|
| )
|
| #endif
|
| {
|
| _VALIDATE_RETURN(base != nullptr || num == 0, EINVAL, nullptr);
|
| _VALIDATE_RETURN(width > 0, EINVAL, nullptr);
|
| _VALIDATE_RETURN(compare != nullptr, EINVAL, nullptr);
|
|
|
| _GUARD_CHECK_ICALL(compare);
|
|
|
| char const* lo = reinterpret_cast<char const*>(base);
|
| char const* hi = reinterpret_cast<char const*>(base) + (num - 1) * width;
|
|
|
|
|
| __crt_state_management::scoped_global_state_reset saved_state;
|
|
|
|
|
|
|
|
|
|
|
| while (lo <= hi)
|
| {
|
| size_t const half = num / 2;
|
| if (half != 0)
|
| {
|
| char const* const mid = lo + (num & 1 ? half : (half - 1)) * width;
|
|
|
| int const result = __COMPARE(context, key, mid);
|
| if (result == 0)
|
| {
|
| return const_cast<void*>(static_cast<void const*>(mid));
|
| }
|
| else if (result < 0)
|
| {
|
| hi = mid - width;
|
| num = num & 1 ? half : half - 1;
|
| }
|
| else
|
| {
|
| lo = mid + width;
|
| num = half;
|
| }
|
| }
|
| else if (num != 0)
|
| {
|
| return __COMPARE(context, key, lo)
|
| ? nullptr
|
| : const_cast<void*>(static_cast<void const*>(lo));
|
| }
|
| else
|
| {
|
| break;
|
| }
|
| }
|
|
|
| return nullptr;
|
| }
|
|
|
| #undef __COMPARE
|
|
|