xref: /titanic_41/usr/src/lib/libbc/libc/gen/common/lsearch.c (revision cde2885fdf538266ee2a3b08dee2d5075ce8fa2b)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*      Copyright (c) 1984 AT&T */
23 /*        All Rights Reserved   */
24 
25 #pragma ident	"%Z%%M%	%I%	%E% SMI"  /* from S5R2 1.8 */
26 
27 /*LINTLIBRARY*/
28 /*
29  * Linear search algorithm, generalized from Knuth (6.1) Algorithm Q.
30  *
31  * This version no longer has anything to do with Knuth's Algorithm Q,
32  * which first copies the new element into the table, then looks for it.
33  * The assumption there was that the cost of checking for the end of the
34  * table before each comparison outweighed the cost of the comparison, which
35  * isn't true when an arbitrary comparison function must be called and when the
36  * copy itself takes a significant number of cycles.
37  * Actually, it has now reverted to Algorithm S, which is "simpler."
38  */
39 
40 typedef char *POINTER;
41 extern POINTER memcpy();
42 
43 POINTER
44 lsearch(key, base, nelp, width, compar)
45 register POINTER key;		/* Key to be located */
46 register POINTER base;		/* Beginning of table */
47 unsigned *nelp;			/* Pointer to current table size */
48 register unsigned width;	/* Width of an element (bytes) */
49 int (*compar)();		/* Comparison function */
50 {
51 	register POINTER next = base + *nelp * width;	/* End of table */
52 
53 	for ( ; base < next; base += width)
54 		if ((*compar)(key, base) == 0)
55 			return (base);	/* Key found */
56 	++*nelp;			/* Not found, add to table */
57 	return (memcpy(base, key, (int)width));	/* base now == next */
58 }
59