diff options
author | Brecht Van Lommel <brechtvanlommel@pandora.be> | 2008-11-11 18:03:26 +0300 |
---|---|---|
committer | Brecht Van Lommel <brechtvanlommel@pandora.be> | 2008-11-11 18:03:26 +0300 |
commit | 3bb5fc9c7d10f7dec32f8d2a772fce69be468b15 (patch) | |
tree | 2acf79b72d49e35ac174cf8d122edcd8d15b1511 /source/blender/blenlib/intern/BLI_dynstr.c | |
parent | ade1495f0e6951bda3ae9852414d86e7c1fd624e (diff) |
* RNA: utility function to retrieve strings. It will use a fixed
size buffer if it's big enough, and otherwise allocate memory.
* Added BLI_dynstr_appendf() to construct strings easily in printf
style, this should make it easier to construct menu strings for
example.
Diffstat (limited to 'source/blender/blenlib/intern/BLI_dynstr.c')
-rw-r--r-- | source/blender/blenlib/intern/BLI_dynstr.c | 59 |
1 files changed, 56 insertions, 3 deletions
diff --git a/source/blender/blenlib/intern/BLI_dynstr.c b/source/blender/blenlib/intern/BLI_dynstr.c index 43c80dd24f0..1c539af2957 100644 --- a/source/blender/blenlib/intern/BLI_dynstr.c +++ b/source/blender/blenlib/intern/BLI_dynstr.c @@ -28,6 +28,8 @@ * Dynamically sized string ADT */ +#include <stdarg.h> +#include <stdio.h> #include <stdlib.h> #include <string.h> @@ -35,8 +37,10 @@ #include "BLI_blenlib.h" #include "BLI_dynstr.h" -#ifdef HAVE_CONFIG_H -#include <config.h> +#ifdef _WIN32 +#ifndef vsnprintf +#define vsnprintf _vsnprintf +#endif #endif /***/ @@ -63,7 +67,7 @@ DynStr *BLI_dynstr_new(void) { return ds; } -void BLI_dynstr_append(DynStr *ds, char *cstr) { +void BLI_dynstr_append(DynStr *ds, const char *cstr) { DynStrElem *dse= malloc(sizeof(*dse)); int cstrlen= strlen(cstr); @@ -79,6 +83,55 @@ void BLI_dynstr_append(DynStr *ds, char *cstr) { ds->curlen+= cstrlen; } +void BLI_dynstr_appendf(DynStr *ds, const char *format, ...) +{ + va_list args; + char *message, fixedmessage[256]; + int len= 256, maxlen= 65536, retval; + + while(1) { + if(len == sizeof(fixedmessage)) + message= fixedmessage; + else + message= MEM_callocN(sizeof(char)*len+1, "BLI_dynstr_appendf"); + + va_start(args, format); + retval= vsnprintf(message, len, format, args); + va_end(args); + + if(retval == -1) { + /* -1 means not enough space, but on windows it may also mean + * there is a formatting error, so we impose a maximum length */ + if(message != fixedmessage) + MEM_freeN(message); + message= NULL; + + len *= 2; + if(len > maxlen) { + fprintf(stderr, "BLI_dynstr_append text too long or format error.\n"); + break; + } + } + else if(retval > len) { + /* in C99 the actual length required is returned */ + if(message != fixedmessage) + MEM_freeN(message); + message= NULL; + + len= retval; + } + else + break; + } + + if(message) { + BLI_dynstr_append(ds, message); + + if(message != fixedmessage) + MEM_freeN(message); + } +} + int BLI_dynstr_get_len(DynStr *ds) { return ds->curlen; } |