Skip to content

Commit

Permalink
[ADT] Add more ArrayRef <-> StringRef conversion functions
Browse files Browse the repository at this point in the history
Add new functions in StringExtras to convert byte size type array to
StringRef and vice versa.

Reviewed By: benlangmuir, dexonsmith

Differential Revision: https://reviews.llvm.org/D139035
  • Loading branch information
cachemeifyoucan committed Oct 6, 2023
1 parent ce8ed00 commit 4c94aff
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
13 changes: 11 additions & 2 deletions llvm/include/llvm/ADT/StringExtras.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,19 @@ inline StringRef toStringRef(bool B) { return StringRef(B ? "true" : "false"); }
inline StringRef toStringRef(ArrayRef<uint8_t> Input) {
return StringRef(reinterpret_cast<const char *>(Input.begin()), Input.size());
}
inline StringRef toStringRef(ArrayRef<char> Input) {
return StringRef(Input.begin(), Input.size());
}

/// Construct a string ref from an array ref of unsigned chars.
inline ArrayRef<uint8_t> arrayRefFromStringRef(StringRef Input) {
return {Input.bytes_begin(), Input.bytes_end()};
template <class CharT = uint8_t>
inline ArrayRef<CharT> arrayRefFromStringRef(StringRef Input) {
static_assert(std::is_same<CharT, char>::value ||
std::is_same<CharT, unsigned char>::value ||
std::is_same<CharT, signed char>::value,
"Expected byte type");
return ArrayRef<CharT>(reinterpret_cast<const CharT *>(Input.data()),
Input.size());
}

/// Interpret the given character \p C as a hexadecimal digit and return its
Expand Down
11 changes: 11 additions & 0 deletions llvm/unittests/ADT/StringExtrasTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -362,3 +362,14 @@ TEST(StringExtrasTest, splitCharForLoop) {
Result.push_back(x);
EXPECT_THAT(Result, testing::ElementsAre("foo", "bar", "", "baz"));
}

TEST(StringExtrasTest, arrayToStringRef) {
auto roundTripTestString = [](llvm::StringRef Str) {
EXPECT_EQ(Str, toStringRef(arrayRefFromStringRef<uint8_t>(Str)));
EXPECT_EQ(Str, toStringRef(arrayRefFromStringRef<char>(Str)));
};
roundTripTestString("");
roundTripTestString("foo");
roundTripTestString("\0\n");
roundTripTestString("\xFF\xFE");
}

0 comments on commit 4c94aff

Please sign in to comment.