-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[common] Add fmt_debug_string polyfill
- Loading branch information
1 parent
cd2ac72
commit f3b1043
Showing
4 changed files
with
82 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
#include "drake/common/fmt.h" | ||
|
||
namespace drake { | ||
|
||
// We can simplify this after we drop support for Ubuntu 22.04 Jammy. | ||
std::string fmt_debug_string(std::string_view x) { | ||
#if FMT_VERSION >= 90000 | ||
return fmt::format("{:?}", x); | ||
#else | ||
std::string result; | ||
result.reserve(x.size() + 2); | ||
result.push_back('"'); | ||
for (const char ch : x) { | ||
// Check for characters with a custom escape sequence. | ||
if (ch == '\n') { | ||
result.push_back('\\'); | ||
result.push_back('n'); | ||
continue; | ||
} | ||
if (ch == '\r') { | ||
result.push_back('\\'); | ||
result.push_back('r'); | ||
continue; | ||
} | ||
if (ch == '\t') { | ||
result.push_back('\\'); | ||
result.push_back('t'); | ||
continue; | ||
} | ||
// Check for characters that require a leading backslash. | ||
if (ch == '"' || ch == '\\') { | ||
result.push_back('\\'); | ||
result.push_back(ch); | ||
continue; | ||
} | ||
// Check for any other non-printable characters. | ||
if (ch < 0x20 || ch >= 0x7F) { | ||
result.append(fmt::format("\\x{:02x}", static_cast<int>(ch))); | ||
continue; | ||
} | ||
// Normal character. | ||
result.push_back(ch); | ||
} | ||
result.push_back('"'); | ||
return result; | ||
#endif | ||
} | ||
|
||
} // namespace drake |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters