Import upstream version 1.28
[debian/tar] / gnu / vsnprintf.c
1 /* -*- buffer-read-only: t -*- vi: set ro: */
2 /* DO NOT EDIT! GENERATED AUTOMATICALLY! */
3 /* Formatted output to strings.
4    Copyright (C) 2004, 2006-2014 Free Software Foundation, Inc.
5    Written by Simon Josefsson and Yoann Vandoorselaere <yoann@prelude-ids.org>.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3, or (at your option)
10    any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License along
18    with this program; if not, see <http://www.gnu.org/licenses/>.  */
19
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 /* Specification.  */
25 #include <stdio.h>
26
27 #include <errno.h>
28 #include <limits.h>
29 #include <stdarg.h>
30 #include <stdlib.h>
31 #include <string.h>
32
33 #include "vasnprintf.h"
34
35 /* Print formatted output to string STR.  Similar to vsprintf, but
36    additional length SIZE limit how much is written into STR.  Returns
37    string length of formatted string (which may be larger than SIZE).
38    STR may be NULL, in which case nothing will be written.  On error,
39    return a negative value.  */
40 int
41 vsnprintf (char *str, size_t size, const char *format, va_list args)
42 {
43   char *output;
44   size_t len;
45   size_t lenbuf = size;
46
47   output = vasnprintf (str, &lenbuf, format, args);
48   len = lenbuf;
49
50   if (!output)
51     return -1;
52
53   if (output != str)
54     {
55       if (size)
56         {
57           size_t pruned_len = (len < size ? len : size - 1);
58           memcpy (str, output, pruned_len);
59           str[pruned_len] = '\0';
60         }
61
62       free (output);
63     }
64
65   if (len > INT_MAX)
66     {
67       errno = EOVERFLOW;
68       return -1;
69     }
70
71   return len;
72 }