[llvm] 83797c0 - [ADT] Use a lookup table in hexdigit() and call that from toHex()

Hans Wennborg via llvm-commits llvm-commits at lists.llvm.org
Tue Jan 11 02:32:40 PST 2022


Author: Hans Wennborg
Date: 2022-01-11T11:32:22+01:00
New Revision: 83797c03d2ee0786259d261e6716836e60520a05

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

LOG: [ADT] Use a lookup table in hexdigit() and call that from toHex()

A lookup table, which toHex() was using, seems like the better approach.
Having two implementations is redundant, so put the lookup table in
hexdigit() and make toHex() call that.

Differential revision: https://reviews.llvm.org/D116960

Added: 
    

Modified: 
    llvm/include/llvm/ADT/StringExtras.h

Removed: 
    


################################################################################
diff  --git a/llvm/include/llvm/ADT/StringExtras.h b/llvm/include/llvm/ADT/StringExtras.h
index 2ca672e7855b0..912b9bb53c83e 100644
--- a/llvm/include/llvm/ADT/StringExtras.h
+++ b/llvm/include/llvm/ADT/StringExtras.h
@@ -35,8 +35,10 @@ class raw_ostream;
 /// hexdigit - Return the hexadecimal character for the
 /// given number \p X (which should be less than 16).
 inline char hexdigit(unsigned X, bool LowerCase = false) {
-  const char HexChar = LowerCase ? 'a' : 'A';
-  return X < 10 ? '0' + X : HexChar + X - 10;
+  assert(X < 16);
+  static const char LUT[] = "0123456789ABCDEF";
+  const uint8_t Offset = LowerCase ? 32 : 0;
+  return LUT[X] | Offset;
 }
 
 /// Given an array of c-style strings terminated by a null pointer, construct
@@ -165,16 +167,14 @@ inline std::string utohexstr(uint64_t X, bool LowerCase = false) {
 /// Convert buffer \p Input to its hexadecimal representation.
 /// The returned string is double the size of \p Input.
 inline std::string toHex(StringRef Input, bool LowerCase = false) {
-  static const char *const LUT = "0123456789ABCDEF";
-  const uint8_t Offset = LowerCase ? 32 : 0;
   size_t Length = Input.size();
 
   std::string Output;
   Output.reserve(2 * Length);
   for (size_t i = 0; i < Length; ++i) {
     const unsigned char c = Input[i];
-    Output.push_back(LUT[c >> 4] | Offset);
-    Output.push_back(LUT[c & 15] | Offset);
+    Output.push_back(hexdigit(c >> 4, LowerCase));
+    Output.push_back(hexdigit(c & 15, LowerCase));
   }
   return Output;
 }


        


More information about the llvm-commits mailing list