token.c (1138B)
1 /* See LICENSE file for copyright and license details. */ 2 3 #include "token.h" 4 5 struct token { 6 char* name; 7 char* value; 8 }; 9 typedef struct token Token; 10 11 Token* new_token(char* name, char* value) { 12 Token* token = malloc(sizeof(Token)); 13 token->name = name; 14 token->value = value; 15 return token; 16 } 17 18 void free_token(Token* token) { 19 free(token->name); 20 free(token->value); 21 free(token); 22 } 23 24 Token** tokens = NULL; 25 size_t tokens_len = 0; 26 27 void free_tokens() { 28 for (size_t i = 0; i < tokens_len; i++) { 29 free_token(tokens[i]); 30 } 31 free(tokens); 32 tokens = NULL; 33 } 34 35 void add_token(Token* token) { 36 tokens = realloc(tokens, sizeof(Token) * ++tokens_len); 37 tokens[tokens_len - 1] = token; 38 } 39 40 void add_new_token(char* name, char* value) { 41 Token* token = new_token(name, value); 42 add_token(token); 43 } 44 45 char* find_in_tokens(const char* name, size_t length) { 46 // O(n) = n, but I don't worry about it right now 47 for (size_t i = 0; i < tokens_len; i++) { 48 if (strncmp(tokens[i]->name, name, length) == 0) { 49 return tokens[i]->value; 50 } 51 } 52 return NULL; 53 } 54