| 41 | |
| 42 | |
| 43 | std::string |
| 44 | Strutil::vformat (const char *fmt, va_list ap) |
| 45 | { |
| 46 | // Allocate a buffer on the stack that's big enough for us almost |
| 47 | // all the time. Be prepared to allocate dynamically if it doesn't fit. |
| 48 | size_t size = 1024; |
| 49 | char stackbuf[1024]; |
| 50 | std::vector<char> dynamicbuf; |
| 51 | char *buf = &stackbuf[0]; |
| 52 | |
| 53 | while (1) { |
| 54 | // Try to vsnprintf into our buffer. |
| 55 | va_list apsave; |
| 56 | #ifdef va_copy |
| 57 | va_copy (apsave, ap); |
| 58 | #else |
| 59 | apsave = ap; |
| 60 | #endif |
| 61 | int needed = vsnprintf (buf, size, fmt, ap); |
| 62 | va_end (ap); |
| 63 | |
| 64 | // NB. C99 (which modern Linux and OS X follow) says vsnprintf |
| 65 | // failure returns the length it would have needed. But older |
| 66 | // glibc and current Windows return -1 for failure, i.e., not |
| 67 | // telling us how much was needed. |
| 68 | |
| 69 | if (needed < (int)size && needed >= 0) { |
| 70 | // It fit fine so we're done. |
| 71 | return std::string (buf, (size_t) needed); |
| 72 | } |
| 73 | |
| 74 | // vsnprintf reported that it wanted to write more characters |
| 75 | // than we allotted. So try again using a dynamic buffer. This |
| 76 | // doesn't happen very often if we chose our initial size well. |
| 77 | size = (needed > 0) ? (needed+1) : (size*2); |
| 78 | dynamicbuf.resize (size); |
| 79 | buf = &dynamicbuf[0]; |
| 80 | #ifdef va_copy |
| 81 | va_copy (ap, apsave); |
| 82 | #else |
| 83 | ap = apsave; |
| 84 | #endif |
| 85 | } |
| 86 | } |