/**
 * @file       bsearch.c
 * @brief      Binary search implementation for Blowfish ASN1
 * @author     Ivan Vorobiov (i.vorobiov@samsung.com)
 * @version    1.0
 * @date       Created Nov 11, 2016
 * @copyright  In Samsung Ukraine R&D Center (SURC) under a contract between
 * @copyright  LLC "Samsung Electronics Ukraine Company" (Kiev, Ukraine) and
 * @copyright  "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
 * @copyright  Copyright: (c) Samsung Electronics Co, Ltd 2016. All rights reserved.
**/
/*
 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
 *
 * Licensed under the OpenSSL license (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */

#include <stdlib.h>


const void *bsearch(
    const void *key, const void *base_, size_t num, size_t size,
    int (*compar)(const void *, const void *)) {
  const char *base = base_;
  int left, right, i = 0, checker = 0;
  const char *p = NULL;

  if (num == 0) {
    return (NULL);
  }

  if (!key || !base || !compar) {
    return (NULL);
  }

  left = 0;
  right = num;
  while (left < right) {
    i = (left + right) / 2;
    p = &(base[i * size]);
    checker = (*compar) (key, p);
    if (checker < 0) {
      right = i;
    } else if (checker > 0) {
      left = i + 1;
    } else {
      break;
    }
  }

  return ((checker != 0) ? NULL : p);
}
