project_files/frontlib/util/util.c
changeset 7179 f84805e6df03
parent 7177 bf6cf4dd847a
child 7224 5143861c83bd
equal deleted inserted replaced
7177:bf6cf4dd847a 7179:f84805e6df03
       
     1 #include "util.h"
       
     2 
       
     3 #include <stddef.h>
       
     4 #include <stdarg.h>
       
     5 #include <stdlib.h>
       
     6 #include <string.h>
       
     7 #include <stdio.h>
       
     8 
       
     9 char *flib_asprintf(const char *fmt, ...) {
       
    10 	va_list argp;
       
    11 	va_start(argp, fmt);
       
    12 	char *result = flib_vasprintf(fmt, argp);
       
    13 	va_end(argp);
       
    14 	return result;
       
    15 }
       
    16 
       
    17 char *flib_vasprintf(const char *fmt, va_list args) {
       
    18 	char *result = NULL;
       
    19 	int requiredSize = vsnprintf(NULL, 0, fmt, args)+1;				// Figure out how much memory we need,
       
    20 	if(requiredSize>=0) {
       
    21 		char *tmpbuf = malloc(requiredSize);						// allocate it
       
    22 		if(tmpbuf) {
       
    23 			if(vsnprintf(tmpbuf, requiredSize, fmt, args)>=0) {		// and then do the actual formatting.
       
    24 				result = tmpbuf;
       
    25 				tmpbuf = NULL;
       
    26 			}
       
    27 		}
       
    28 		free(tmpbuf);
       
    29 	}
       
    30 	return result;
       
    31 }
       
    32 
       
    33 char *flib_strdupnull(const char *str) {
       
    34 	if(!str) {
       
    35 		return NULL;
       
    36 	}
       
    37 	return flib_asprintf("%s", str);
       
    38 }
       
    39 
       
    40 void *flib_bufdupnull(const void *buf, size_t size) {
       
    41 	if(!buf || size==0) {
       
    42 		return NULL;
       
    43 	}
       
    44 	void *result = malloc(size);
       
    45 	if(result) {
       
    46 		memcpy(result, buf, size);
       
    47 	}
       
    48 	return result;
       
    49 }