30 #define DICT_INVALID_KEY ((char*)-1)
38 static void * mem_double(
void * ptr,
int size)
42 newptr = calloc(2*size, 1);
46 memcpy(newptr, ptr, size);
61 static char * xstrdup(
const char * s)
66 t = (
char*)malloc(strlen(s)+1) ;
95 for (hash=0, i=0 ; i<len ; i++) {
96 hash += (unsigned)key[i] ;
128 d->
val = (
char **)calloc(size,
sizeof(
char*));
129 d->
key = (
char **)calloc(size,
sizeof(
char*));
130 d->
hash = (
unsigned int *)calloc(size,
sizeof(
unsigned));
147 if (d==NULL) return ;
148 for (i=0 ; i<d->
size ; i++) {
181 for (i=0 ; i<d->
size ; i++) {
185 if (hash==d->
hash[i]) {
187 if (!strcmp(key, d->
key[i])) {
226 if (d==NULL || key==NULL)
return -1 ;
232 for (i=0 ; i<d->
size ; i++) {
235 if (hash==d->
hash[i]) {
236 if (!strcmp(key, d->
key[i])) {
240 d->
val[i] = val ? xstrdup(val) : NULL ;
252 d->
val = (
char **)mem_double(d->
val, d->
size *
sizeof(
char*)) ;
253 d->
key = (
char **)mem_double(d->
key, d->
size *
sizeof(
char*)) ;
254 d->
hash = (
unsigned int *)mem_double(d->
hash, d->
size *
sizeof(
unsigned)) ;
255 if ((d->
val==NULL) || (d->
key==NULL) || (d->
hash==NULL)) {
266 for (i=d->
n ; d->
key[i] ; ) {
267 if(++i == d->
size) i = 0;
270 d->
key[i] = xstrdup(key);
271 d->
val[i] = val ? xstrdup(val) : NULL ;
298 for (i=0 ; i<d->
size ; i++) {
302 if (hash==d->
hash[i]) {
304 if (!strcmp(key, d->
key[i])) {
316 if (d->
val[i]!=NULL) {
341 if (d==NULL || out==NULL) return ;
343 fprintf(out,
"empty dictionary\n");
346 for (i=0 ; i<d->
size ; i++) {
348 fprintf(out,
"%20s\t[%s]\n",
350 d->
val[i] ? d->
val[i] :
"UNDEF");
360 int main(
int argc,
char *argv[])
368 printf(
"allocating...\n");
372 printf(
"setting %d values...\n", NVALS);
373 for (i=0 ; i<NVALS ; i++) {
374 sprintf(cval,
"%04d", i);
377 printf(
"getting %d values...\n", NVALS);
378 for (i=0 ; i<NVALS ; i++) {
379 sprintf(cval,
"%04d", i);
382 printf(
"cannot get value for key [%s]\n", cval);
385 printf(
"unsetting %d values...\n", NVALS);
386 for (i=0 ; i<NVALS ; i++) {
387 sprintf(cval,
"%04d", i);
391 printf(
"error deleting values\n");
393 printf(
"deallocating...\n");
char * dictionary_get(dictionary *d, const char *key, char *def)
Get a value from a dictionary.
int main()
Main application.
void dictionary_unset(dictionary *d, const char *key)
Delete a key in a dictionary.
unsigned dictionary_hash(const char *key)
Compute the hash key for a string.
void dictionary_dump(dictionary *d, FILE *out)
Dump a dictionary to an opened file pointer.
dictionary * dictionary_new(int size)
Create a new dictionary object.
void dictionary_del(dictionary *d)
Delete a dictionary object.
int dictionary_set(dictionary *d, const char *key, const char *val)
Set a value in a dictionary.
Implements a dictionary for string variables.