Skip to content

Instantly share code, notes, and snippets.

@ivan-krukov ivan-krukov/example.c
Last active Aug 29, 2015

What would you like to do?
Using sds with clib/list
//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;
//push a few
//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
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.