I'm currently learning c. I'm writing a web server as an exercise.
Now i have to store the status codes and reason phrases.
What is the best way to store those key/value pairs?
My first bet was a hashmap. But there is no native implementation in c. So i would have to use a library.
Like other answers, I would also recommend just using an array of strings as a lookup table. If you assume all the status codes are unique, an array of strings is by far the easiest implementation for a smaller set of data.
Once you start storing larger amounts of data, that is when hashmaps start becoming useful. A lookup array is the solution here, but as you said you're learning C, you can actually implement a hashtable in native C by using dynamic memory (a critical concept to learn for C.) This website explains how to create a hashtable in C very well.
http://www.sparknotes.com/cs/searching/hashtables/section3.rhtml
Here is an alternative idea, which has the benefit of speed, while having some memory overhead.
Basically, the simplest form of hash table, where the hash function is the identity (code -> code), also known as lookup table.
To do so, knowing that HTTP status codes are limited to 5xx, you can assume 599 will be the highest you need, therefore you will create a table with 600 elements.
This table can be done like this:
const char * status_messages[600];
Initialisation is pretty simple:
/* initialize all with NULL's so invalid codes correspond to NULL pointers */
memset(status_messages, (int)NULL, 600 * sizeof(const char *));
/* ... */
status_messages[403] = "Forbidden";
status_messages[404] = "Not found";
/* ... */
Looking up a message is also dead-simple:
int code = 403;
const char * message = status_messages[code];
This array will be 2400 bytes large (4800 on 64-bit platforms), but the access time is guaranteed to be O(1).
I would use a sorted array.
You can define the array in any order, and sort it at run-time (once) with the qsort()
function. Then you can do binary searches using bsearch()
. The total number of response codes is small, a binary search will be very fast.
This has the advantage of not needing any external code, for something simple like this.
Maybe you can create a struct with the K\V in it.
Like so:
struct key_value
{
int key;
char* value;
};
struct key_value kv;
kv.key = 1;
kv.value = "foo";