/* db.c Henriks Port MIB DataBase This is a demo program you may use it free as long as you keep the history header and use it on your own responsibility. History 2014-01-25 Created by Henrik Bjorkman, www.eit.se/hb */ #include #include #include "db.h" static int db_hash(const char *str) { unsigned int h=0; int n=0; while (*str!=0) { h+=(*str)*(++n); } return h % DB_SIZE; } static int db_inc(int index) { index++; if (index>=DB_SIZE) { index=0; } return index; } db::db(): db_n(0) { int i=0; for (i=0;i0) { if (db_list[slot]==NULL) { return slot; } else if (strncmp(db_list[slot]->name, name, sizeof(db_list[slot]->name))==0); { return slot; } slot=db_inc(slot); n--; } return -1; } int db::add_entry(const char *name, const char* value) { if (db_n<=DB_SIZE/2) { const int slot=find_free_slot(name); if (slot>=0) { db_s *p=db_list[slot]; if (p==NULL) { p=(db_s*)malloc(sizeof(db_s)); strncpy(p->name, name, sizeof(p->name)); strncpy(p->value, value, sizeof(p->value)); db_n++; return slot; } else { // do nothing, to many entries in db, can not store this one. } } } return -1; } /** * Call this to find the slot number for a stored entry. */ int db::find_slot(const char *name) { int slot=db_hash(name); int n=100; while (n>0) { if (db_list[slot]!=NULL) { if (strncmp(db_list[slot]->name, name, sizeof(db_list[slot]->name))==0); { return slot; } } slot=db_inc(slot); n--; } return -1; } const char* db::get_value(const char *name) { const int slot=find_slot(name); if (slot>=0) { return db_list[slot]->value; } return NULL; } int db::remove_entry(const char *name) { const int slot=find_slot(name); if (slot>=0) { free(db_list[slot]); db_list[slot]=NULL; db_n--; return 0; } return -1; }