Merge commit 'b1e7e97d3b60469b243b3b2e22c7d8cbd11c7c90'
[unleashed.git] / usr / src / cmd / pgrep / idtab.c
blobd76e73005e6ae536cd130d6dd7ded77a6be8961a
1 /*
2 * CDDL HEADER START
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.
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.
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]
20 * CDDL HEADER END
23 * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
24 * Use is subject to license terms.
27 #pragma ident "%Z%%M% %I% %E% SMI"
29 #include <libintl.h>
30 #include <string.h>
31 #include <stdlib.h>
32 #include <libuutil.h>
34 #include "idtab.h"
36 #define IDTAB_GROW 2 /* Table size multiplier on grow */
37 #define IDTAB_DEFSIZE 16 /* Starting table size */
39 void
40 idtab_create(idtab_t *idt)
42 (void) memset(idt, 0, sizeof (idtab_t));
45 void
46 idtab_destroy(idtab_t *idt)
48 if (idt->id_data) {
49 free(idt->id_data);
50 idt->id_data = NULL;
51 idt->id_nelems = idt->id_size = 0;
55 void
56 idtab_append(idtab_t *idt, idkey_t id)
58 size_t size;
59 void *data;
61 if (idt->id_nelems >= idt->id_size) {
62 size = idt->id_size ? idt->id_size * IDTAB_GROW : IDTAB_DEFSIZE;
64 if (data = reallocarray(idt->id_data, size, sizeof (idkey_t))) {
65 idt->id_data = data;
66 idt->id_size = size;
67 } else {
68 uu_die(gettext("Failed to grow table"));
72 idt->id_data[idt->id_nelems++] = id;
75 static int
76 idtab_compare(const void *lhsp, const void *rhsp)
78 idkey_t lhs = *((idkey_t *)lhsp);
79 idkey_t rhs = *((idkey_t *)rhsp);
81 if (lhs == rhs)
82 return (0);
84 return (lhs > rhs ? 1 : -1);
87 void
88 idtab_sort(idtab_t *idt)
90 if (idt->id_data) {
91 qsort(idt->id_data, idt->id_nelems,
92 sizeof (idkey_t), idtab_compare);
96 int
97 idtab_search(idtab_t *idt, idkey_t id)
99 return (bsearch(&id, idt->id_data, idt->id_nelems,
100 sizeof (idkey_t), idtab_compare) != NULL);