/*
 * util.c
 */

#include <stdio.h>
#include <string.h>
#include <stdarg.h>

#include "util.h"

/*
 * Special versions of some string handling functions,
 * to avoid buffer overflows.
 */


/*
 * This always NUL-terminates the buffer, even if vsnprintf does not.
 */
void p_snprintf(char *buf, size_t maxsize, const char *fmt, ...)
{
    va_list args;

    va_start(args, fmt);
    vsnprintf(buf, maxsize, fmt, args);
    buf[maxsize - 1] = '\0';
    va_end(args);
}

void p_vsnprintf(char *buf, size_t maxsize, const char *fmt, va_list args)
{
    vsnprintf(buf, maxsize, fmt, args);
    buf[maxsize - 1] = '\0';
}

void p_strcpy(char *dest, const char *src, size_t maxsize)
{
    size_t len;

    len = strlen(src);
    if(len > maxsize - 1)
	len = maxsize - 1;

    memcpy(dest, src, len);
    dest[len] = '\0';
}

void p_strcat(char *dest, const char *src, size_t maxsize)
{
    size_t len_d, len_s;

    len_d = strlen(dest);
    len_s = strlen(src);

    if(len_d + len_s > maxsize - 1)
	len_s = maxsize - 1 - len_d;

    if(len_d < 1)
	return;

    memcpy(dest + len_d, src, len_s);
    dest[len_d + len_s] = '\0';
}


syntax highlighted by Code2HTML, v. 0.9.1