llvm.org GIT mirror llvm / 522b113
Add raw_ostream::write_escaped, for writing escaped strings. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@84355 91177308-0d34-0410-b5e6-96231b3b80d8 Daniel Dunbar 10 years ago
3 changed file(s) with 54 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
215215 /// write_hex - Output \arg N in hexadecimal, without any prefix or padding.
216216 raw_ostream &write_hex(unsigned long long N);
217217
218 /// write_escaped - Output \arg Str, turning '\\', '\t', '\n', '"', and
219 /// anything that doesn't satisfy std::isprint into an escape sequence.
220 raw_ostream &write_escaped(StringRef Str);
221
218222 raw_ostream &write(unsigned char C);
219223 raw_ostream &write(const char *Ptr, size_t Size);
220224
165165 }
166166
167167 return write(CurPtr, EndPtr-CurPtr);
168 }
169
170 raw_ostream &raw_ostream::write_escaped(StringRef Str) {
171 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
172 unsigned char c = Str[i];
173
174 switch (c) {
175 case '\\':
176 *this << '\\' << '\\';
177 break;
178 case '\t':
179 *this << '\\' << 't';
180 break;
181 case '\n':
182 *this << '\\' << 'n';
183 break;
184 case '"':
185 *this << '\\' << '"';
186 break;
187 default:
188 if (std::isprint(c)) {
189 *this << c;
190 break;
191 }
192
193 // Always expand to a 3-character octal escape.
194 *this << '\\';
195 *this << char('0' + ((c >> 6) & 7));
196 *this << char('0' + ((c >> 3) & 7));
197 *this << char('0' + ((c >> 0) & 7));
198 }
199 }
200
201 return *this;
168202 }
169203
170204 raw_ostream &raw_ostream::operator<<(const void *P) {
126126 EXPECT_EQ("hello1world", OS.str());
127127 }
128128
129 TEST(raw_ostreamTest, WriteEscaped) {
130 std::string Str;
131
132 Str = "";
133 raw_string_ostream(Str).write_escaped("hi");
134 EXPECT_EQ("hi", Str);
135
136 Str = "";
137 raw_string_ostream(Str).write_escaped("\\\t\n\"");
138 EXPECT_EQ("\\\\\\t\\n\\\"", Str);
139
140 Str = "";
141 raw_string_ostream(Str).write_escaped("\1\10\200");
142 EXPECT_EQ("\\001\\010\\200", Str);
129143 }
144
145 }