view dmstring.c @ 510:43ea59887c69

Start work on making C64 formats encoding possible by changing DMDecodeOps to DMEncDecOps and adding fields and op enums for custom encode functions, renaming, etc. Split generic op sanity checking into a separate function in preparation for its use in generic encoding function.
author Matti Hamalainen <ccr@tnsp.org>
date Mon, 19 Nov 2012 15:06:01 +0200
parents 32250b436bca
children 2726d91e3409
line wrap: on
line source

#include "dmlib.h"
#include <stdarg.h>

/* strdup with a NULL check
 */
char *dm_strdup(const char *s)
{
    char *res;
    if (s == NULL)
        return NULL;

    if ((res = dmMalloc(strlen(s) + 1)) == NULL)
        return NULL;

    strcpy(res, s);
    return res;
}


/* Simulate a sprintf() that allocates memory
 */
char *dm_strdup_vprintf(const char *fmt, va_list args)
{
    int size = 64;
    char *buf;

    if ((buf = dmMalloc(size)) == NULL)
        return NULL;

    while (1)
    {
        int n;
        va_list ap;
        va_copy(ap, args);
        n = vsnprintf(buf, size, fmt, ap);
        va_end(ap);

        if (n > -1 && n < size)
            return buf;
        if (n > -1)
            size = n + 1;
        else
            size *= 2;

        if ((buf = dmRealloc(buf, size)) == NULL)
            return NULL;
    }
}


char *dm_strdup_printf(const char *fmt, ...)
{
    char *res;
    va_list ap;

    va_start(ap, fmt);
    res = dm_strdup_vprintf(fmt, ap);
    va_end(ap);

    return res;
}