/* pdnmesh - a 2D finite element solver Copyright (C) 2001-2005 Sarod Yatawatta This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: hash.c,v 1.23 2005/02/22 03:26:01 sarod Exp $ */ /* generic hash table */ #include "types.h" #include #include #include /* for memset() */ /* initialize hash table */ void htbl_init(htbl *tbl, int hashtable_size, size_t datasize, unsigned int (*h)(const void *key), int (*match)(const void *key1, const void *key2), void (*destroy)(void *data)) { int i; if (((tbl)->table = (glist*)malloc(hashtable_size*sizeof(glist))) == NULL ) { fprintf(stderr,"%s: %d: no free memory\n",__FILE__,__LINE__); exit(1); } tbl->positions=hashtable_size; tbl->size=0; for (i=0; ipositions; i++) { glist_sorted_init(&(tbl->table[i]),datasize,destroy,match); } tbl->h=h; tbl->destroy=destroy; tbl->match=match; } /* destroy hash table */ void htbl_destroy(htbl* tbl) { int i; for (i=0; ipositions; i++) { glist_delete(&(tbl->table[i])); } free(tbl->table); memset(tbl,0,sizeof(htbl)); } /* insert data */ /* if data inserted return 0, else return 1 (data already there) */ int htbl_insert(htbl *tbl, const void *data) { int position; /* get hash key */ position=tbl->h(data)%tbl->positions; #ifdef DEBUG printf("hash position %d\n",position); #endif if (glist_sorted_insert(&(tbl->table[position]),data)) { tbl->size++; return(0); /* data inserted */ } /* else */ return(1); /* data not inserted: already exsists */ } /* remove data */ /* if data is removed return 0, else return 1 */ int htbl_remove(htbl *tbl,const void *data) { int position; /* get hash key */ position=tbl->h(data)%tbl->positions; #ifdef DEBUG printf("hash position %d\n",position); #endif if (glist_sorted_remove(&(tbl->table[position]),data)) { tbl->size--; return(0); /* data removed */ } /* else */ return(1); /* data not removed: not exsist*/ } /* lookup data and return address*/ /* if data not found, null is returned */ void * htbl_lookup(const htbl *tbl,const void *data) { int position; /* get hash key */ position=tbl->h(data)%tbl->positions; #ifdef DEBUG printf("hash position %d\n",position); #endif return(glist_sorted_lookup(&(tbl->table[position]),data)); }