Support/ADT/Twine: Add toNullTerminatedStringRef.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@120600 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Michael J. Spencer 2010-12-01 20:37:30 +00:00
parent f00140c8e1
commit 7dc7ac3cb2
3 changed files with 28 additions and 0 deletions

View 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;

View 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) {

View 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... :)