[codex] Match MSL bsearch #108

Merged
coah80 merged 1 commits from agent/continue-0922/tools-bsearch into main 2026-09-22 05:22:43 +00:00
2 changed files with 44 additions and 1 deletions

View File

@@ -1947,7 +1947,7 @@ config.libs = [
Object(Matching, "MSL_Common/ctype.c"),
Object(NonMatching, "MSL_Common/locale.c"),
Object(Matching, "MSL_Common/arith.c"),
Object(NonMatching, "MSL_Common/bsearch.c"),
Object(Matching, "MSL_Common/bsearch.c"),
Object(NonMatching, "MSL_Common/buffer_io.c"),
Object(NonMatching, "MSL_Common/direct_io.c"),
Object(NonMatching, "MSL_Common/file_io.c"),

View File

@@ -0,0 +1,43 @@
#include <search.h>
void* bsearch(const void* key, const void* ptr, size_t count, size_t size, COMPARE_FUNC comp) {
const char* p;
int cmp;
size_t low, high, mid;
if (key == NULL || ptr == NULL || count == 0 || size == 0 || comp == NULL) {
return NULL;
}
p = (const char*)ptr;
cmp = comp(key, p);
if (cmp == 0) {
return (void*)p;
}
if (cmp < 0) {
return NULL;
}
low = 1;
high = count - 1;
while (low <= high) {
mid = (low + high) >> 1;
p = (const char*)ptr + size * mid;
cmp = comp(key, p);
if (cmp == 0) {
return (void*)p;
}
if (cmp < 0) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return NULL;
}