From dbe77cfa0bcae10d91fbdbf118a97ec212afc88e Mon Sep 17 00:00:00 2001 From: Daniel Dunbar Date: Wed, 22 Jul 2009 17:13:20 +0000 Subject: [PATCH] Support writing a StringRef to a raw_ostream directly. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@76754 91177308-0d34-0410-b5e6-96231b3b80d8 --- include/llvm/Support/raw_ostream.h | 21 ++++++++++++++------- unittests/ADT/StringRefTest.cpp | 6 ++++++ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/include/llvm/Support/raw_ostream.h b/include/llvm/Support/raw_ostream.h index 4c7338eac4c..74a4206c235 100644 --- a/include/llvm/Support/raw_ostream.h +++ b/include/llvm/Support/raw_ostream.h @@ -15,6 +15,7 @@ #define LLVM_SUPPORT_RAW_OSTREAM_H #include "llvm/ADT/StringExtras.h" +#include "llvm/ADT/StringRef.h" #include #include #include @@ -151,21 +152,27 @@ public: return *this; } - raw_ostream &operator<<(const char *Str) { - // Inline fast path, particulary for constant strings where a - // sufficiently smart compiler will simplify strlen. - - size_t Size = strlen(Str); + raw_ostream &operator<<(const StringRef &Str) { + // Inline fast path, particularly for strings with a known length. + size_t Size = Str.size(); // Make sure we can use the fast path. if (OutBufCur+Size > OutBufEnd) - return write(Str, Size); + return write(Str.data(), Size); - memcpy(OutBufCur, Str, Size); + memcpy(OutBufCur, Str.data(), Size); OutBufCur += Size; return *this; } + raw_ostream &operator<<(const char *Str) { + // Inline fast path, particulary for constant strings where a sufficiently + // smart compiler will simplify strlen. + + this->operator<<(StringRef(Str)); + return *this; + } + raw_ostream &operator<<(const std::string& Str) { write(Str.data(), Str.length()); return *this; diff --git a/unittests/ADT/StringRefTest.cpp b/unittests/ADT/StringRefTest.cpp index bb46dc010a5..ba2216debd6 100644 --- a/unittests/ADT/StringRefTest.cpp +++ b/unittests/ADT/StringRefTest.cpp @@ -9,6 +9,7 @@ #include "gtest/gtest.h" #include "llvm/ADT/StringRef.h" +#include "llvm/Support/raw_ostream.h" using namespace llvm; namespace { @@ -66,6 +67,11 @@ TEST(StringRefTest, Utilities) { EXPECT_TRUE(Str.startswith("he")); EXPECT_FALSE(Str.startswith("helloworld")); EXPECT_FALSE(Str.startswith("hi")); + + std::string Storage; + raw_string_ostream OS(Storage); + OS << StringRef("hello"); + EXPECT_EQ("hello", OS.str()); } } // end anonymous namespace -- 2.11.0