#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <fcntl.h>
#include <unistd.h>
//#include "socket.h"
void raise(const char* msg) {
printf("\n\n%s\n\n", msg);
exit(-1);
}
class StringHash {
public:
StringHash() {
allocSize = 20;
hashSize = 0;
hkeys = new char*[allocSize];
if(hkeys == NULL) {raise("Allocation failure in StringHash::StringHash() (1)");}
values = new char*[allocSize];
if(values == NULL) {raise("Allocation failure in StringHash::StringHash() (2)");}
}
~StringHash() {
for(int i = 0; i < hashSize; ++i) {
delete hkeys[i];
delete values[i];
}
delete hkeys;
delete values;
}
const char* operator[](const char* key) {
for(int i = 0; i < hashSize; ++i) {
if(strcmp(hkeys[i], key) == 0) {return values[i];}
}
return NULL;
}
void addEntry(const char* key, const char* value) {
//void operator[]=(const char* key, const char* value) {
if(hashSize == allocSize) {
allocSize += 20;
char** tempKeys = new char*[allocSize];
if(tempKeys == NULL) {raise("Allocation failure in StringHash::addEntry() (1)");}
char** tempVals = new char*[allocSize];
if(tempVals == NULL) {raise("Allocation failure in StringHash::addEntry() (2)");}
for(int i = 0; i < hashSize; ++i) {
tempKeys[i] = hkeys[i];
tempVals[i] = values[i];
}
delete hkeys;
hkeys = tempKeys;
delete values;
values = tempVals;
}
int keyLen = strlen(key) + 1;
int valLen = strlen(value) + 1;
hkeys[hashSize] = new char[keyLen];
if(hkeys[hashSize] == NULL) {raise("Allocation failure in StringHash::addEntry() (3)");}
memset(hkeys[hashSize], 0, keyLen);
strcpy(hkeys[hashSize], key);
values[hashSize] = new char[valLen];
if(values[hashSize] == NULL) {raise("Allocation failure in StringHash::addEntry() (4)");}
memset(values[hashSize], 0, valLen);
strcpy(values[hashSize], value);
++hashSize;
}
const char** keys() {
return (const char**)hkeys;
}
int size() {
return hashSize;
}
private:
int allocSize;
int hashSize;
char** hkeys;
char** values;
};
int main() {
StringHash hash;
hash.addEntry("test", "This is a test\n");
//hash["test"] = "This is a test";
printf(hash["test"]);
return 0;
}