Fix bug with -0.0L in previous patch.
[gnulib.git] / lib / unistdio / u-vsnprintf.h
1 /* Formatted output to strings.
2    Copyright (C) 1999, 2002, 2006-2007 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify it
5    under the terms of the GNU Lesser General Public License as published
6    by the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    Lesser General Public License for more details.
13
14    You should have received a copy of the GNU Lesser General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 /* Some systems, like OSF/1 4.0 and Woe32, don't have EOVERFLOW.  */
18 #ifndef EOVERFLOW
19 # define EOVERFLOW E2BIG
20 #endif
21
22 int
23 VSNPRINTF (DCHAR_T *buf, size_t size, const FCHAR_T *format, va_list args)
24 {
25   size_t length;
26   DCHAR_T *result;
27
28   if (size == 0)
29     buf = NULL;
30   else
31     length = size;
32   result = VASNPRINTF (buf, &length, format, args);
33   if (result == NULL)
34     return -1;
35
36   if (result != buf)
37     {
38       if (size != 0)
39         {
40           /* The result did not fit into the buffer.  Copy the initial segment
41              into the buffer, truncating it if necessary.  */
42           size_t n = (length < size ? length : size - 1);
43           DCHAR_CPY (buf, result, n);
44           buf[n] = '\0';
45         }
46       free (result);
47     }
48
49   if (length > INT_MAX)
50     {
51       errno = EOVERFLOW;
52       return -1;
53     }
54
55   /* Return the number of resulting units, excluding the trailing NUL.  */
56   return length;
57 }