/*
** mg_str.c for  in 
** 
** Made by vianney rancurel
** Login   <vianney@epita.fr>
** 
** Started on  Wed Aug 25 12:13:42 1999 vianney rancurel
** Last update Thu Oct 28 20:15:37 1999 
*/
#include "mg.h"

/* catenates a string to a string.
   Dst must be a valid string.
   Returns 0 if OK, ERR_MG_BO on buffer overflows */
t_status	str_cat_str(dst,max_len,str)
char		*dst;
int		max_len;
char		*str;
{
  int		dst_len;
  int		str_len;

  dst_len = strlen(dst);
  str_len = strlen(str);
  if ((dst_len + str_len + 1) > max_len)
    return (ERR_MG_BO);
  strcpy(dst + dst_len,str);
  return (0);
}

/* catenates a char to a string.
   Dst must be a valid string.
   Returns 0 if OK, ERR_MG_BO on buffer overflows */
t_status	str_cat_char(dst,max_len,c)
char		*dst;
int		max_len;
int		c;
{
  int		dst_len;
  
  dst_len = strlen(dst);
  if ((dst_len + 1) > max_len)
    return (ERR_MG_BO);
  dst[dst_len] = c;
  dst[dst_len + 1] = 0;
  return (0);
}

/* catenates a buffer to a string.
   Dst must be a valid string. Note that there is no check of an
   eventual zero in buffer. It calls str_cat_char(3).
   Returns 0 if OK, ERR_MG_BO on buffer overflows */
t_status	str_cat_buf(dst,max_len,buf,len)
char		*dst;
int		max_len;
char		*buf;
int		len;
{
  int		i;
  t_status	status;

  i = 0;
  while (i < len)
    {
      if ((status = str_cat_char(dst,max_len,buf[i])) <0)
	return (status);
      i++;
    }
  return (0);
}

/* catenates a printf(3) format under a form of va_list to a string.
   Dst must be a valid string.
   Returns 0 if OK.

   Warning: vsnprintf(8) doesn't tell if buffer is overflown */
t_status	str_cat_fmt_va_list(dst,max_len,fmt,args)
char		*dst;
int		max_len;
char		*fmt;
va_list		args;
{
  int		dstlen;

  dstlen = strlen(dst);
  vsnprintf(dst + dstlen,max_len - dstlen,fmt,args);
  return (0);
}

/* catenates a printf(3) format to a string.
   Dst must be a valid string. 
   Returns 0 if OK.

   Warning: vsnprintf(8) doesn't tell if buffer is overflown */
#ifdef HAVE_STDARG_H
t_status	str_cat_fmt_va(char *dst,
			       int max_len,
			       char *fmt,...)
#else
t_status	str_cat_fmt_va(dst,max_len,fmt,va_alist)
char		*dst;
int		max_len;
char		*fmt;
va_dcl
#endif
{
  va_list	args;
  int		dstlen;
  
  dstlen = strlen(dst);
#ifdef HAVE_STDARG_H
  va_start(args,fmt);
#else
  va_start(args);
#endif
  vsnprintf(dst + dstlen,max_len - dstlen,fmt,args);
  va_end(args);
  return (0);
}

