Blame gl/vsnprintf.c

Packit 549fdc
/* Formatted output to strings.
Packit 549fdc
   Copyright (C) 2004, 2006-2016 Free Software Foundation, Inc.
Packit 549fdc
   Written by Simon Josefsson and Yoann Vandoorselaere <yoann@prelude-ids.org>.
Packit 549fdc
Packit 549fdc
   This program is free software; you can redistribute it and/or modify
Packit 549fdc
   it under the terms of the GNU Lesser General Public License as published by
Packit 549fdc
   the Free Software Foundation; either version 2.1, or (at your option)
Packit 549fdc
   any later version.
Packit 549fdc
Packit 549fdc
   This program is distributed in the hope that it will be useful,
Packit 549fdc
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 549fdc
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Packit 549fdc
   GNU Lesser General Public License for more details.
Packit 549fdc
Packit 549fdc
   You should have received a copy of the GNU Lesser General Public License along
Packit 549fdc
   with this program; if not, see <http://www.gnu.org/licenses/>.  */
Packit 549fdc
Packit 549fdc
#ifdef HAVE_CONFIG_H
Packit 549fdc
# include <config.h>
Packit 549fdc
#endif
Packit 549fdc
Packit 549fdc
/* Specification.  */
Packit 549fdc
#include <stdio.h>
Packit 549fdc
Packit 549fdc
#include <errno.h>
Packit 549fdc
#include <limits.h>
Packit 549fdc
#include <stdarg.h>
Packit 549fdc
#include <stdlib.h>
Packit 549fdc
#include <string.h>
Packit 549fdc
Packit 549fdc
#include "vasnprintf.h"
Packit 549fdc
Packit 549fdc
/* Print formatted output to string STR.  Similar to vsprintf, but
Packit 549fdc
   additional length SIZE limit how much is written into STR.  Returns
Packit 549fdc
   string length of formatted string (which may be larger than SIZE).
Packit 549fdc
   STR may be NULL, in which case nothing will be written.  On error,
Packit 549fdc
   return a negative value.  */
Packit 549fdc
int
Packit 549fdc
vsnprintf (char *str, size_t size, const char *format, va_list args)
Packit 549fdc
{
Packit 549fdc
  char *output;
Packit 549fdc
  size_t len;
Packit 549fdc
  size_t lenbuf = size;
Packit 549fdc
Packit 549fdc
  output = vasnprintf (str, &lenbuf, format, args);
Packit 549fdc
  len = lenbuf;
Packit 549fdc
Packit 549fdc
  if (!output)
Packit 549fdc
    return -1;
Packit 549fdc
Packit 549fdc
  if (output != str)
Packit 549fdc
    {
Packit 549fdc
      if (size)
Packit 549fdc
        {
Packit 549fdc
          size_t pruned_len = (len < size ? len : size - 1);
Packit 549fdc
          memcpy (str, output, pruned_len);
Packit 549fdc
          str[pruned_len] = '\0';
Packit 549fdc
        }
Packit 549fdc
Packit 549fdc
      free (output);
Packit 549fdc
    }
Packit 549fdc
Packit 549fdc
  if (len > INT_MAX)
Packit 549fdc
    {
Packit 549fdc
      errno = EOVERFLOW;
Packit 549fdc
      return -1;
Packit 549fdc
    }
Packit 549fdc
Packit 549fdc
  return len;
Packit 549fdc
}