Skip to content

Instantly share code, notes, and snippets.

@AleksLitynski
Created April 17, 2018 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AleksLitynski/0db58bc2b727389215dae66aa9aece10 to your computer and use it in GitHub Desktop.
Save AleksLitynski/0db58bc2b727389215dae66aa9aece10 to your computer and use it in GitHub Desktop.
// prints the tag tree 'self' into an sds string 'printed'
// recursive function, 'node_addr' should start at 0
sds _ts_tags_print_node(ts_tags * self, size_t node_addr, sds padding, sds printed) {
/*
return value should resemble this structure:
.
|── 0
│ |── abc123
| +── abc124
+── 1
*/
// get a reference to the current node
ts_tag_node * current = self->data + node_addr;
// if we're at a leaf node, print the value of the node
if(current->type == TS_TAG_NODE_LEAF) {
sds id_str = ts_id_nbit_string(&(current->value.leaf), sdsempty(), 8);
printed = sdscatprintf(printed, "%s+-- %s\n", padding, id_str);
sdsfree(id_str);
}
// if we're at an inner node...
if(current->type == TS_TAG_NODE_INNER) {
// the indentation before the next layer of the tree may or may not need a '|' before it,
// so prepare both indentations
sds extendedpadding = sdscatprintf(sdsempty(), "%s| ", padding);
sds emptypadding = sdscatprintf(sdsempty(), "%s ", padding);
// print first branch
if(current->value.inner[0] != 0) {
char * tee = "|";
sds currentpadding = extendedpadding;
// if there is no second branch, print a cap after the first branch
if(current->value.inner[1] == 0) {
tee = "+";
currentpadding = emptypadding;
}
// recurse to follow the branch
printed = sdscatprintf(printed, "%s%s-- 0\n", padding, tee);
printed = _ts_tags_print_node(self, current->value.inner[0], currentpadding, printed);
}
// print second branch
if(current->value.inner[1] != 0) {
// recurse to follow the branch
printed = sdscatprintf(printed, "%s+-- 1\n", padding);
printed = _ts_tags_print_node(self, current->value.inner[1], emptypadding, printed);
}
sdsfree(extendedpadding);
sdsfree(emptypadding);
}
return printed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment