From 17c4d7a48c3c9bf7052b6a47d9e3bc66d554def4 Mon Sep 17 00:00:00 2001 From: Joursoir Date: Wed, 19 May 2021 07:40:42 +0000 Subject: xstring: make string assignment using string_(n)alloc * Code in ctimeline have rewritten using updated function --- ctimeline.c | 8 ++++---- xstring.c | 31 ++++++++++++++++++++----------- xstring.h | 5 +++-- 3 files changed, 27 insertions(+), 17 deletions(-) diff --git a/ctimeline.c b/ctimeline.c index 6ecbca3..cfb4e05 100644 --- a/ctimeline.c +++ b/ctimeline.c @@ -69,10 +69,10 @@ struct ctimeline_branch *add_branch(const char *name) } br = &ctx.branches.list[ctx.branches.count-1]; - br->name = string_alloc(name); + br->name = string_alloc(NULL, name); br->age_from = 0; br->age_to = 0; - br->desc = string_alloc("No description"); + br->desc = string_alloc(NULL, "No description"); return br; } @@ -91,8 +91,8 @@ void handle_config_context(const char *name, const char *value) ctx.cur_branch->age_to = atoi(value); } else if(strcmp(name, "branch.desc") == 0) { - string_release(ctx.cur_branch->desc); - ctx.cur_branch->desc = string_alloc(value); + ctx.cur_branch->desc = string_alloc( + ctx.cur_branch->desc, value); } } diff --git a/xstring.c b/xstring.c index 17804f3..09c6bf3 100644 --- a/xstring.c +++ b/xstring.c @@ -3,27 +3,36 @@ #include "xstring.h" -string *string_alloc(const char *text) +string *string_alloc(string *str, const char *text) { - return string_nalloc(text, + return string_nalloc(str, text, (text) ? strlen(text) : INIT_LEN_STRING); } -string *string_nalloc(const char *text, size_t text_len) +string *string_nalloc(string *str, const char *text, size_t text_len) { - string *str = malloc(sizeof(string)); - str->s = malloc(sizeof(char) * (text_len + 1)); + if(!str) { + str = malloc(sizeof(string)); + str->s = malloc(sizeof(char) * (text_len + 1)); + str->capacity = text_len; + } + else { + if(text_len >= str->capacity) { + free(str->s); + str->s = malloc(sizeof(char) * (text_len + 1)); + str->capacity = text_len; + } + + } + if(text) { strncpy(str->s, text, text_len); - str->capacity = text_len; str->len = text_len; - str->s[text_len] = '\0'; } - else { + else str->len = 0; - str->capacity = text_len; - str->s[0] = '\0'; - } + + str->s[str->len] = '\0'; return str; } diff --git a/xstring.h b/xstring.h index 4a33e99..be11600 100644 --- a/xstring.h +++ b/xstring.h @@ -9,8 +9,9 @@ typedef struct tag_string { int capacity; } string; -string *string_alloc(const char *text); -string *string_nalloc(const char *text, size_t text_len); +string *string_alloc(string *str, const char *text); +string *string_nalloc(string *str, const char *text, + size_t text_len); void string_release(string *str); void string_reset(string *str); void string_addch(string *str, int ch); -- cgit v1.2.3-18-g5258