aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--ctimeline.c8
-rw-r--r--xstring.c31
-rw-r--r--xstring.h5
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);