[PATCH] D118427: [ADT] support fixed-width output with `utohexstr`

Yuanfang Chen via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Thu Jan 27 19:57:14 PST 2022


ychen created this revision.
ychen added reviewers: dblaikie, dexonsmith.
ychen requested review of this revision.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Will use it to output a hash value that needs fixed-width.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D118427

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


Index: llvm/unittests/ADT/StringExtrasTest.cpp
===================================================================
--- llvm/unittests/ADT/StringExtrasTest.cpp
+++ llvm/unittests/ADT/StringExtrasTest.cpp
@@ -96,6 +96,12 @@
   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));
Index: llvm/include/llvm/ADT/StringExtras.h
===================================================================
--- llvm/include/llvm/ADT/StringExtras.h
+++ llvm/include/llvm/ADT/StringExtras.h
@@ -148,13 +148,14 @@
   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;


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D118427.403864.patch
Type: text/x-patch
Size: 1257 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20220128/fb45edcd/attachment.bin>


More information about the llvm-commits mailing list