[llvm] a41c8b8 - [ADT] support fixed-width output with `utohexstr`

Yuanfang Chen via llvm-commits llvm-commits at lists.llvm.org
Fri Jan 28 10:08:08 PST 2022


Author: Yuanfang Chen
Date: 2022-01-28T10:07:54-08:00
New Revision: a41c8b8fd5ade12b8f055634ab9faf69c7ba6765

URL: https://github.com/llvm/llvm-project/commit/a41c8b8fd5ade12b8f055634ab9faf69c7ba6765
DIFF: https://github.com/llvm/llvm-project/commit/a41c8b8fd5ade12b8f055634ab9faf69c7ba6765.diff

LOG: [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

Added: 
    

Modified: 
    llvm/include/llvm/ADT/StringExtras.h
    llvm/unittests/ADT/StringExtrasTest.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/include/llvm/ADT/StringExtras.h b/llvm/include/llvm/ADT/StringExtras.h
index 81a0954226d6a..9383b647382ac 100644
--- a/llvm/include/llvm/ADT/StringExtras.h
+++ b/llvm/include/llvm/ADT/StringExtras.h
@@ -148,13 +148,14 @@ inline char toUpper(char x) {
   return x;
 }
 
-inline std::string utohexstr(uint64_t X, bool LowerCase = false) {
+inline std::string utohexstr(uint64_t X, bool LowerCase = false,
+                             unsigned Width = 0) {
   char Buffer[17];
   char *BufPtr = std::end(Buffer);
 
   if (X == 0) *--BufPtr = '0';
 
-  while (X) {
+  for (unsigned i = 0; Width ? (i < Width) : X; ++i) {
     unsigned char Mod = static_cast<unsigned char>(X) & 15;
     *--BufPtr = hexdigit(Mod, LowerCase);
     X >>= 4;

diff  --git a/llvm/unittests/ADT/StringExtrasTest.cpp b/llvm/unittests/ADT/StringExtrasTest.cpp
index 49a9bcd79db99..2557dcedbaf01 100644
--- a/llvm/unittests/ADT/StringExtrasTest.cpp
+++ b/llvm/unittests/ADT/StringExtrasTest.cpp
@@ -96,6 +96,12 @@ TEST(StringExtrasTest, ToAndFromHex) {
   EXPECT_FALSE(tryGetFromHex(InvalidStr, IgnoredOutput));
 }
 
+TEST(StringExtrasTest, UINT64ToHex) {
+  EXPECT_EQ(utohexstr(0xA0u), "A0");
+  EXPECT_EQ(utohexstr(0xA0u, false, 4), "00A0");
+  EXPECT_EQ(utohexstr(0xA0u, false, 8), "000000A0");
+}
+
 TEST(StringExtrasTest, to_float) {
   float F;
   EXPECT_TRUE(to_float("4.7", F));


        


More information about the llvm-commits mailing list