/src/openssl40/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 "internal/cryptlib.h" |
12 | | |
13 | | typedef int (*cmpthunk_fn)(const void *, const void *); |
14 | | const void *ossl_bsearch(const void *key, const void *base, int num, |
15 | | int size, int (*cmp)(const void *, const void *), |
16 | | int (*cmp_thunk)(cmpthunk_fn real_cmp_fn, const void *, const void *), |
17 | | int flags) |
18 | 41.4M | { |
19 | 41.4M | const char *base_ = base; |
20 | 41.4M | int l, h, i = 0, c = 0; |
21 | 41.4M | const char *p = NULL; |
22 | | |
23 | 41.4M | if (num == 0) |
24 | 0 | return NULL; |
25 | 41.4M | l = 0; |
26 | 41.4M | h = num; |
27 | 403M | while (l < h) { |
28 | 383M | i = l + (h - l) / 2; |
29 | 383M | p = &(base_[i * size]); |
30 | 383M | if (cmp_thunk != NULL) |
31 | 254k | c = cmp_thunk((cmpthunk_fn)cmp, key, (const void *)p); |
32 | 382M | else |
33 | 382M | c = cmp(key, p); |
34 | 383M | if (c < 0) |
35 | 244M | h = i; |
36 | 138M | else if (c > 0) |
37 | 117M | l = i + 1; |
38 | 20.8M | else |
39 | 20.8M | break; |
40 | 383M | } |
41 | 41.4M | if (c != 0 && !(flags & OSSL_BSEARCH_VALUE_ON_NOMATCH)) |
42 | 20.6M | p = NULL; |
43 | 20.8M | else if (c == 0 && (flags & OSSL_BSEARCH_FIRST_VALUE_ON_MATCH)) { |
44 | 144k | while (i > 0) { |
45 | 40.5k | if (cmp_thunk != NULL) { |
46 | 30.2k | if (cmp_thunk((cmpthunk_fn)cmp, key, (const void *)&(base_[(i - 1) * size]))) |
47 | 27.2k | break; |
48 | 30.2k | } else { |
49 | 10.2k | if (cmp(key, &(base_[(i - 1) * size]))) |
50 | 10.2k | break; |
51 | 10.2k | } |
52 | 3.02k | i--; |
53 | 3.02k | } |
54 | 141k | p = &(base_[i * size]); |
55 | 141k | } |
56 | 41.4M | return p; |
57 | 41.4M | } |