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