blob: e6c3fcedc667844cdc2436b93a292f6f3f70166f [file] [log] [blame]
Marc-André Lemburge5006eb2001-07-31 13:24:44 +00001
2#include "Python.h"
3
4/* snprintf() emulation for platforms which don't have it (yet).
5
6 Return value
7
8 The number of characters printed (not including the trailing
9 `\0' used to end output to strings) or a negative number in
10 case of an error.
11
12 PyOS_snprintf and PyOS_vsnprintf do not write more than size
13 bytes (including the trailing '\0').
14
15 If the output would have been truncated, they return the number
16 of characters (excluding the trailing '\0') which would have
17 been written to the final string if enough space had been
18 available. This is inline with the C99 standard.
19
20*/
21
22#include <ctype.h>
23
24#ifndef HAVE_SNPRINTF
25
26static
27int myvsnprintf(char *str, size_t size, const char *format, va_list va)
28{
29 char *buffer = PyMem_Malloc(size + 512);
30 int len;
31
32 if (buffer == NULL)
33 return -1;
34 len = vsprintf(buffer, format, va);
35 if (len < 0) {
36 PyMem_Free(buffer);
37 return len;
38 }
39 len++;
40 if (len > size + 512)
41 Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf");
42 if (len > size) {
43 PyMem_Free(buffer);
44 return len - 1;
45 }
46 memcpy(str, buffer, len);
47 PyMem_Free(buffer);
48 return len - 1;
49}
50
51int PyOS_snprintf(char *str, size_t size, const char *format, ...)
52{
53 int rc;
54 va_list va;
55
56 va_start(va, format);
57 rc = myvsnprintf(str, size, format, va);
58 va_end(va);
59 return rc;
60}
61
62int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
63{
64 return myvsnprintf(str, size, format, va);
65}
66
67#else
68
69/* Make sure that a C API is included in the lib */
70
71#ifdef PyOS_snprintf
72# undef PyOS_snprintf
73#endif
74
75int PyOS_snprintf(char *str, size_t size, const char *format, ...)
76{
77 int rc;
78 va_list va;
79
80 va_start(va, format);
81 rc = vsnprintf(str, size, format, va);
82 va_end(va);
83 return rc;
84}
85
86#ifdef PyOS_vsnprintf
87# undef PyOS_vsnprintf
88#endif
89
90int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
91{
92 return vsnprintf(str, size, format, va);
93}
94
95#endif
96