Support/ADT/Twine: Add toNullTerminatedStringRef.
authorMichael J. Spencer <bigcheesegs@gmail.com>
Wed, 1 Dec 2010 20:37:30 +0000 (20:37 +0000)
committerMichael J. Spencer <bigcheesegs@gmail.com>
Wed, 1 Dec 2010 20:37:30 +0000 (20:37 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@120600 91177308-0d34-0410-b5e6-96231b3b80d8

include/llvm/ADT/Twine.h
lib/Support/Twine.cpp
unittests/ADT/TwineTest.cpp

index 82f46c9379c083a98deb4e9a62c638fe2549bc68..ab8d3653e33f2043829f48f8b03b32452d10d0e2 100644 (file)
@@ -382,6 +382,14 @@ namespace llvm {
     /// SmallVector and a StringRef to the SmallVector's data is returned.
     StringRef toStringRef(SmallVectorImpl<char> &Out) const;
 
+    /// toNullTerminatedStringRef - This returns the twine as a single null
+    /// terminated StringRef if it can be represented as such. Otherwise the
+    /// twine is written into the given SmallVector and a StringRef to the
+    /// SmallVector's data is returned.
+    ///
+    /// The returned StringRef's size does not include the null terminator.
+    StringRef toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const;
+
     /// print - Write the concatenated string represented by this twine to the
     /// stream \arg OS.
     void print(raw_ostream &OS) const;
index 093e29de96a1d71f85e6b07bc727861774ff9daa..4f6f479a7eae910f13cdd12b80c622b0204b7221 100644 (file)
@@ -30,6 +30,18 @@ StringRef Twine::toStringRef(SmallVectorImpl<char> &Out) const {
   return StringRef(Out.data(), Out.size());
 }
 
+StringRef Twine::toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const {
+  if (isSingleStringRef()) {
+    StringRef sr = getSingleStringRef();
+    if (*(sr.begin() + sr.size()) == 0)
+      return sr;
+  }
+  toVector(Out);
+  Out.push_back(0);
+  Out.pop_back();
+  return StringRef(Out.data(), Out.size());
+}
+
 void Twine::printOneChild(raw_ostream &OS, const void *Ptr,
                           NodeKind Kind) const {
   switch (Kind) {
index 61e8a0ac37cbbccfe7cd1cb13103cffaef24b276..57f54cb0060f57199c8967e73c3c310774d7039e 100644 (file)
@@ -9,6 +9,7 @@
 
 #include "gtest/gtest.h"
 #include "llvm/ADT/Twine.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace llvm;
 
@@ -69,6 +70,13 @@ TEST(TwineTest, Concat) {
             repr(Twine("a").concat(Twine("b").concat(Twine("c")))));
 }
 
+TEST(TwineTest, toNullTerminatedStringRef) {
+  SmallString<8> storage;
+  EXPECT_EQ(0, *Twine("hello").toNullTerminatedStringRef(storage).end());
+  EXPECT_EQ(0,
+           *Twine(StringRef("hello")).toNullTerminatedStringRef(storage).end());
+}
+
   // I suppose linking in the entire code generator to add a unit test to check
   // the code size of the concat operation is overkill... :)