/** * Create a hashtable by conversion from a list of child-nodes * @param children add these nodes to the hashtable for starters * @return an initialised hashtable */ hashtable *hashtable_create( node *parent ) { hashtable *ht = calloc( 1, sizeof(hashtable) ); if ( ht != NULL ) { int nnodes = node_num_children( parent ); mem_usage += sizeof(hashtable); ht->nbuckets = nnodes*2; ht->items = calloc( ht->nbuckets, sizeof(struct bucket*) ); if ( ht->items != NULL ) { int res = 1; mem_usage += ht->nbuckets*sizeof(struct bucket*); node_iterator *iter = node_children( parent ); if ( iter != NULL ) { while ( res && node_iterator_has_next(iter) ) { node *temp = node_iterator_next( iter ); node_clear_next( temp ); res = hashtable_add( ht, temp ); } node_iterator_dispose( iter ); } else res = 0; if ( !res ) { hashtable_dispose( ht ); ht = NULL; } } else fprintf(stderr,"failed to allocate %d buckets\n",ht->nbuckets); } else fprintf(stderr,"hashtable: failed to allocate\n"); return ht; }
int main() { const int TABLE_SIZE = 101; int i; Hashtable* ht_str_str = new_hashtable(TABLE_SIZE); print_hashtable(ht_str_str); srand(time(NULL)); for (i = 0; i < TABLE_SIZE << 1; ++i) { int len = rand() % 100 + 1; int key_size = len + 1; char* strkey = (char*)malloc(key_size); if (strkey == NULL) { continue; } strkey[len] = '\0'; len--; while (len >= 0) { strkey[len] = (char)rand(); if (strkey[len] == '\0') { continue; } len--; } len = rand() % 100 + 1; int val_size = len + 1; char* strval = (char*)malloc(val_size); if (strval == NULL) { free(strkey); continue; } strval[len] = '\0'; len--; while (len >= 0) { strval[len] = (char)rand(); if (strval[len] == '\0') { continue; } len--; } hashtable_add(ht_str_str, (BYTE*)strkey, key_size, (BYTE*)strval, val_size); } print_hashtable(ht_str_str); /* the function strlen(const char* s) return the length of string s(not include the end char '\0')*/ hashtable_add(ht_str_str, (BYTE*)"hello world", strlen("hello world") + 1, (BYTE*)"f**k haitai", strlen("hello world") +1); printf("find :%d\n", hashtable_contains_key(ht_str_str, (BYTE*)"hello world", strlen("hello world") + 1)); printf("find :%d\n", hashtable_contains_key(ht_str_str, (BYTE*)"f**k world", strlen("f**k world") + 1)); char* pstr = (char*)hashtable_getval(ht_str_str, (BYTE*)"hello world", 12); printf("get :%s\n", pstr); free(pstr); print_hashtable(ht_str_str); BYTE* p = NULL; hashtable_add(ht_str_str, (BYTE*)&p, sizeof(p), (BYTE*)"The key is NULL", 16); int* k = NULL; pstr = (char*)hashtable_getval(ht_str_str, (BYTE*)&k, sizeof(k)); printf("'null' key's value :%s\n", pstr); free(pstr); hashtable_remove(ht_str_str, (BYTE*)&p, sizeof(p)); hashtable_empty(ht_str_str); //print_hashtable(ht_str_str); hashtable_dispose(ht_str_str); //print_hashtable(ht_str_str); getchar(); return 0; }