Last active
August 29, 2015 14:06
-
-
Save ivan-krukov/d3871745d7a935866bc9 to your computer and use it in GitHub Desktop.
Using sds with clib/list
This file contains hidden or 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
//A little function to allocate a length-1 sds from a char | |
//This is a little nasty, since we would need a lot of tiny mallocs if we do this often | |
sds sdsnewchar(char c) { | |
//Do some dirty allocations to save the char | |
char *ch = (char*)malloc(2*sizeof(char)); //culprit of small size allocation - could pre-allocate if we do this often | |
ch[0] = c; | |
ch[1] = '\0'; //zero-termination | |
sds str = sdsnew(ch); //new sds item, copied | |
free(ch); //sdsnew copies the content, so we can free | |
return str; | |
} | |
//This is a tiny example of how to properly use a list of sds elements | |
int main() { | |
//use the nasty little function | |
sds word = sdsnewchar('c'); | |
//sds can be printf-ed as a string! | |
printf("%s\n", word); | |
//new clib/list | |
list_t *tokens = list_new(); | |
//tell the list to deallocate elements with sdsfree - super handy | |
void (*sds_dealloc)() = &sdsfree; | |
tokens->free=sds_dealloc; | |
//push a few | |
list_rpush(tokens,list_node_new(word)); | |
list_rpush(tokens,list_node_new(sdsnew("woooot!"))); | |
//running iteration pointer | |
list_node_t *n; | |
//new iterator | |
list_iterator_t *iter = list_iterator_new(tokens,LIST_HEAD); | |
//double brackets to evaluate the result, not the assignment | |
while ((n = list_iterator_next(iter))) { | |
printf("%s\n", (sds)n->val); //note the sds cast | |
} | |
//cleam | |
list_iterator_destroy(iter); | |
//clean | |
list_destroy(tokens); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment