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
25 #include "negate_unsigned.h"
28 #include <cstdio> // For snprintf().
29 #include <cstdlib> // For abort().
31 #include <type_traits>
35 // Much faster than snprintf() - also less generated code!
38 tostring_unsigned(T value
)
40 static_assert(std::is_unsigned_v
<T
>, "Unsigned type required");
41 // Special case single digit positive numbers.
42 // FIXME: is this actually worthwhile?
43 if (value
< 10) return string(1, '0' + char(value
));
44 char buf
[(sizeof(T
) * 5 + 1) / 2];
45 char * p
= buf
+ sizeof(buf
);
48 char ch
= static_cast<char>(value
% 10);
52 return string(p
, buf
+ sizeof(buf
) - p
);
59 // Special case single digit positive numbers.
60 // FIXME: is this actually worthwhile?
61 if (value
< 10 && value
>= 0) return string(1, '0' + char(value
));
63 bool negative
= (value
< 0);
65 typedef typename
std::make_unsigned_t
<T
> unsigned_type
;
66 unsigned_type
val(value
);
68 val
= negate_unsigned(val
);
71 char buf
[(sizeof(unsigned_type
) * 5 + 1) / 2 + 1];
72 char * p
= buf
+ sizeof(buf
);
75 char ch
= static_cast<char>(val
% 10);
84 return string(p
, buf
+ sizeof(buf
) - p
);
93 return tostring(value
);
97 str(unsigned int value
)
99 return tostring_unsigned(value
);
105 return tostring(value
);
109 str(unsigned long value
)
111 return tostring_unsigned(value
);
117 return tostring(value
);
121 str(unsigned long long value
)
123 return tostring_unsigned(value
);
128 format(const char * fmt
, T value
)
131 // If -1 is returned (as pre-ISO snprintf does if the buffer is too small,
132 // it will be cast to > sizeof(buf) and handled appropriately.
133 size_t size
= snprintf(buf
, sizeof(buf
), fmt
, value
);
134 AssertRel(size
,<=,sizeof(buf
));
135 if (size
> sizeof(buf
)) size
= sizeof(buf
);
136 return string(buf
, size
);
142 return format("%.20g", value
);
146 str(const void * value
)
148 return format("%p", value
);