#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

#ifdef DMALLOC
#include <dmalloc.h>
#endif

#include "hash.h"

void hash_create(hash *table) {
  Tcl_InitHashTable(table,TCL_STRING_KEYS);
}

void hash_destroy(hash *table) {
  Tcl_HashEntry *entry;
  Tcl_HashSearch ptr;
  if((entry=Tcl_FirstHashEntry(table,&ptr))) {
    free(Tcl_GetHashValue(entry));
    while((entry=Tcl_NextHashEntry(&ptr))) {
      free(Tcl_GetHashValue(entry));
    }
  }
  Tcl_DeleteHashTable(table);
}

int hash_set(hash *table, const char *key, const char *value) {
  Tcl_HashEntry *entry;
  char *data;
  int newentry;
  if(!(data=strdup(value))) {
    return -1;
  } else {
    entry=Tcl_CreateHashEntry(table,key,&newentry);
    if(!newentry) free(Tcl_GetHashValue(entry));
    Tcl_SetHashValue(entry,data);
    return 0;
  }
}

char *hash_get(hash *table, const char *key) {
  Tcl_HashEntry *entry;
  if(!(entry=Tcl_FindHashEntry(table,key))) {
    return 0;
  } else {
    return((char *)Tcl_GetHashValue(entry));
  }
}

int hash_delete(hash *table, char *key) {
  Tcl_HashEntry *entry;
  if(!(entry=Tcl_FindHashEntry(table,key))) {
    return -1;
  } else {
    free(Tcl_GetHashValue(entry));
    Tcl_DeleteHashEntry(entry);
    return 0;
  }
}


syntax highlighted by Code2HTML, v. 0.9.1