[PATCH] D27686: Add llvm::StringLiteral
Zachary Turner via Phabricator via llvm-commits
llvm-commits at lists.llvm.org
Mon Dec 12 14:16:01 PST 2016
zturner created this revision.
zturner added reviewers: malcolm.parsons, mehdi_amini.
zturner added a subscriber: llvm-commits.
As discussed on the mailing list, this allows us to create global tables of StringRefs that don't incur a global constructor.
https://reviews.llvm.org/D27686
Files:
include/llvm/ADT/StringRef.h
unittests/ADT/StringRefTest.cpp
Index: unittests/ADT/StringRefTest.cpp
===================================================================
--- unittests/ADT/StringRefTest.cpp
+++ unittests/ADT/StringRefTest.cpp
@@ -1002,4 +1002,10 @@
EXPECT_EQ("", Taken);
}
+TEST(StringRefTest, StringLiteral) {
+ constexpr StringLiteral Strings[] = {"Foo", "Bar"};
+ EXPECT_STREQ("Foo", Strings[0].data());
+ EXPECT_STREQ("Bar", Strings[1].data());
+}
+
} // end anonymous namespace
Index: include/llvm/ADT/StringRef.h
===================================================================
--- include/llvm/ADT/StringRef.h
+++ include/llvm/ADT/StringRef.h
@@ -84,11 +84,8 @@
/// Construct a string ref from a pointer and length.
LLVM_ATTRIBUTE_ALWAYS_INLINE
- /*implicit*/ StringRef(const char *data, size_t length)
- : Data(data), Length(length) {
- assert((data || length == 0) &&
- "StringRef cannot be built from a NULL argument with non-null length");
- }
+ /*implicit*/ constexpr StringRef(const char *data, size_t length)
+ : Data(data), Length(length) {}
/// Construct a string ref from an std::string.
LLVM_ATTRIBUTE_ALWAYS_INLINE
@@ -839,6 +836,20 @@
/// @}
};
+ /// StringLiteral - A wrapper around a StringLiteral that serves as a proxy
+ /// for constructing global tables of StringRefs with the length computed
+ /// at compile time. Using this class with a non-literal char array is
+ /// considered undefined behavior. To prevent this, it is recommended
+ /// that StringLiteral *only* be used in a constexpr context, as such:
+ ///
+ /// constexpr StringLiteral S("test");
+ ///
+ class StringLiteral : public StringRef {
+ public:
+ template <size_t N>
+ constexpr StringLiteral(const char (&Str)[N]) : StringRef(Str, N) {}
+ };
+
/// @name StringRef Comparison Operators
/// @{
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D27686.81138.patch
Type: text/x-patch
Size: 1855 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20161212/747a9624/attachment.bin>
More information about the llvm-commits
mailing list