Skip to content

Commit a41c8b8

Browse files
author
Yuanfang Chen
committed
[ADT] support fixed-width output with utohexstr
Will use it to output a hash value that needs fixed-width. Reviewed By: dblaikie Differential Revision: https://reviews.llvm.org/D118427
1 parent 68e3946 commit a41c8b8

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

llvm/include/llvm/ADT/StringExtras.h

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,13 +148,14 @@ inline char toUpper(char x) {
148148
return x;
149149
}
150150

151-
inline std::string utohexstr(uint64_t X, bool LowerCase = false) {
151+
inline std::string utohexstr(uint64_t X, bool LowerCase = false,
152+
unsigned Width = 0) {
152153
char Buffer[17];
153154
char *BufPtr = std::end(Buffer);
154155

155156
if (X == 0) *--BufPtr = '0';
156157

157-
while (X) {
158+
for (unsigned i = 0; Width ? (i < Width) : X; ++i) {
158159
unsigned char Mod = static_cast<unsigned char>(X) & 15;
159160
*--BufPtr = hexdigit(Mod, LowerCase);
160161
X >>= 4;

llvm/unittests/ADT/StringExtrasTest.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,12 @@ TEST(StringExtrasTest, ToAndFromHex) {
9696
EXPECT_FALSE(tryGetFromHex(InvalidStr, IgnoredOutput));
9797
}
9898

99+
TEST(StringExtrasTest, UINT64ToHex) {
100+
EXPECT_EQ(utohexstr(0xA0u), "A0");
101+
EXPECT_EQ(utohexstr(0xA0u, false, 4), "00A0");
102+
EXPECT_EQ(utohexstr(0xA0u, false, 8), "000000A0");
103+
}
104+
99105
TEST(StringExtrasTest, to_float) {
100106
float F;
101107
EXPECT_TRUE(to_float("4.7", F));

0 commit comments

Comments
 (0)