bsearch.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /*
  2. * Copyright 2019 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. #include <stddef.h>
  10. #include "internal/cryptlib.h"
  11. const void *ossl_bsearch(const void *key, const void *base, int num,
  12. int size, int (*cmp) (const void *, const void *),
  13. int flags)
  14. {
  15. const char *base_ = base;
  16. int l, h, i = 0, c = 0;
  17. const char *p = NULL;
  18. if (num == 0)
  19. return NULL;
  20. l = 0;
  21. h = num;
  22. while (l < h) {
  23. i = (l + h) / 2;
  24. p = &(base_[i * size]);
  25. c = (*cmp) (key, p);
  26. if (c < 0)
  27. h = i;
  28. else if (c > 0)
  29. l = i + 1;
  30. else
  31. break;
  32. }
  33. if (c != 0 && !(flags & OSSL_BSEARCH_VALUE_ON_NOMATCH))
  34. p = NULL;
  35. else if (c == 0 && (flags & OSSL_BSEARCH_FIRST_VALUE_ON_MATCH)) {
  36. while (i > 0 && (*cmp) (key, &(base_[(i - 1) * size])) == 0)
  37. i--;
  38. p = &(base_[i * size]);
  39. }
  40. return p;
  41. }