Merge pull request #260 from pcc/topmost
[mono.git] / mono / utils / bsearch.c
1 /*
2  * bsearch () implementation. Needed because some broken platforms
3  * have implementations that have unreasonable, non-standard
4  * requirements (e.g. "key must not be null"). Taken from NetBSD
5  * with some minor modifications.
6  *
7  * Copyright (c) 1990, 1993
8  *      The Regents of the University of California.  All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #include "mono/utils/bsearch.h"
36
37 void *
38 mono_binary_search (
39         const void *key,
40         const void *array,
41         size_t array_length,
42         size_t member_size,
43         BinarySearchComparer comparer)
44 {
45         const char *base = array;
46         size_t lim;
47         int cmp;
48         const void *p;
49
50         for (lim = array_length; lim; lim >>= 1) {
51                 p = base + (lim >> 1) * member_size;
52                 cmp = (* comparer) (key, p);
53
54                 if (!cmp)
55                         return (void *) p;
56                 else if (cmp > 0) {
57                         base = (const char *) p + member_size;
58                         lim--;
59                 }
60         }
61
62         return NULL;
63 }