New \grammartoken markup, similar to \token but allowed everywhere.
[python/dscho.git] / Python / mysnprintf.c
bloba373f4efe6d7516d38e1b7ad4f3713ccac3b5698
2 #include "Python.h"
4 /* snprintf() emulation for platforms which don't have it (yet).
6 Return value
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.
12 PyOS_snprintf and PyOS_vsnprintf do not write more than size
13 bytes (including the trailing '\0').
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.
22 #include <ctype.h>
24 #ifndef HAVE_SNPRINTF
26 static
27 int myvsnprintf(char *str, size_t size, const char *format, va_list va)
29 char *buffer = PyMem_Malloc(size + 512);
30 int len;
32 if (buffer == NULL)
33 return -1;
34 len = vsprintf(buffer, format, va);
35 if (len < 0) {
36 PyMem_Free(buffer);
37 return len;
39 len++;
40 assert(len >= 0);
41 if ((size_t)len > size + 512)
42 Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf");
43 if ((size_t)len > size) {
44 PyMem_Free(buffer);
45 return len - 1;
47 memcpy(str, buffer, len);
48 PyMem_Free(buffer);
49 return len - 1;
52 int PyOS_snprintf(char *str, size_t size, const char *format, ...)
54 int rc;
55 va_list va;
57 va_start(va, format);
58 rc = myvsnprintf(str, size, format, va);
59 va_end(va);
60 return rc;
63 int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
65 return myvsnprintf(str, size, format, va);
68 #else
70 /* Make sure that a C API is included in the lib */
72 #ifdef PyOS_snprintf
73 # undef PyOS_snprintf
74 #endif
76 int PyOS_snprintf(char *str, size_t size, const char *format, ...)
78 int rc;
79 va_list va;
81 va_start(va, format);
82 rc = vsnprintf(str, size, format, va);
83 va_end(va);
84 return rc;
87 #ifdef PyOS_vsnprintf
88 # undef PyOS_vsnprintf
89 #endif
91 int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
93 return vsnprintf(str, size, format, va);
96 #endif