Created
February 6, 2013 18:44
-
-
Save reagent/4724774 to your computer and use it in GitHub Desktop.
Dynamic header structs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
typedef struct Header { | |
char *key; | |
char *value; | |
} Header; | |
typedef struct Response { | |
Header **headers; | |
int headers_count; | |
} Response; | |
Header * | |
header_create(const char *key, char *value) | |
{ | |
Header *header = malloc(sizeof(Header)); | |
header->key = calloc(strlen(key) + 1, sizeof(char)); | |
strncpy(header->key, key, strlen(key)); | |
header->value = calloc(strlen(value) + 1, sizeof(char)); | |
strncpy(header->value, value, strlen(value)); | |
return header; | |
} | |
void | |
header_free(Header *header) | |
{ | |
free(header->key); | |
free(header->value); | |
free(header); | |
} | |
Response * | |
response_create() | |
{ | |
Response *response = malloc(sizeof(Response)); | |
response->headers = NULL; | |
response->headers_count = 0; | |
return response; | |
} | |
void | |
response_header_add(Response *response, const char *key, char *value) | |
{ | |
// This is inefficient since we only grow the allocation by 1, would be better to allocate multiple | |
// blocks at the same time and keep track of count vs. allocated, but that's premature optimization | |
// for this example. | |
response->headers = realloc(response->headers, (response->headers_count + 1) * sizeof(Header *)); | |
response->headers[response->headers_count] = header_create(key, value); | |
response->headers_count++; | |
} | |
void response_free(Response *response) | |
{ | |
int i = 0; | |
for (i = 0; i < response->headers_count; i++) { | |
header_free(response->headers[i]); | |
} | |
free(response->headers); | |
free(response); | |
} | |
int | |
main(void) | |
{ | |
int i = 0; | |
Response *response = response_create(); | |
response_header_add(response, "Content-Type", "text/html"); | |
response_header_add(response, "Content-Length", "1337"); | |
response_header_add(response, "Connection", "close"); | |
for (i = 0; i < response->headers_count; i++) { | |
printf("Header at position %d is: %s: %s\n", i, response->headers[i]->key, response->headers[i]->value); | |
} | |
response_free(response); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment