store known key/value pairs in c

后端 未结 4 373
孤独总比滥情好
孤独总比滥情好 2020-12-30 05:21

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

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 05:59

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

提交回复
热议问题