Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions ext/tm/include/tm/string.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1577,6 +1577,20 @@ class String final {
* auto str = String::format("{} {}orld {}", cstr, c, num);
* assert_str_eq("hello world 999", str);
* ```
*
* Using `{h}`, an integral value or a pointer can be displayed as hex
* ```
* void *ptr = nullptr;
* int i = 255;
* auto str = String::format("Pointer = {h}, Integer = {h}", ptr, i);
* assert_str_eq("Pointer = 0x0, Integer = 0xff", str);
* ```
*
* A floating point in hex mode is floored to the integer value.
* ```should_abort
* float f = 10.5;
* String::format("{h}", f);
* ```
*/
template <typename... Args>
static String format(const char *const fmt, Args... args) {
Expand All @@ -1595,7 +1609,7 @@ class String final {
static void format(String &out, const char *fmt, T first, Args... rest) {
for (const char *c = fmt; *c != 0; c++) {
if (*c == '{' && *(c + 1) == 'h' && *(c + 2) == '}') {
if constexpr (std::is_arithmetic<T>::value || std::is_pointer<T>::value) {
if constexpr (std::is_integral_v<T> || std::is_pointer_v<T>) {
out += hex(first, HexFormat::LowercaseAndPrefixed);
format(out, c + 3, rest...);
return;
Expand All @@ -1604,7 +1618,7 @@ class String final {
abort();
}
} else if (*c == '{' && *(c + 1) == '}') {
if constexpr (std::is_pointer<T>::value && !std::is_same<const char *, T>::value && !std::is_same<char *, T>::value) {
if constexpr (std::is_pointer_v<T> && !std::is_same_v<const char *, T> && !std::is_same_v<char *, T>) {
fprintf(stderr, "String::format: T is a general pointer type but you didn't specify {h}\n");
abort();
} else {
Expand Down