00001 #include <stdio.h>
00002 #include <stdlib.h>
00003 #include <string.h>
00004 #include "table.h"
00005 #include "xassert.h"
00006 #include "xmem.h"
00007
00008 #define TRUE 1
00009 #define FALSE 0
00010
00011 void table_init(int maxsize, Table_t *S,
00012 int (*not_equal)(const void *, const void *))
00013 {
00014 S->not_equal = not_equal;
00015 if (maxsize>0)
00016 {
00017 S->data = (Entry_t *) malloc((size_t) maxsize * sizeof(Entry_t));
00018 XASSERT(S->data);
00019 }
00020 else
00021 S->data = NULL;
00022
00023 S->size = 0;
00024 S->maxsize = maxsize;
00025 }
00026
00027
00028 void table_copy(Table_t *dst, Table_t *src)
00029 {
00030 table_init(src->maxsize, dst, src->not_equal);
00031 dst->size = src->size;
00032 memcpy(dst->data, src->data, src->size*sizeof(Entry_t));
00033 }
00034
00035
00036
00037 void table_free(Table_t *S)
00038 {
00039 if (S->data)
00040 {
00041 free(S->data);
00042 S->data=NULL;
00043 }
00044 }
00045
00046 void table_insert(Table_t *S, const void *key, const void *value)
00047 {
00048 int i;
00049 Entry_t *tmp;
00050
00051 for(i=0; i<S->size; i++)
00052 if ( !(*S->not_equal)(key,S->data[i].key) )
00053 break;
00054
00055 if ( i>=S->maxsize )
00056 {
00057
00058 tmp = S->data;
00059 S->data = malloc(2*(S->maxsize+1)*sizeof(Entry_t));
00060 XASSERT(S->data);
00061 if (tmp)
00062 {
00063 memcpy(S->data, tmp, S->maxsize*sizeof(Entry_t));
00064 free(tmp);
00065 }
00066 S->maxsize = 2*(S->maxsize+1);
00067 ++S->size;
00068 }
00069 else
00070 {
00071
00072
00073 if ( i>=S->size )
00074 ++S->size;
00075 }
00076 S->data[i].key = key;
00077 S->data[i].value = value;
00078 }
00079
00080 int table_remove(Table_t *S, const void *key)
00081 {
00082 int i;
00083
00084 for(i=0; i < S->size; i++)
00085 {
00086 if ( !(*S->not_equal)(key,S->data[i].key) )
00087 {
00088 --S->size;
00089 S->data[i].value = S->data[S->size].value;
00090 S->data[i].key = S->data[S->size].key;
00091 return 0;
00092 }
00093 }
00094 return 1;
00095 }
00096
00097 const void *table_lookup(Table_t *S, const void *key)
00098 {
00099 int i;
00100
00101 for(i=0; i < S->size; i++)
00102 {
00103 if ( !(*S->not_equal)(key,S->data[i].key) )
00104 return S->data[i].value;
00105 }
00106 return NULL;
00107 }
00108
00109
00110 void table_map(Table_t *S, void (*f)(const void *key, const void *value))
00111 {
00112 int i;
00113
00114 for(i=0; i < S->size; i++)
00115 f(S->data[i].key, S->data[i].value);
00116 }
00117
00118 void table_map_data(Table_t *S, void (*f)(const void *key, const void *value, const void *data), const void *data)
00119 {
00120 int i;
00121
00122 for(i=0; i < S->size; i++)
00123 f(S->data[i].key, S->data[i].value, data);
00124 }
00125
00126 int table_member(Table_t *S, const void *key)
00127 {
00128 int i;
00129
00130 for(i=0; i < S->size; i++)
00131 {
00132 if ( !(*S->not_equal)(key,S->data[i].key) )
00133 return TRUE;
00134 }
00135 return FALSE;
00136 }
00137
00138 int table_len(Table_t *S)
00139 {
00140 return S->size;
00141 }