A safe version of vprintf.
| 43 | |
| 44 | /// A safe version of vprintf. |
| 45 | string |
| 46 | vformat(const char* format, va_list ap) |
| 47 | { |
| 48 | string s; |
| 49 | |
| 50 | // We're not really sure how big of a buffer will be necessary. |
| 51 | // Try 1K, if not the return value will tell us how much is necessary. |
| 52 | int bufSize = 1024; |
| 53 | while (true) { |
| 54 | char buf[bufSize]; |
| 55 | // vsnprintf trashes the va_list, so copy it first |
| 56 | va_list aq; |
| 57 | __va_copy(aq, ap); |
| 58 | int r = vsnprintf(buf, bufSize, format, aq); |
| 59 | assert(r >= 0); // old glibc versions returned -1 |
| 60 | if (r < bufSize) { |
| 61 | s = buf; |
| 62 | break; |
| 63 | } |
| 64 | bufSize = r + 1; |
| 65 | } |
| 66 | |
| 67 | return s; |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * Return (potentially multi-line) string hex dump of a binary buffer in |