xref: /original-bsd/lib/libc/db/btree/bt_search.c (revision 16bc4816)
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Mike Olson.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #if defined(LIBC_SCCS) && !defined(lint)
12 static char sccsid[] = "@(#)bt_search.c	5.5 (Berkeley) 11/13/92";
13 #endif /* LIBC_SCCS and not lint */
14 
15 #include <sys/types.h>
16 
17 #include <db.h>
18 #include <stdio.h>
19 
20 #include "btree.h"
21 
22 /*
23  * __BT_SEARCH -- Search a btree for a key.
24  *
25  * Parameters:
26  *	t:	tree to search
27  *	key:	key to find
28  *	exactp:	pointer to exact match flag
29  *
30  * Returns:
31  *	EPG for matching record, if any, or the EPG for the location of the
32  *	key, if it were inserted into the tree.
33  *
34  * Warnings:
35  *	The EPG returned is in static memory, and will be overwritten by the
36  *	next search of any kind in any tree.
37  */
38 EPG *
39 __bt_search(t, key, exactp)
40 	BTREE *t;
41 	const DBT *key;
42 	int *exactp;
43 {
44 	register index_t index;
45 	register int base, cmp, lim;
46 	register PAGE *h;
47 	pgno_t pg;
48 	static EPG e;
49 
50 	for (pg = P_ROOT;;) {
51 		if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL)
52 			return (NULL);
53 
54 		/* Do a binary search on the current page. */
55 		e.page = h;
56 		for (base = 0, lim = NEXTINDEX(h); lim; lim >>= 1) {
57 			e.index = index = base + (lim >> 1);
58 			if ((cmp = __bt_cmp(t, key, &e)) == 0) {
59 				if (h->flags & P_BLEAF) {
60 					*exactp = 1;
61 					return (&e);
62 				}
63 				goto next;
64 			}
65 			if (cmp > 0) {
66 				base = index + 1;
67 				--lim;
68 			}
69 		}
70 
71 		/*
72 		 * No match found.  Base is the smallest index greater than
73 		 * key but may be an illegal index.  Use base if it's a leaf
74 		 * page, decrement it by one if it's an internal page.  This
75 		 * is safe because internal pages can't be empty.
76 		 */
77 		index = h->flags & P_BLEAF ? base : base - 1;
78 
79 		/* If it's a leaf page, we're done. */
80 		if (h->flags & P_BLEAF) {
81 			e.index = index;
82 			*exactp = 0;
83 			return (&e);
84 		}
85 
86 next:		if (__bt_push(t, h->pgno, index) == RET_ERROR)
87 			return (NULL);
88 		pg = GETBINTERNAL(h, index)->pgno;
89 		mpool_put(t->bt_mp, h, 0);
90 	}
91 }
92