00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014 #include "base/stringprintf.h"
00015
00016 #include <cstdarg>
00017 #include <cstdio>
00018
00019 #include <string>
00020
00021 namespace operations_research {
00022
00023 void StringAppendV(std::string* const dst,
00024 const char* const format,
00025 va_list ap) {
00026
00027 char space[1024];
00028
00029
00030
00031
00032 va_list backup_ap;
00033 #if defined(_MSC_VER)
00034 backup_ap = ap;
00035 #else
00036 va_copy(backup_ap, ap);
00037 #endif
00038 int result = vsnprintf(space, sizeof(space), format, backup_ap);
00039 va_end(backup_ap);
00040
00041 if ((result >= 0) && (result < sizeof(space))) {
00042
00043 dst->append(space, result);
00044 return;
00045 }
00046
00047
00048 int length = sizeof(space);
00049 while (true) {
00050 if (result < 0) {
00051
00052 length *= 2;
00053 } else {
00054
00055 length = result+1;
00056 }
00057 char* const buf = new char[length];
00058
00059
00060 #if defined(_MSC_VER)
00061 backup_ap = ap;
00062 #else
00063 va_copy(backup_ap, ap);
00064 #endif
00065 result = vsnprintf(buf, length, format, backup_ap);
00066 va_end(backup_ap);
00067
00068 if ((result >= 0) && (result < length)) {
00069
00070 dst->append(buf, result);
00071 delete[] buf;
00072 return;
00073 }
00074 delete[] buf;
00075 }
00076 }
00077
00078 std::string StringPrintf(const char* const format, ...) {
00079 va_list ap;
00080 va_start(ap, format);
00081 std::string result;
00082 StringAppendV(&result, format, ap);
00083 va_end(ap);
00084 return result;
00085 }
00086
00087 void SStringPrintf(std::string* const dst, const char* const format, ...) {
00088 va_list ap;
00089 va_start(ap, format);
00090 dst->clear();
00091 StringAppendV(dst, format, ap);
00092 va_end(ap);
00093 }
00094
00095 void StringAppendF(std::string* const dst, const char* const format, ...) {
00096 va_list ap;
00097 va_start(ap, format);
00098 StringAppendV(dst, format, ap);
00099 va_end(ap);
00100 }
00101 }