00001
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #include <config.h>
00022
00023 #include "str.h"
00024
00025 #include "omassert.h"
00026
00027 #include <cstdio>
00028 #include <cstdlib>
00029 #include <string>
00030
00031 using namespace std;
00032
00033
00034 template<class T>
00035 inline string
00036 tostring_unsigned(T value)
00037 {
00038 STATIC_ASSERT_UNSIGNED_TYPE(T);
00039
00040
00041 if (value < 10) return string(1, '0' + char(value));
00042 char buf[(sizeof(T) * 5 + 1) / 2];
00043 char * p = buf + sizeof(buf);
00044 do {
00045 AssertRel(p,>,buf);
00046 char ch(value % 10);
00047 value /= 10;
00048 *(--p) = ch + '0';
00049 } while (value);
00050 return string(p, buf + sizeof(buf) - p);
00051 }
00052
00053 template<class T>
00054 inline string
00055 tostring(T value)
00056 {
00057
00058
00059 if (value < 10 && value >= 0) return string(1, '0' + char(value));
00060
00061 bool negative = (value < 0);
00062 if (negative) value = -value;
00063
00064 char buf[(sizeof(T) * 5 + 1) / 2 + 1];
00065 char * p = buf + sizeof(buf);
00066 do {
00067 AssertRel(p,>,buf);
00068 char ch(value % 10);
00069 value /= 10;
00070 *(--p) = ch + '0';
00071 } while (value);
00072
00073 if (negative) {
00074 AssertRel(p,>,buf);
00075 *--p = '-';
00076 }
00077 return string(p, buf + sizeof(buf) - p);
00078 }
00079
00080 namespace Xapian {
00081 namespace Internal {
00082
00083 string
00084 str(int value)
00085 {
00086 return tostring(value);
00087 }
00088
00089 string
00090 str(unsigned int value)
00091 {
00092 return tostring_unsigned(value);
00093 }
00094
00095 string
00096 str(long value)
00097 {
00098 return tostring(value);
00099 }
00100
00101 string
00102 str(unsigned long value)
00103 {
00104 return tostring_unsigned(value);
00105 }
00106
00107 string
00108 str(long long value)
00109 {
00110 return tostring(value);
00111 }
00112
00113 string
00114 str(unsigned long long value)
00115 {
00116 return tostring_unsigned(value);
00117 }
00118
00119 template<class T>
00120 inline string
00121 format(const char * fmt, T value)
00122 {
00123 char buf[128];
00124 #ifdef SNPRINTF
00125
00126
00127 size_t size = SNPRINTF_ISO(buf, sizeof(buf), fmt, value);
00128 AssertRel(size,<=,sizeof(buf));
00129 if (size > sizeof(buf)) size = sizeof(buf);
00130 #else
00131 size_t size = sprintf(buf, fmt, value);
00132
00133 if (size >= sizeof(buf)) abort();
00134 #endif
00135 return string(buf, size);
00136 }
00137
00138 string
00139 str(double value)
00140 {
00141 return format("%.20g", value);
00142 }
00143
00144 string
00145 str(const void * value)
00146 {
00147 return format("%p", value);
00148 }
00149
00150 }
00151 }