/src/openssl/crypto/bsearch.c
Line | Count | Source |
1 | | /* |
2 | | * Copyright 2019-2026 The OpenSSL Project Authors. All Rights Reserved. |
3 | | * |
4 | | * Licensed under the Apache License 2.0 (the "License"). You may not use |
5 | | * this file except in compliance with the License. You can obtain a copy |
6 | | * in the file LICENSE in the source distribution or at |
7 | | * https://www.openssl.org/source/license.html |
8 | | */ |
9 | | |
10 | | #include <stddef.h> |
11 | | #include <limits.h> |
12 | | #include "internal/cryptlib.h" |
13 | | |
14 | | typedef int (*cmpthunk_fn)(const void *, const void *); |
15 | | const void *ossl_bsearch(const void *key, const void *base, int num, |
16 | | int size, int (*cmp)(const void *, const void *), |
17 | | int (*cmp_thunk)(cmpthunk_fn real_cmp_fn, const void *, const void *), |
18 | | int flags) |
19 | 0 | { |
20 | 0 | const char *base_ = base; |
21 | 0 | int l, h, i = 0, c = 0; |
22 | 0 | const char *p = NULL; |
23 | |
|
24 | 0 | if (num <= 0 || size <= 0 || num > INT_MAX / size) |
25 | 0 | return NULL; |
26 | 0 | l = 0; |
27 | 0 | h = num; |
28 | 0 | while (l < h) { |
29 | 0 | i = l + (h - l) / 2; |
30 | 0 | p = &(base_[i * size]); |
31 | 0 | if (cmp_thunk != NULL) |
32 | 0 | c = cmp_thunk((cmpthunk_fn)cmp, key, (const void *)p); |
33 | 0 | else |
34 | 0 | c = cmp(key, p); |
35 | 0 | if (c < 0) |
36 | 0 | h = i; |
37 | 0 | else if (c > 0) |
38 | 0 | l = i + 1; |
39 | 0 | else |
40 | 0 | break; |
41 | 0 | } |
42 | 0 | if (c != 0 && !(flags & OSSL_BSEARCH_VALUE_ON_NOMATCH)) |
43 | 0 | p = NULL; |
44 | 0 | else if (c == 0 && (flags & OSSL_BSEARCH_FIRST_VALUE_ON_MATCH)) { |
45 | 0 | while (i > 0) { |
46 | 0 | if (cmp_thunk != NULL) { |
47 | 0 | if (cmp_thunk((cmpthunk_fn)cmp, key, (const void *)&(base_[(i - 1) * size]))) |
48 | 0 | break; |
49 | 0 | } else { |
50 | 0 | if (cmp(key, &(base_[(i - 1) * size]))) |
51 | 0 | break; |
52 | 0 | } |
53 | 0 | i--; |
54 | 0 | } |
55 | 0 | p = &(base_[i * size]); |
56 | 0 | } |
57 | 0 | return p; |
58 | 0 | } |