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