1 /* $Id: table.c,v 1.7 2005/10/06 13:08:28 sys-op Exp $
2 * -------------------------------------------------------
3 * Copyright (c) 1998-2002 Sebastian Kienzl <zap@riot.org>
4 * -------------------------------------------------------
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 */
15
16 #include "muh.h"
17 #include "table.h"
18
19 /* #define DEBUG */
20
21 /* c at it's best ;) */
add_item(void ** data,int elementsize,int * entries,int * indx)22 void **add_item( void **data, int elementsize, int *entries, int *indx )
23 {
24 int i;
25 int ind = -1;
26
27 for( i = 0; i < *entries; i++ ) {
28 if( !data[ i ] ) {
29 ind = i; /* xfree pointer found */
30 #ifdef DEBUG
31 printf( "using empty pointer at index %d.\n", ind );
32 #endif
33 }
34 }
35 if( ind < 0 ) { /* allocate new pointer */
36 data = ( void ** )xrealloc( data, ++( *entries ) * sizeof( void * ) );
37 ind = ( *entries - 1 );
38 #ifdef DEBUG
39 printf( "allocating new pointer. %d entries, index %d\n", *entries, ind );
40 #endif
41 }
42
43 data[ ind ] = ( void * )xmalloc( elementsize );
44
45 *indx = ind;
46
47 return data;
48 }
49
compact_table(void ** data,int * entries)50 void **compact_table( void **data, int *entries )
51 {
52 #ifdef DEBUG
53 int x = 0;
54 #endif
55 int i = *entries - 1;
56
57 while( i >= 0 ) {
58 if( !data[ i ] ) {
59 data = ( void ** )xrealloc( data, --( *entries ) * sizeof( void * ) );
60 if( !( *entries ) ) data = 0;
61 #ifdef DEBUG
62 x++;
63 #endif
64 }
65 else
66 i = -1;
67 i--;
68 }
69 #ifdef DEBUG
70 printf( "reduced %d (size %d)\n", x, *entries );
71 if( !*entries ) printf( "ignore: pointer-array is now empty\n" );
72 #endif
73 return data;
74 }
75
rem_item(void ** data,int number,int * entries)76 void **rem_item( void **data, int number, int *entries )
77 {
78 if( number >= 0 && number < *entries ) {
79 #ifdef DEBUG
80 printf( "deleting entry %d, compacting table: ", number );
81 #endif
82 xfree( data[ number ] );
83 data[ number ] = 0;
84 }
85 data = compact_table( data, entries );
86 return data;
87 }
88
free_table(void ** data,int * entries,int clear)89 void **free_table( void **data, int *entries, int clear )
90 {
91 int i;
92 for( i = 0; i < *entries; i++ ) {
93 if( data[ i ] ) xfree( data[ i ] );
94 }
95 xfree( data );
96
97 if( clear )
98 *entries = 0;
99
100 return 0;
101 }
102