Formats a list of arguments to a String, using the same format spec string as for printf. We do not use the StringPrintf class as it is not universally available. The result is limited to 4096 characters (including the tailing 0). If 4096 characters are not enough to format the input, or if there's an error, " " is returned.
| 3001 | // there's an error, "<formatting error or buffer exceeded>" is |
| 3002 | // returned. |
| 3003 | String String::Format(const char * format, ...) { |
| 3004 | va_list args; |
| 3005 | va_start(args, format); |
| 3006 | |
| 3007 | char buffer[4096]; |
| 3008 | const int kBufferSize = sizeof(buffer)/sizeof(buffer[0]); |
| 3009 | |
| 3010 | // MSVC 8 deprecates vsnprintf(), so we want to suppress warning |
| 3011 | // 4996 (deprecated function) there. |
| 3012 | #ifdef _MSC_VER // We are using MSVC. |
| 3013 | # pragma warning(push) // Saves the current warning state. |
| 3014 | # pragma warning(disable:4996) // Temporarily disables warning 4996. |
| 3015 | |
| 3016 | const int size = vsnprintf(buffer, kBufferSize, format, args); |
| 3017 | |
| 3018 | # pragma warning(pop) // Restores the warning state. |
| 3019 | #else // We are not using MSVC. |
| 3020 | const int size = vsnprintf(buffer, kBufferSize, format, args); |
| 3021 | #endif // _MSC_VER |
| 3022 | va_end(args); |
| 3023 | |
| 3024 | // vsnprintf()'s behavior is not portable. When the buffer is not |
| 3025 | // big enough, it returns a negative value in MSVC, and returns the |
| 3026 | // needed buffer size on Linux. When there is an output error, it |
| 3027 | // always returns a negative value. For simplicity, we lump the two |
| 3028 | // error cases together. |
| 3029 | if (size < 0 || size >= kBufferSize) { |
| 3030 | return String("<formatting error or buffer exceeded>"); |
| 3031 | } else { |
| 3032 | return String(buffer, size); |
| 3033 | } |
| 3034 | } |
| 3035 | |
| 3036 | // Converts the buffer in a stringstream to a String, converting NUL |
| 3037 | // bytes to "\\0" along the way. |