From bacd3060202001a059911fe73ef0ac9aad2b35a9 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 30 Aug 2023 14:27:53 -0400 Subject: [PATCH] more better --- libfatstr/libfatstr.c | 63 ++++++++++++++++++++++++++++--------------- 1 file changed, 41 insertions(+), 22 deletions(-) diff --git a/libfatstr/libfatstr.c b/libfatstr/libfatstr.c index 453089c..9e4e27e 100644 --- a/libfatstr/libfatstr.c +++ b/libfatstr/libfatstr.c @@ -1,42 +1,35 @@ #include /* free(3), malloc(3), realloc(3) */ -#include /* strncpy(3) */ +#include /* strncpy(3), size_t */ #include "libfatstr.h" /* quick and dirty ASCII edition */ /* Size by which to grow memory allocations. */ -#define GROW_INTERVAL 100 - -struct FatStr * -FatStr_initialize(struct FatStr *p){ - - if((p->v = malloc((sizeof *(p->v)) * GROW_INTERVAL)) == NULL) - return NULL; /* who knows */ - p->a = GROW_INTERVAL; - p->s = 0; - return p; -} +static size_t FatStr_growinterval = 100; /* in sizeof chars */ struct FatStr * FatStr_append(struct FatStr *p, FatStr_scalar_t c){ FatStr_vector_t t; - if(p->s + 1 > p->a){ - if((t = realloc(p->v, (sizeof *(p->v)) * (p->a + GROW_INTERVAL))) - == NULL) - return NULL; - p->a += GROW_INTERVAL; - } + if(p == NULL || (p->s + (sizeof *(p->v)) > p->a + && FatStr_grow(p, FatStr_growinterval) == NULL)) + return NULL; (p->v)[(p->s)++] = c; + return p; +} + +struct FatStr * +FatStr_construct(struct FatStr *p){ + + return FatStr_grow(FatStr_initialize(p), FatStr_growinterval); } -/* retval will need to be freed */ char * FatStr_convert(struct FatStr *p){ char *r; /* allocation might be wrong */ - return ((r = malloc(p->s * (sizeof *(p->v)))) == NULL) + return (p == NULL || (r = malloc(p->s * (sizeof *(p->v)))) == NULL) ? NULL : strncpy(r, p->v, p->s) ; @@ -44,10 +37,36 @@ FatStr_convert(struct FatStr *p){ struct FatStr * FatStr_destruct(struct FatStr *p){ - free(p->v); + + if(p != NULL){ + free(p->v); + FatStr_initialize(p); + } return NULL; } struct FatStr * -FatStr_trimfront(){ +FatStr_grow(struct FatStr *p, size_t units){ + FatStr_vector_t t; + + if(p == NULL || (t = realloc(p->v, p->a + units)) == NULL) + return NULL; + p->a += units; + p->v = t; + return p; +} + +struct FatStr * +FatStr_initialize(struct FatStr *p){ + + if(p != NULL){ + p->a = 0; + p->s = 0; + p->v = NULL; + } + return p; +} + +struct FatStr * +FatStr_trimfront(struct FatStr *p, size_t units){ }