[PATCH] D139035: [ADT] Add more ArrayRef <-> StringRef conversion functions
Steven Wu via Phabricator via llvm-commits
llvm-commits at lists.llvm.org
Wed Nov 30 10:56:41 PST 2022
steven_wu created this revision.
steven_wu added reviewers: rnk, dblaikie, benlangmuir, akyrtzi.
Herald added a subscriber: ributzka.
Herald added a project: All.
steven_wu requested review of this revision.
Herald added a project: LLVM.
Add new functions in StringExtras to convert byte size type array to
StringRef and vice versa.
Repository:
rG LLVM Github Monorepo
https://reviews.llvm.org/D139035
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
@@ -327,3 +327,14 @@
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");
+}
Index: llvm/include/llvm/ADT/StringExtras.h
===================================================================
--- llvm/include/llvm/ADT/StringExtras.h
+++ llvm/include/llvm/ADT/StringExtras.h
@@ -58,10 +58,19 @@
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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D139035.479021.patch
Type: text/x-patch
Size: 1867 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20221130/a2c0d73c/attachment.bin>
More information about the llvm-commits
mailing list