| 20 | #endif |
| 21 | |
| 22 | void StringAppendV(string* dst, const char* format, va_list ap) { |
| 23 | // First try with a small fixed size buffer |
| 24 | static const int kSpaceLength = 1024; |
| 25 | char space[kSpaceLength]; |
| 26 | |
| 27 | // It's possible for methods that use a va_list to invalidate |
| 28 | // the data in it upon use. The fix is to make a copy |
| 29 | // of the structure before using it and use that copy instead. |
| 30 | va_list backup_ap; |
| 31 | va_copy(backup_ap, ap); |
| 32 | int result = vsnprintf(space, kSpaceLength, format, backup_ap); |
| 33 | va_end(backup_ap); |
| 34 | |
| 35 | if (result < kSpaceLength) { |
| 36 | if (result >= 0) { |
| 37 | // Normal case -- everything fit. |
| 38 | dst->append(space, result); |
| 39 | return; |
| 40 | } |
| 41 | |
| 42 | if (IS__MSC_VER) { |
| 43 | // Error or MSVC running out of space. MSVC 8.0 and higher |
| 44 | // can be asked about space needed with the special idiom below: |
| 45 | va_copy(backup_ap, ap); |
| 46 | result = vsnprintf(nullptr, 0, format, backup_ap); |
| 47 | va_end(backup_ap); |
| 48 | } |
| 49 | |
| 50 | if (result < 0) { |
| 51 | // Just an error. |
| 52 | return; |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // Increase the buffer size to the size requested by vsnprintf, |
| 57 | // plus one for the closing \0. |
| 58 | int length = result+1; |
| 59 | auto buf = new char[length]; |
| 60 | |
| 61 | // Restore the va_list before we use it again |
| 62 | va_copy(backup_ap, ap); |
| 63 | result = vsnprintf(buf, length, format, backup_ap); |
| 64 | va_end(backup_ap); |
| 65 | |
| 66 | if (result >= 0 && result < length) { |
| 67 | // It fit |
| 68 | dst->append(buf, result); |
| 69 | } |
| 70 | delete[] buf; |
| 71 | } |
| 72 | |
| 73 | |
| 74 | string StringPrintf(const char* format, ...) { |
no test coverage detected