Blame lib/snprintf.c

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