Add raw_ostream::write_escaped, for writing escaped strings.
authorDaniel Dunbar <daniel@zuster.org>
Sat, 17 Oct 2009 20:43:08 +0000 (20:43 +0000)
committerDaniel Dunbar <daniel@zuster.org>
Sat, 17 Oct 2009 20:43:08 +0000 (20:43 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@84355 91177308-0d34-0410-b5e6-96231b3b80d8

include/llvm/Support/raw_ostream.h
lib/Support/raw_ostream.cpp
unittests/Support/raw_ostream_test.cpp

index 8012b6fdfc0875b9abb36f815a4f23afe1e93650..e67ff85a7927e456b8a994c696d5ae85b0a7c91d 100644 (file)
@@ -216,6 +216,10 @@ public:
   /// write_hex - Output \arg N in hexadecimal, without any prefix or padding.
   raw_ostream &write_hex(unsigned long long N);
 
+  /// write_escaped - Output \arg Str, turning '\\', '\t', '\n', '"', and
+  /// anything that doesn't satisfy std::isprint into an escape sequence.
+  raw_ostream &write_escaped(StringRef Str);
+
   raw_ostream &write(unsigned char C);
   raw_ostream &write(const char *Ptr, size_t Size);
 
index 0a82cc1d10c394ff33fceb2b55bcdc2c26d5f63e..31451ccfdb148c389ff08703ac95df6e239abdfa 100644 (file)
@@ -168,6 +168,40 @@ raw_ostream &raw_ostream::write_hex(unsigned long long N) {
   return write(CurPtr, EndPtr-CurPtr);
 }
 
+raw_ostream &raw_ostream::write_escaped(StringRef Str) {
+  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
+    unsigned char c = Str[i];
+
+    switch (c) {
+    case '\\':
+      *this << '\\' << '\\';
+      break;
+    case '\t':
+      *this << '\\' << 't';
+      break;
+    case '\n':
+      *this << '\\' << 'n';
+      break;
+    case '"':
+      *this << '\\' << '"';
+      break;
+    default:
+      if (std::isprint(c)) {
+        *this << c;
+        break;
+      }
+
+      // Always expand to a 3-character octal escape.
+      *this << '\\';
+      *this << char('0' + ((c >> 6) & 7));
+      *this << char('0' + ((c >> 3) & 7));
+      *this << char('0' + ((c >> 0) & 7));
+    }
+  }
+
+  return *this;
+}
+
 raw_ostream &raw_ostream::operator<<(const void *P) {
   *this << '0' << 'x';
 
index bd2e95cbb531418b7e9fb46fa4fe127497ae9432..2b797b43666bac648e573cbaadbf77833c4b5027 100644 (file)
@@ -127,4 +127,20 @@ TEST(raw_ostreamTest, TinyBuffer) {
   EXPECT_EQ("hello1world", OS.str());
 }
 
+TEST(raw_ostreamTest, WriteEscaped) {
+  std::string Str;
+
+  Str = "";
+  raw_string_ostream(Str).write_escaped("hi");
+  EXPECT_EQ("hi", Str);
+
+  Str = "";
+  raw_string_ostream(Str).write_escaped("\\\t\n\"");
+  EXPECT_EQ("\\\\\\t\\n\\\"", Str);
+
+  Str = "";
+  raw_string_ostream(Str).write_escaped("\1\10\200");
+  EXPECT_EQ("\\001\\010\\200", Str);
+}
+
 }