llvm.org GIT mirror llvm / 7dc7ac3
Support/ADT/Twine: Add toNullTerminatedStringRef. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@120600 91177308-0d34-0410-b5e6-96231b3b80d8 Michael J. Spencer 8 years ago
3 changed file(s) with 28 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
381381 /// SmallVector and a StringRef to the SmallVector's data is returned.
382382 StringRef toStringRef(SmallVectorImpl &Out) const;
383383
384 /// toNullTerminatedStringRef - This returns the twine as a single null
385 /// terminated StringRef if it can be represented as such. Otherwise the
386 /// twine is written into the given SmallVector and a StringRef to the
387 /// SmallVector's data is returned.
388 ///
389 /// The returned StringRef's size does not include the null terminator.
390 StringRef toNullTerminatedStringRef(SmallVectorImpl &Out) const;
391
384392 /// print - Write the concatenated string represented by this twine to the
385393 /// stream \arg OS.
386394 void print(raw_ostream &OS) const;
2626 if (isSingleStringRef())
2727 return getSingleStringRef();
2828 toVector(Out);
29 return StringRef(Out.data(), Out.size());
30 }
31
32 StringRef Twine::toNullTerminatedStringRef(SmallVectorImpl &Out) const {
33 if (isSingleStringRef()) {
34 StringRef sr = getSingleStringRef();
35 if (*(sr.begin() + sr.size()) == 0)
36 return sr;
37 }
38 toVector(Out);
39 Out.push_back(0);
40 Out.pop_back();
2941 return StringRef(Out.data(), Out.size());
3042 }
3143
88
99 #include "gtest/gtest.h"
1010 #include "llvm/ADT/Twine.h"
11 #include "llvm/ADT/SmallString.h"
1112 #include "llvm/Support/raw_ostream.h"
1213 using namespace llvm;
1314
6869 repr(Twine("a").concat(Twine("b").concat(Twine("c")))));
6970 }
7071
72 TEST(TwineTest, toNullTerminatedStringRef) {
73 SmallString<8> storage;
74 EXPECT_EQ(0, *Twine("hello").toNullTerminatedStringRef(storage).end());
75 EXPECT_EQ(0,
76 *Twine(StringRef("hello")).toNullTerminatedStringRef(storage).end());
77 }
78
7179 // I suppose linking in the entire code generator to add a unit test to check
7280 // the code size of the concat operation is overkill... :)
7381