view dmstring.c @ 0:32250b436bca

Initial re-import.
author Matti Hamalainen <ccr@tnsp.org>
date Fri, 28 Sep 2012 01:54:23 +0300
parents
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;
}