From 055198709bad82bafe4737fde1b2b03241d76dda Mon Sep 17 00:00:00 2001 From: khamidou Date: Thu, 5 Mar 2009 09:35:15 +0100 Subject: [PATCH] finished implementing dynamic strings package --- dynstring.c | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++- dynstring.h | 8 ++++++++ parse.c | 2 ++ 3 files changed, 62 insertions(+), 1 deletion(-) diff --git a/dynstring.c b/dynstring.c index b434157..2c692a6 100644 --- a/dynstring.c +++ b/dynstring.c @@ -32,7 +32,58 @@ struct dstring* alloc_after(struct dstring *before) if (s == NULL) fail("Unable to alloc() memory"); - TAILQ_INSERT_AFTER(dstrings_head, dstring, dstring, p) + TAILQ_INSERT_AFTER(dstrings_head, before, s, strings); + break; } } + + return ptr; +} + +void free_dstring(struct dstring *s) +{ + if (s == NULL) + return; + + TAILQ_REMOVE(&dstrings_head, s, strings); + + if (s->p != NULL) + free(s->p); + + free(s); + + return; +} + +void free_all_dstrings(void) +{ + struct dstring *s; + TAILQ_FOREACH(s, &dstrings_head, strings) { + TAILQ_REMOVE(&dstrings_head, s, strings); + free_dstring(s); + } +} +/* + break_after breaks a string after *s and allocates it after "before". + */ +struct dstring* break_after(struct dstring *before, char *s) +{ + if (before == NULL) + return NULL; + + int s_len = before->length - (s - p); /* the length of the string after s */ + + before->length = s - p; + + struct dstring *after = alloc_after(before); + *s = '\0'; /* terminate the string. FIXME: use realloc() */ + + after->p = calloc(s_len, sizeof(char)); + if (after->p == NULL) + fail("Unable to allocate memory "); + + memcpy(after->p, s, s_len); + after->length = s_len; + + return after; } diff --git a/dynstring.h b/dynstring.h index 0e7f890..b9811ce 100644 --- a/dynstring.h +++ b/dynstring.h @@ -12,4 +12,12 @@ struct dstring { TAILQ_HEAD(dstring_heads, dstring) dstrings_head; +void init_dynstring(void); +struct dstring* alloc_and_insert_string(size_t len); +struct dstring* alloc_after(struct dstring *before); +void free_dstring(struct dstring *s); +void free_all_dstrings(void); + +struct dstring* break_after(struct dstring *before, char *s); + #endif diff --git a/parse.c b/parse.c index 8a56aea..afd8ef9 100644 --- a/parse.c +++ b/parse.c @@ -1,4 +1,5 @@ #include +#include "dynstring.h" #include "parse.h" extern char *strndup (__const char *__string, size_t __n); @@ -43,6 +44,7 @@ void expect(int t) void init_parser(void) { TAILQ_INIT(&blocks_head); + init_dynstring(); } -- 2.43.0