xref: /illumos-gate/usr/src/cmd/pgrep/idtab.c (revision 2a8bcb4efb45d99ac41c94a75c396b362c414f7f)
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 /*
23  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #include <libintl.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <libuutil.h>
31 
32 #include "idtab.h"
33 
34 #define	IDTAB_GROW	2	/* Table size multiplier on grow */
35 #define	IDTAB_DEFSIZE	16	/* Starting table size */
36 
37 void
idtab_create(idtab_t * idt)38 idtab_create(idtab_t *idt)
39 {
40 	(void) memset(idt, 0, sizeof (idtab_t));
41 }
42 
43 void
idtab_destroy(idtab_t * idt)44 idtab_destroy(idtab_t *idt)
45 {
46 	if (idt->id_data) {
47 		free(idt->id_data);
48 		idt->id_data = NULL;
49 		idt->id_nelems = idt->id_size = 0;
50 	}
51 }
52 
53 void
idtab_append(idtab_t * idt,idkey_t id)54 idtab_append(idtab_t *idt, idkey_t id)
55 {
56 	size_t size;
57 	void *data;
58 
59 	if (idt->id_nelems >= idt->id_size) {
60 		size = idt->id_size ? idt->id_size * IDTAB_GROW : IDTAB_DEFSIZE;
61 
62 		if (data = realloc(idt->id_data, sizeof (idkey_t) * size)) {
63 			idt->id_data = data;
64 			idt->id_size = size;
65 		} else {
66 			uu_die(gettext("Failed to grow table"));
67 		}
68 	}
69 
70 	idt->id_data[idt->id_nelems++] = id;
71 }
72 
73 static int
idtab_compare(const void * lhsp,const void * rhsp)74 idtab_compare(const void *lhsp, const void *rhsp)
75 {
76 	idkey_t lhs = *((idkey_t *)lhsp);
77 	idkey_t rhs = *((idkey_t *)rhsp);
78 
79 	if (lhs == rhs)
80 		return (0);
81 
82 	return (lhs > rhs ? 1 : -1);
83 }
84 
85 void
idtab_sort(idtab_t * idt)86 idtab_sort(idtab_t *idt)
87 {
88 	if (idt->id_data) {
89 		qsort(idt->id_data, idt->id_nelems,
90 		    sizeof (idkey_t), idtab_compare);
91 	}
92 }
93 
94 int
idtab_search(idtab_t * idt,idkey_t id)95 idtab_search(idtab_t *idt, idkey_t id)
96 {
97 	return (bsearch(&id, idt->id_data, idt->id_nelems,
98 	    sizeof (idkey_t), idtab_compare) != NULL);
99 }
100