summaryrefslogtreecommitdiff
path: root/Libraries/LibC
diff options
context:
space:
mode:
authorWilliam McPherson <willmcpherson2@gmail.com>2019-11-29 17:22:06 +1100
committerAndreas Kling <awesomekling@gmail.com>2019-11-29 11:04:01 +0100
commit680fd3999efc9caa1698304e157cbef1308b48df (patch)
treed55080ece0f00b195c41232c8aac1fcb2151f9ac /Libraries/LibC
parent4ef6be82123ef7c1788db4725ad9f3c0d5a86746 (diff)
downloadserenity-680fd3999efc9caa1698304e157cbef1308b48df.zip
LibC: Implement bsearch
Nothing fancy, just a simple implementation of bsearch(3).
Diffstat (limited to 'Libraries/LibC')
-rw-r--r--Libraries/LibC/stdlib.cpp17
1 files changed, 15 insertions, 2 deletions
diff --git a/Libraries/LibC/stdlib.cpp b/Libraries/LibC/stdlib.cpp
index d0dc63e9fb..4a5f23fe6c 100644
--- a/Libraries/LibC/stdlib.cpp
+++ b/Libraries/LibC/stdlib.cpp
@@ -509,8 +509,21 @@ char* mkdtemp(char* pattern)
void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*))
{
- dbgprintf("FIXME(LibC): bsearch(%p, %p, %u, %u, %p)\n", key, base, nmemb, size, compar);
- ASSERT_NOT_REACHED();
+ int low = 0;
+ int high = nmemb - 1;
+ while (low <= high) {
+ int middle = (low + high) / 2;
+ void* middle_memb = const_cast<char*>((const char*)base + middle * size);
+ int comparison = compar(key, middle_memb);
+ if (comparison < 0)
+ high = middle - 1;
+ else if (comparison > 0)
+ low = middle + 1;
+ else
+ return middle_memb;
+ }
+
+ return NULL;
}
div_t div(int numerator, int denominator)