MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
basestring_vsnprintf.c
1 /*
2  Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
3 
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; version 2 of the License.
7 
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  GNU General Public License for more details.
12 
13  You should have received a copy of the GNU General Public License
14  along with this program; if not, write to the Free Software
15  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
16 */
17 
18 #ifdef __sgi
19 /* define on IRIX to get posix compliant vsnprintf */
20 #define _XOPEN_SOURCE 500
21 #endif
22 #include <stdio.h>
23 #include <basestring_vsnprintf.h>
24 
25 int
26 basestring_snprintf(char *str, size_t size, const char *format, ...)
27 {
28  int ret;
29  va_list ap;
30  va_start(ap, format);
31  ret= basestring_vsnprintf(str, size, format, ap);
32  va_end(ap);
33  return(ret);
34 }
35 
36 #ifdef SNPRINTF_RETURN_TRUNC
37 static int
38 vsnprintf_doubling(size_t size, const char *format, va_list ap)
39 {
40  char *buf = 0;
41  int ret = -1;
42 
43  while (ret < 0 || ret >= (int)size)
44  {
45  buf = realloc(buf, size*=2);
46  ret = vsnprintf(buf, size, format, ap);
47  }
48  free(buf);
49  return ret;
50 }
51 #endif
52 
53 int
54 basestring_vsnprintf(char *str, size_t size, const char *format, va_list ap)
55 {
56  int ret;
57 
58  if (size == 0)
59  {
60  char buf[1];
61  return basestring_vsnprintf(buf, 1, format, ap);
62  }
63  ret = IF_WIN(_vsnprintf,vsnprintf)(str, size, format, ap);
64  if (ret >= 0 && ret < (int)size)
65  return ret;
66 #ifdef _WIN32
67  if (ret < 0 && errno == EINVAL)
68  return ret;
69  // otherwise, more than size chars are needed
70  return _vscprintf(format, ap);
71 #endif
72 #ifdef SNPRINTF_RETURN_TRUNC
73  {
74  char buf[512];
75  ret = vsnprintf(buf, sizeof(buf), format, ap);
76  if (ret >= 0 && ret < sizeof(buf))
77  return ret;
78  ret = vsnprintf_doubling(sizeof(buf), format, ap);
79  }
80 #endif
81  return ret;
82 }