Skip to content

Commit 83797c0

Browse files
committed
[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
1 parent 2e52f76 commit 83797c0

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

llvm/include/llvm/ADT/StringExtras.h

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,10 @@ class raw_ostream;
3535
/// hexdigit - Return the hexadecimal character for the
3636
/// given number \p X (which should be less than 16).
3737
inline char hexdigit(unsigned X, bool LowerCase = false) {
38-
const char HexChar = LowerCase ? 'a' : 'A';
39-
return X < 10 ? '0' + X : HexChar + X - 10;
38+
assert(X < 16);
39+
static const char LUT[] = "0123456789ABCDEF";
40+
const uint8_t Offset = LowerCase ? 32 : 0;
41+
return LUT[X] | Offset;
4042
}
4143

4244
/// 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) {
165167
/// Convert buffer \p Input to its hexadecimal representation.
166168
/// The returned string is double the size of \p Input.
167169
inline std::string toHex(StringRef Input, bool LowerCase = false) {
168-
static const char *const LUT = "0123456789ABCDEF";
169-
const uint8_t Offset = LowerCase ? 32 : 0;
170170
size_t Length = Input.size();
171171

172172
std::string Output;
173173
Output.reserve(2 * Length);
174174
for (size_t i = 0; i < Length; ++i) {
175175
const unsigned char c = Input[i];
176-
Output.push_back(LUT[c >> 4] | Offset);
177-
Output.push_back(LUT[c & 15] | Offset);
176+
Output.push_back(hexdigit(c >> 4, LowerCase));
177+
Output.push_back(hexdigit(c & 15, LowerCase));
178178
}
179179
return Output;
180180
}

0 commit comments

Comments
 (0)