| 93 | } |
| 94 | |
| 95 | static void StringAppendV(std::string* dst, const char* format, va_list ap) { |
| 96 | // First try with a small fixed size buffer |
| 97 | char space[1024]; |
| 98 | |
| 99 | // It's possible for methods that use a va_list to invalidate |
| 100 | // the data in it upon use. The fix is to make a copy |
| 101 | // of the structure before using it and use that copy instead. |
| 102 | va_list backup_ap; |
| 103 | va_copy(backup_ap, ap); |
| 104 | int result = vsnprintf(space, sizeof(space), format, backup_ap); |
| 105 | va_end(backup_ap); |
| 106 | |
| 107 | if ((result >= 0) && (static_cast<size_t>(result) < sizeof(space))) { |
| 108 | // It fit |
| 109 | dst->append(space, result); |
| 110 | return; |
| 111 | } |
| 112 | |
| 113 | // Repeatedly increase buffer size until it fits |
| 114 | int length = sizeof(space); |
| 115 | while (true) { |
| 116 | if (result < 0) { |
| 117 | // Older behavior: just try doubling the buffer size |
| 118 | length *= 2; |
| 119 | } else { |
| 120 | // We need exactly "result+1" characters |
| 121 | length = result+1; |
| 122 | } |
| 123 | char* buf = new char[length]; |
| 124 | |
| 125 | // Restore the va_list before we use it again |
| 126 | va_copy(backup_ap, ap); |
| 127 | result = vsnprintf(buf, length, format, backup_ap); |
| 128 | va_end(backup_ap); |
| 129 | |
| 130 | if ((result >= 0) && (result < length)) { |
| 131 | // It fit |
| 132 | dst->append(buf, result); |
| 133 | delete[] buf; |
| 134 | return; |
| 135 | } |
| 136 | delete[] buf; |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | std::string StringPrintf(const char* format, ...) { |
| 141 | va_list ap; |