From 4fc5243fa6c249c1f1e118f95f42870b7ccf8c6e Mon Sep 17 00:00:00 2001 From: mrb0nk500 Date: Tue, 26 Jul 2022 17:51:29 -0300 Subject: index: Add a function for converting an index into a string. --- index.c | 28 ++++++++++++++++++++++++++++ index.h | 1 + 2 files changed, 29 insertions(+) diff --git a/index.c b/index.c index 2571a61..d996b45 100644 --- a/index.c +++ b/index.c @@ -4,6 +4,17 @@ #include "index.h" #include "macros.h" +static int index_strlen(index *idx) { + int len = 0; + /* Get the length of the index. */ + for (index *i = idx; i != NULL; i = i->next) { + const int is_last = (i->next == NULL); + const char *fmt = (i->type) "%llu" : "%s"; + len += format_len(fmt, (i->type) ? i->num : i->name) + !is_last; + } + return len; +} + int is_valid_index(index *idx) { int did_alloc = 0; char *err_str = NULL; @@ -68,3 +79,20 @@ char *make_index_path(const char *root, index *idx, int path_type) { return path; } + +char *index_to_str(index *idx) { + if (is_valid_index(idx)) { + char *idx_str = calloc(index_strlen(idx)+1, sizeof(char)); + char *tmp = idx_str; + /* Create the index. */ + for (index *i = idx; i != NULL; i = i->next) { + const int is_last = (i->next == NULL); + const char *fmt = (i->type) "%llu%s" : "%s%s"; + + tmp += sprintf(tmp, fmt, (i->type) ? i->num : i->name, (!is_last) ? "-" : ""); + } + return idx_str; + } else { + return NULL; + } +} diff --git a/index.h b/index.h index af0ba68..d579d98 100644 --- a/index.h +++ b/index.h @@ -16,5 +16,6 @@ struct index { extern int is_valid_index(index *idx); extern char *make_index_path(const char *root, index *idx, int path_type); +extern char *index_to_str(index *idx); #endif -- cgit v1.2.3-13-gbd6f