#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <fcntl.h>
#include <unistd.h>
//#include "socket.h"
#define STRINGHASH_ALLOC_INCREMENT 20
void raise(const char* msg) {
printf("\n\n%s\n\n", msg);
exit(-1);
}
class StringHashHelper {
public:
StringHashHelper() {
data = NULL;
}
StringHashHelper(const char* input) {
setData(input);
}
~StringHashHelper() {
if(data != NULL) {delete [] data;}
}
operator const char*() {
return (const char*)data;
}
void operator=(const char* input) {
setData(input);
}
private:
char* data;
void setData(const char* input) {
if(data != NULL) {delete [] data;}
int inLen = strlen(input) + 1;
data = new char[inLen];
if(data == NULL) {raise("Allocation failure in StringHashHelper::operator=()");}
strcpy(data, input);
}
};
class StringHash {
public:
StringHash() {
allocSize = STRINGHASH_ALLOC_INCREMENT;
hashSize = 0;
hkeys = new char*[allocSize];
if(hkeys == NULL) {raise("Allocation failure in StringHash::StringHash() (1)");}
values = new StringHashHelper[allocSize];
if(values == NULL) {raise("Allocation failure in StringHash::StringHash() (2)");}
}
~StringHash() {
for(int i = 0; i < hashSize; ++i) {delete [] hkeys[i];}
delete [] hkeys;
delete [] values;
}
StringHashHelper &operator[](const char* key) {
for(int i = 0; i < hashSize; ++i) {
if(strcmp(hkeys[i], key) == 0) {return values[i];}
}
if(hashSize == allocSize) {
allocSize += STRINGHASH_ALLOC_INCREMENT;
char** tempKeys = new char*[allocSize];
if(tempKeys == NULL) {raise("Allocation failure in StringHash::addEntry() (1)");}
StringHashHelper* tempVals = new StringHashHelper[allocSize];
if(tempVals == NULL) {raise("Allocation failure in StringHash::addEntry() (2)");}
int tkl;
for(int i = 0; i < hashSize; ++i) {
tempKeys[i] = hkeys[i];
tempVals[i] = (const char*)values[i];
}
delete [] hkeys;
hkeys = tempKeys;
delete [] values;
values = tempVals;
}
int keyLen = strlen(key) + 1;
hkeys[hashSize] = new char[keyLen];
if(hkeys[hashSize] == NULL) {raise("Allocation failure in StringHash::addEntry() (3)");}
strcpy(hkeys[hashSize], key);
return values[hashSize++];
}
const char** keys() {
return (const char**)hkeys;
}
int size() {
return hashSize;
}
void show() {
for(int i = 0; i < hashSize; ++i) {
printf("%i) \"", i);
printf(hkeys[i]);
printf("\" -> \"");
printf(values[i]);
printf("\"\n");
}
}
private:
int allocSize;
int hashSize;
char** hkeys;
StringHashHelper* values;
};
int main() {
StringHash hash;
hash["a"] = "This is a test.\n";
hash["b"] = "This is a second line.\n";
hash["c"] = "The test has three lines.\n";
printf(hash["a"]);
printf(hash["c"]);
printf(hash["b"]);
printf(hash["a"]);
return 0;
}