2 * @brief Convert types to std::string
4 /* Copyright (C) 2009,2012,2015,2017 Olly Betts
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
27 #include <cstdio> // For snprintf() or sprintf().
28 #include <cstdlib> // For abort().
30 #include <type_traits>
34 // Much faster than snprintf() - also less generated code!
37 tostring_unsigned(T value
)
39 static_assert(std::is_unsigned
<T
>::value
, "Unsigned type required");
40 // Special case single digit positive numbers.
41 // FIXME: is this actually worthwhile?
42 if (value
< 10) return string(1, '0' + char(value
));
43 char buf
[(sizeof(T
) * 5 + 1) / 2];
44 char * p
= buf
+ sizeof(buf
);
47 char ch
= static_cast<char>(value
% 10);
51 return string(p
, buf
+ sizeof(buf
) - p
);
58 // Special case single digit positive numbers.
59 // FIXME: is this actually worthwhile?
60 if (value
< 10 && value
>= 0) return string(1, '0' + char(value
));
62 bool negative
= (value
< 0);
63 if (negative
) value
= -value
;
65 char buf
[(sizeof(T
) * 5 + 1) / 2 + 1];
66 char * p
= buf
+ sizeof(buf
);
69 char ch
= static_cast<char>(value
% 10);
78 return string(p
, buf
+ sizeof(buf
) - p
);
87 return tostring(value
);
91 str(unsigned int value
)
93 return tostring_unsigned(value
);
99 return tostring(value
);
103 str(unsigned long value
)
105 return tostring_unsigned(value
);
111 return tostring(value
);
115 str(unsigned long long value
)
117 return tostring_unsigned(value
);
122 format(const char * fmt
, T value
)
126 // If -1 is returned (as pre-ISO snprintf does if the buffer is too small,
127 // it will be cast to > sizeof(buf) and handled appropriately.
128 size_t size
= SNPRINTF_ISO(buf
, sizeof(buf
), fmt
, value
);
129 AssertRel(size
,<=,sizeof(buf
));
130 if (size
> sizeof(buf
)) size
= sizeof(buf
);
132 size_t size
= sprintf(buf
, fmt
, value
);
134 if (size
>= sizeof(buf
)) abort();
136 return string(buf
, size
);
142 return format("%.20g", value
);
146 str(const void * value
)
148 return format("%p", value
);