/src/cpython/Python/mysnprintf.c
Line | Count | Source |
1 | | #include "Python.h" |
2 | | |
3 | | /* snprintf() and vsnprintf() wrappers. |
4 | | |
5 | | We wrap vsnprintf() to guarantee consistent behavior in corner cases: |
6 | | C99 behavior is to return the number of characters that would have been |
7 | | written had the buffer not been too small, and to set the last byte of the |
8 | | buffer to \0. |
9 | | Unlike C99, our wrappers do not support passing a null buffer. |
10 | | |
11 | | The wrappers ensure that str[size-1] is always \0 upon return. |
12 | | |
13 | | PyOS_snprintf and PyOS_vsnprintf never write more than size bytes |
14 | | (including the trailing '\0') into str. |
15 | | |
16 | | Return value (rv): |
17 | | |
18 | | When 0 <= rv < size, the output conversion was unexceptional, and |
19 | | rv characters were written to str (excluding a trailing \0 byte at |
20 | | str[rv]). |
21 | | |
22 | | When rv >= size, output conversion was truncated, and a buffer of |
23 | | size rv+1 would have been needed to avoid truncation. str[size-1] |
24 | | is \0 in this case. |
25 | | |
26 | | When rv < 0, "something bad happened". str[size-1] is \0 in this |
27 | | case too, but the rest of str is unreliable. It could be that |
28 | | an error in format codes was detected by libc. |
29 | | |
30 | | CAUTION: Unlike C99, str != NULL and size > 0 are required. |
31 | | Also, size must be smaller than INT_MAX. |
32 | | */ |
33 | | |
34 | | int |
35 | | PyOS_snprintf(char *str, size_t size, const char *format, ...) |
36 | 508 | { |
37 | 508 | int rc; |
38 | 508 | va_list va; |
39 | | |
40 | 508 | va_start(va, format); |
41 | 508 | rc = PyOS_vsnprintf(str, size, format, va); |
42 | 508 | va_end(va); |
43 | 508 | return rc; |
44 | 508 | } |
45 | | |
46 | | int |
47 | | PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) |
48 | 508 | { |
49 | 508 | assert(str != NULL); |
50 | 508 | assert(size > 0); |
51 | 508 | assert(size <= (INT_MAX - 1)); |
52 | 508 | assert(format != NULL); |
53 | | |
54 | 508 | int len; /* # bytes written, excluding \0 */ |
55 | | /* We take a size_t as input but return an int. Sanity check |
56 | | * our input so that it won't cause an overflow in the |
57 | | * vsnprintf return value. */ |
58 | 508 | if (size > INT_MAX - 1) { |
59 | 0 | len = -666; |
60 | 0 | goto Done; |
61 | 0 | } |
62 | | |
63 | 508 | len = vsnprintf(str, size, format, va); |
64 | | |
65 | 508 | Done: |
66 | 508 | if (size > 0) { |
67 | 508 | str[size-1] = '\0'; |
68 | 508 | } |
69 | 508 | return len; |
70 | 508 | } |