diff options
Diffstat (limited to '')
-rw-r--r-- | Makefile | 2 | ||||
-rw-r--r-- | strbuf.c | 33 | ||||
-rw-r--r-- | strbuf.h | 9 |
3 files changed, 17 insertions, 27 deletions
@@ -4,7 +4,7 @@ CC := gcc OBJDIR = obj -CPPFLAGS = -DSAFE_STR # -DSAFE_HASH +# CPPFLAGS = CFLAGS = $(CPPFLAGS) \ -std=gnu11 -Wall -Wextra \ -ggdb -fPIC \ @@ -3,9 +3,7 @@ #include <string.h> #include <stdio.h> -#ifdef SAFE_STR #include "err.h" -#endif INIT_F(strbuf) { INIT(strbuf, this, 1); @@ -30,10 +28,9 @@ int strbuf_realloc(strbuf* str, size_t len) { } FREE_F(strbuf) { -#ifdef SAFE_STR /* has already been freed */ if (this->mem == NULL) return 1; -#endif + free (this->mem); this->mem = NULL; this->alloc = 0; @@ -46,13 +43,13 @@ FREE_F(strbuf) { */ int strbuf_append(strbuf* s, char c) { int retval = 0; -#ifdef SAFE_STR + if (s->len + 1 > s->alloc) { s->alloc <<= 1; s->mem = realloc(s->mem, s->alloc); retval = 1; } -#endif + s->mem[s->len] = c; s->ptr = ++s->len; return retval; @@ -68,48 +65,44 @@ int strbuf_cap(strbuf* s) { int strbuf_copy(strbuf* dest, strbuf* src) { int retval = 0; -#ifdef SAFE_STR + if (dest->alloc < src->len) { - /* - * one extra octet allocated to have space for a finishing - * '\0'. - * */ + /* +1 in length is to have room for '\0'. */ strbuf_realloc(dest, src->len + 1); retval = 1; } -#endif + dest->len = src->len; memcpy(dest->mem, src->mem, src->len); return retval; } int strbuf_cmp(strbuf* a, strbuf* b) { -#ifdef SAFE_STR - if (a->alloc == 0 || b->alloc == 0) { + if (a == NULL || a->alloc == 0 || + b == NULL || b->alloc == 0) + { ERR("a or b not alloced"); return -1; } -#endif + return strncmp(a->mem, b->mem, a->len); } int strbuf_c(strbuf* a, char* b) { -#ifdef SAFE_STR - if (a->alloc == 0) { + if (a == NULL || a->alloc == 0) { ERR("a not allocated"); return -1; } -#endif + return strcmp(a->mem, b) == 0; } char* charat(strbuf* s, unsigned int idx) { -#ifdef SAFE_STR if (idx > s->len) { ERR("Index out of bounds"); return (char*) -1; } -#endif + return &s->mem[idx]; } @@ -21,10 +21,6 @@ typedef struct { } strbuf; /* - * TODO Check memmory allocation for last +1 byte for null. - */ - -/* * Init strbuf to size of 0 * Doesnt't call malloc. */ @@ -50,6 +46,7 @@ FREE_F(strbuf); * also see: strbuf_alloc_copy */ int strbuf_copy(strbuf* dest, strbuf* src); + int strbuf_cmp(strbuf* a, strbuf* b); int strbuf_c(strbuf* a, char* b); @@ -82,7 +79,7 @@ char* strbuf_cur(strbuf* s); int strbuf_reset(strbuf* s); /* - * Sets the length and seek ptr to 0, but doesn't touch the memmory. + * Sets the length and seek ptr to 0, but doesn't touch the memmory. */ int strbuf_soft_reset(strbuf* s); @@ -99,7 +96,7 @@ int strbuf_realloc_copy(strbuf* dest, strbuf* src); /* * Copies contents from src to dest, also allocating dest in the - * process. dest should not be initialized before this call. + * process. dest should not be initialized before this call. */ int strbuf_init_copy(strbuf* dest, strbuf* src); |