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.
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).