aboutsummaryrefslogtreecommitdiffstats
path: root/xstring.c
diff options
context:
space:
mode:
authorJoursoir <chat@joursoir.net>2021-05-19 07:40:42 +0000
committerJoursoir <chat@joursoir.net>2021-05-19 07:40:42 +0000
commit17c4d7a48c3c9bf7052b6a47d9e3bc66d554def4 (patch)
tree7f5fbea94a85bb44375f806236c08d40a937a085 /xstring.c
parentbbf29455ed723ef4e9be95033e7aca2ea6a72a91 (diff)
downloadctimeline-17c4d7a48c3c9bf7052b6a47d9e3bc66d554def4.tar.gz
ctimeline-17c4d7a48c3c9bf7052b6a47d9e3bc66d554def4.tar.bz2
ctimeline-17c4d7a48c3c9bf7052b6a47d9e3bc66d554def4.zip
xstring: make string assignment using string_(n)alloc
* Code in ctimeline have rewritten using updated function
Diffstat (limited to 'xstring.c')
-rw-r--r--xstring.c31
1 files changed, 20 insertions, 11 deletions
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;
}