1 //===- llvm/unittest/Support/raw_ostream_test.cpp - raw_ostream tests -----===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/ADT/SmallString.h"
10 #include "llvm/Support/Errc.h"
11 #include "llvm/Support/FileSystem.h"
12 #include "llvm/Support/FileUtilities.h"
13 #include "llvm/Support/Format.h"
14 #include "llvm/Support/MemoryBuffer.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include "llvm/Testing/Support/Error.h"
17 #include "gtest/gtest.h"
23 template<typename T
> std::string
printToString(const T
&Value
) {
25 llvm::raw_string_ostream
OS(res
);
32 /// printToString - Print the given value to a stream which only has \arg
33 /// BytesLeftInBuffer bytes left in the buffer. This is useful for testing edge
34 /// cases in the buffer handling logic.
35 template<typename T
> std::string
printToString(const T
&Value
,
36 unsigned BytesLeftInBuffer
) {
37 // FIXME: This is relying on internal knowledge of how raw_ostream works to
38 // get the buffer position right.
39 SmallString
<256> SVec
;
40 assert(BytesLeftInBuffer
< 256 && "Invalid buffer count!");
41 llvm::raw_svector_ostream
OS(SVec
);
42 unsigned StartIndex
= 256 - BytesLeftInBuffer
;
43 for (unsigned i
= 0; i
!= StartIndex
; ++i
)
46 return std::string(OS
.str().substr(StartIndex
));
49 template<typename T
> std::string
printToStringUnbuffered(const T
&Value
) {
51 llvm::raw_string_ostream
OS(res
);
59 raw_ostream
&operator<<(raw_ostream
&OS
, const X
&) { return OS
<< 'X'; }
61 TEST(raw_ostreamTest
, Types_Buffered
) {
63 EXPECT_EQ("c", printToString('c'));
66 EXPECT_EQ("hello", printToString("hello"));
67 EXPECT_EQ("hello", printToString(std::string("hello")));
70 EXPECT_EQ("0", printToString(0));
71 EXPECT_EQ("2425", printToString(2425));
72 EXPECT_EQ("-2425", printToString(-2425));
75 EXPECT_EQ("0", printToString(0LL));
76 EXPECT_EQ("257257257235709", printToString(257257257235709LL));
77 EXPECT_EQ("-257257257235709", printToString(-257257257235709LL));
80 EXPECT_EQ("1.100000e+00", printToString(1.1));
83 EXPECT_EQ("0x0", printToString((void*) nullptr));
84 EXPECT_EQ("0xbeef", printToString((void*) 0xbeefLL
));
85 EXPECT_EQ("0xdeadbeef", printToString((void*) 0xdeadbeefLL
));
88 EXPECT_EQ("18446744073709551615", printToString(UINT64_MAX
));
89 EXPECT_EQ("-9223372036854775808", printToString(INT64_MIN
));
91 // X, checking free operator<<().
92 EXPECT_EQ("X", printToString(X
{}));
95 TEST(raw_ostreamTest
, Types_Unbuffered
) {
97 EXPECT_EQ("c", printToStringUnbuffered('c'));
100 EXPECT_EQ("hello", printToStringUnbuffered("hello"));
101 EXPECT_EQ("hello", printToStringUnbuffered(std::string("hello")));
104 EXPECT_EQ("0", printToStringUnbuffered(0));
105 EXPECT_EQ("2425", printToStringUnbuffered(2425));
106 EXPECT_EQ("-2425", printToStringUnbuffered(-2425));
109 EXPECT_EQ("0", printToStringUnbuffered(0LL));
110 EXPECT_EQ("257257257235709", printToStringUnbuffered(257257257235709LL));
111 EXPECT_EQ("-257257257235709", printToStringUnbuffered(-257257257235709LL));
114 EXPECT_EQ("1.100000e+00", printToStringUnbuffered(1.1));
117 EXPECT_EQ("0x0", printToStringUnbuffered((void*) nullptr));
118 EXPECT_EQ("0xbeef", printToStringUnbuffered((void*) 0xbeefLL
));
119 EXPECT_EQ("0xdeadbeef", printToStringUnbuffered((void*) 0xdeadbeefLL
));
122 EXPECT_EQ("18446744073709551615", printToStringUnbuffered(UINT64_MAX
));
123 EXPECT_EQ("-9223372036854775808", printToStringUnbuffered(INT64_MIN
));
125 // X, checking free operator<<().
126 EXPECT_EQ("X", printToString(X
{}));
129 TEST(raw_ostreamTest
, BufferEdge
) {
130 EXPECT_EQ("1.20", printToString(format("%.2f", 1.2), 1));
131 EXPECT_EQ("1.20", printToString(format("%.2f", 1.2), 2));
132 EXPECT_EQ("1.20", printToString(format("%.2f", 1.2), 3));
133 EXPECT_EQ("1.20", printToString(format("%.2f", 1.2), 4));
134 EXPECT_EQ("1.20", printToString(format("%.2f", 1.2), 10));
137 TEST(raw_ostreamTest
, TinyBuffer
) {
139 raw_string_ostream
OS(Str
);
143 OS
<< 'w' << 'o' << 'r' << 'l' << 'd';
145 EXPECT_EQ("hello1world", Str
);
148 TEST(raw_ostreamTest
, WriteEscaped
) {
152 raw_string_ostream(Str
).write_escaped("hi");
153 EXPECT_EQ("hi", Str
);
156 raw_string_ostream(Str
).write_escaped("\\\t\n\"");
157 EXPECT_EQ("\\\\\\t\\n\\\"", Str
);
160 raw_string_ostream(Str
).write_escaped("\1\10\200");
161 EXPECT_EQ("\\001\\010\\200", Str
);
164 TEST(raw_ostreamTest
, Justify
) {
165 EXPECT_EQ("xyz ", printToString(left_justify("xyz", 6), 6));
166 EXPECT_EQ("abc", printToString(left_justify("abc", 3), 3));
167 EXPECT_EQ("big", printToString(left_justify("big", 1), 3));
168 EXPECT_EQ(" xyz", printToString(right_justify("xyz", 6), 6));
169 EXPECT_EQ("abc", printToString(right_justify("abc", 3), 3));
170 EXPECT_EQ("big", printToString(right_justify("big", 1), 3));
171 EXPECT_EQ(" on ", printToString(center_justify("on", 9), 9));
172 EXPECT_EQ(" off ", printToString(center_justify("off", 10), 10));
173 EXPECT_EQ("single ", printToString(center_justify("single", 7), 7));
174 EXPECT_EQ("none", printToString(center_justify("none", 1), 4));
175 EXPECT_EQ("none", printToString(center_justify("none", 1), 1));
178 TEST(raw_ostreamTest
, FormatHex
) {
179 EXPECT_EQ("0x1234", printToString(format_hex(0x1234, 6), 6));
180 EXPECT_EQ("0x001234", printToString(format_hex(0x1234, 8), 8));
181 EXPECT_EQ("0x00001234", printToString(format_hex(0x1234, 10), 10));
182 EXPECT_EQ("0x1234", printToString(format_hex(0x1234, 4), 6));
183 EXPECT_EQ("0xff", printToString(format_hex(255, 4), 4));
184 EXPECT_EQ("0xFF", printToString(format_hex(255, 4, true), 4));
185 EXPECT_EQ("0x1", printToString(format_hex(1, 3), 3));
186 EXPECT_EQ("0x12", printToString(format_hex(0x12, 3), 4));
187 EXPECT_EQ("0x123", printToString(format_hex(0x123, 3), 5));
188 EXPECT_EQ("FF", printToString(format_hex_no_prefix(0xFF, 2, true), 4));
189 EXPECT_EQ("ABCD", printToString(format_hex_no_prefix(0xABCD, 2, true), 4));
190 EXPECT_EQ("0xffffffffffffffff",
191 printToString(format_hex(UINT64_MAX
, 18), 18));
192 EXPECT_EQ("0x8000000000000000",
193 printToString(format_hex((INT64_MIN
), 18), 18));
196 TEST(raw_ostreamTest
, FormatDecimal
) {
197 EXPECT_EQ(" 0", printToString(format_decimal(0, 4), 4));
198 EXPECT_EQ(" -1", printToString(format_decimal(-1, 4), 4));
199 EXPECT_EQ(" -1", printToString(format_decimal(-1, 6), 6));
200 EXPECT_EQ("1234567890", printToString(format_decimal(1234567890, 10), 10));
201 EXPECT_EQ(" 9223372036854775807",
202 printToString(format_decimal(INT64_MAX
, 21), 21));
203 EXPECT_EQ(" -9223372036854775808",
204 printToString(format_decimal(INT64_MIN
, 21), 21));
207 static std::string
formatted_bytes_str(ArrayRef
<uint8_t> Bytes
,
208 llvm::Optional
<uint64_t> Offset
= None
,
209 uint32_t NumPerLine
= 16,
210 uint8_t ByteGroupSize
= 4) {
212 raw_string_ostream
Str(S
);
213 Str
<< format_bytes(Bytes
, Offset
, NumPerLine
, ByteGroupSize
);
218 static std::string
format_bytes_with_ascii_str(ArrayRef
<uint8_t> Bytes
,
219 Optional
<uint64_t> Offset
= None
,
220 uint32_t NumPerLine
= 16,
221 uint8_t ByteGroupSize
= 4) {
223 raw_string_ostream
Str(S
);
224 Str
<< format_bytes_with_ascii(Bytes
, Offset
, NumPerLine
, ByteGroupSize
);
229 TEST(raw_ostreamTest
, FormattedHexBytes
) {
230 std::vector
<uint8_t> Buf
= {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
231 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
232 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0',
233 '1', '2', '3', '4', '5', '6', '7', '8', '9'};
234 ArrayRef
<uint8_t> B(Buf
);
236 // Test invalid input.
237 EXPECT_EQ("", formatted_bytes_str(ArrayRef
<uint8_t>()));
238 EXPECT_EQ("", format_bytes_with_ascii_str(ArrayRef
<uint8_t>()));
239 //----------------------------------------------------------------------
240 // Test hex byte output with the default 4 byte groups
241 //----------------------------------------------------------------------
242 EXPECT_EQ("61", formatted_bytes_str(B
.take_front()));
243 EXPECT_EQ("61626364 65", formatted_bytes_str(B
.take_front(5)));
244 // Test that 16 bytes get written to a line correctly.
245 EXPECT_EQ("61626364 65666768 696a6b6c 6d6e6f70",
246 formatted_bytes_str(B
.take_front(16)));
247 // Test raw bytes with default 16 bytes per line wrapping.
248 EXPECT_EQ("61626364 65666768 696a6b6c 6d6e6f70\n71",
249 formatted_bytes_str(B
.take_front(17)));
250 // Test raw bytes with 1 bytes per line wrapping.
251 EXPECT_EQ("61\n62\n63\n64\n65\n66",
252 formatted_bytes_str(B
.take_front(6), None
, 1));
253 // Test raw bytes with 7 bytes per line wrapping.
254 EXPECT_EQ("61626364 656667\n68696a6b 6c6d6e\n6f7071",
255 formatted_bytes_str(B
.take_front(17), None
, 7));
256 // Test raw bytes with 8 bytes per line wrapping.
257 EXPECT_EQ("61626364 65666768\n696a6b6c 6d6e6f70\n71",
258 formatted_bytes_str(B
.take_front(17), None
, 8));
259 //----------------------------------------------------------------------
260 // Test hex byte output with the 1 byte groups
261 //----------------------------------------------------------------------
262 EXPECT_EQ("61 62 63 64 65",
263 formatted_bytes_str(B
.take_front(5), None
, 16, 1));
264 // Test that 16 bytes get written to a line correctly.
265 EXPECT_EQ("61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70",
266 formatted_bytes_str(B
.take_front(16), None
, 16, 1));
267 // Test raw bytes with default 16 bytes per line wrapping.
268 EXPECT_EQ("61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70\n71",
269 formatted_bytes_str(B
.take_front(17), None
, 16, 1));
270 // Test raw bytes with 7 bytes per line wrapping.
271 EXPECT_EQ("61 62 63 64 65 66 67\n68 69 6a 6b 6c 6d 6e\n6f 70 71",
272 formatted_bytes_str(B
.take_front(17), None
, 7, 1));
273 // Test raw bytes with 8 bytes per line wrapping.
274 EXPECT_EQ("61 62 63 64 65 66 67 68\n69 6a 6b 6c 6d 6e 6f 70\n71",
275 formatted_bytes_str(B
.take_front(17), None
, 8, 1));
277 //----------------------------------------------------------------------
278 // Test hex byte output with the 2 byte groups
279 //----------------------------------------------------------------------
280 EXPECT_EQ("6162 6364 65", formatted_bytes_str(B
.take_front(5), None
, 16, 2));
281 // Test that 16 bytes get written to a line correctly.
282 EXPECT_EQ("6162 6364 6566 6768 696a 6b6c 6d6e 6f70",
283 formatted_bytes_str(B
.take_front(16), None
, 16, 2));
284 // Test raw bytes with default 16 bytes per line wrapping.
285 EXPECT_EQ("6162 6364 6566 6768 696a 6b6c 6d6e 6f70\n71",
286 formatted_bytes_str(B
.take_front(17), None
, 16, 2));
287 // Test raw bytes with 7 bytes per line wrapping.
288 EXPECT_EQ("6162 6364 6566 67\n6869 6a6b 6c6d 6e\n6f70 71",
289 formatted_bytes_str(B
.take_front(17), None
, 7, 2));
290 // Test raw bytes with 8 bytes per line wrapping.
291 EXPECT_EQ("6162 6364 6566 6768\n696a 6b6c 6d6e 6f70\n71",
292 formatted_bytes_str(B
.take_front(17), None
, 8, 2));
294 //----------------------------------------------------------------------
295 // Test hex bytes with offset with the default 4 byte groups.
296 //----------------------------------------------------------------------
297 EXPECT_EQ("0000: 61", formatted_bytes_str(B
.take_front(), 0x0));
298 EXPECT_EQ("1000: 61", formatted_bytes_str(B
.take_front(), 0x1000));
299 EXPECT_EQ("1000: 61\n1001: 62",
300 formatted_bytes_str(B
.take_front(2), 0x1000, 1));
301 //----------------------------------------------------------------------
302 // Test hex bytes with ASCII with the default 4 byte groups.
303 //----------------------------------------------------------------------
304 EXPECT_EQ("61626364 65666768 696a6b6c 6d6e6f70 |abcdefghijklmnop|",
305 format_bytes_with_ascii_str(B
.take_front(16)));
306 EXPECT_EQ("61626364 65666768 |abcdefgh|\n"
307 "696a6b6c 6d6e6f70 |ijklmnop|",
308 format_bytes_with_ascii_str(B
.take_front(16), None
, 8));
309 EXPECT_EQ("61626364 65666768 |abcdefgh|\n696a6b6c |ijkl|",
310 format_bytes_with_ascii_str(B
.take_front(12), None
, 8));
311 std::vector
<uint8_t> Unprintable
= {'a', '\x1e', 'b', '\x1f'};
312 // Make sure the ASCII is still lined up correctly when fewer bytes than 16
313 // bytes per line are available. The ASCII should still be aligned as if 16
314 // bytes of hex might be displayed.
315 EXPECT_EQ("611e621f |a.b.|",
316 format_bytes_with_ascii_str(Unprintable
));
317 //----------------------------------------------------------------------
318 // Test hex bytes with ASCII with offsets with the default 4 byte groups.
319 //----------------------------------------------------------------------
320 EXPECT_EQ("0000: 61626364 65666768 "
321 "696a6b6c 6d6e6f70 |abcdefghijklmnop|",
322 format_bytes_with_ascii_str(B
.take_front(16), 0));
323 EXPECT_EQ("0000: 61626364 65666768 |abcdefgh|\n"
324 "0008: 696a6b6c 6d6e6f70 |ijklmnop|",
325 format_bytes_with_ascii_str(B
.take_front(16), 0, 8));
326 EXPECT_EQ("0000: 61626364 656667 |abcdefg|\n"
327 "0007: 68696a6b 6c |hijkl|",
328 format_bytes_with_ascii_str(B
.take_front(12), 0, 7));
330 //----------------------------------------------------------------------
331 // Test hex bytes with ASCII with offsets with the default 2 byte groups.
332 //----------------------------------------------------------------------
333 EXPECT_EQ("0000: 6162 6364 6566 6768 "
334 "696a 6b6c 6d6e 6f70 |abcdefghijklmnop|",
335 format_bytes_with_ascii_str(B
.take_front(16), 0, 16, 2));
336 EXPECT_EQ("0000: 6162 6364 6566 6768 |abcdefgh|\n"
337 "0008: 696a 6b6c 6d6e 6f70 |ijklmnop|",
338 format_bytes_with_ascii_str(B
.take_front(16), 0, 8, 2));
339 EXPECT_EQ("0000: 6162 6364 6566 67 |abcdefg|\n"
340 "0007: 6869 6a6b 6c |hijkl|",
341 format_bytes_with_ascii_str(B
.take_front(12), 0, 7, 2));
343 //----------------------------------------------------------------------
344 // Test hex bytes with ASCII with offsets with the default 1 byte groups.
345 //----------------------------------------------------------------------
346 EXPECT_EQ("0000: 61 62 63 64 65 66 67 68 "
347 "69 6a 6b 6c 6d 6e 6f 70 |abcdefghijklmnop|",
348 format_bytes_with_ascii_str(B
.take_front(16), 0, 16, 1));
349 EXPECT_EQ("0000: 61 62 63 64 65 66 67 68 |abcdefgh|\n"
350 "0008: 69 6a 6b 6c 6d 6e 6f 70 |ijklmnop|",
351 format_bytes_with_ascii_str(B
.take_front(16), 0, 8, 1));
352 EXPECT_EQ("0000: 61 62 63 64 65 66 67 |abcdefg|\n"
353 "0007: 68 69 6a 6b 6c |hijkl|",
354 format_bytes_with_ascii_str(B
.take_front(12), 0, 7, 1));
358 TEST(raw_ostreamTest
, Colors
) {
361 raw_string_ostream
Sos(S
);
362 Sos
.enable_colors(false);
363 Sos
.changeColor(raw_ostream::YELLOW
);
364 EXPECT_EQ("", Sos
.str());
369 raw_string_ostream
Sos(S
);
370 Sos
.enable_colors(true);
371 Sos
.changeColor(raw_ostream::YELLOW
);
372 EXPECT_EQ("\x1B[0;33m", Sos
.str());
377 TEST(raw_fd_ostreamTest
, multiple_raw_fd_ostream_to_stdout
) {
380 { raw_fd_ostream("-", EC
, sys::fs::OpenFlags::OF_None
); }
381 { raw_fd_ostream("-", EC
, sys::fs::OpenFlags::OF_None
); }
384 TEST(raw_ostreamTest
, flush_tied_to_stream_on_write
) {
385 std::string TiedToBuffer
;
386 raw_string_ostream
TiedTo(TiedToBuffer
);
387 TiedTo
.SetBuffered();
391 raw_string_ostream
TiedStream(Buffer
);
392 TiedStream
.tie(&TiedTo
);
393 // Sanity check that the stream hasn't already been flushed.
394 EXPECT_EQ("", TiedToBuffer
);
396 // Empty string doesn't cause a flush of TiedTo.
398 EXPECT_EQ("", TiedToBuffer
);
400 // Non-empty strings trigger flush of TiedTo.
402 EXPECT_EQ("a", TiedToBuffer
);
404 // Single char write flushes TiedTo.
407 EXPECT_EQ("ac", TiedToBuffer
);
409 // Write to buffered stream without flush does not flush TiedTo.
410 TiedStream
.SetBuffered();
411 TiedStream
.SetBufferSize(2);
414 EXPECT_EQ("ac", TiedToBuffer
);
416 // Explicit flush of buffered stream flushes TiedTo.
418 EXPECT_EQ("ace", TiedToBuffer
);
420 // Explicit flush of buffered stream with empty buffer does not flush TiedTo.
423 EXPECT_EQ("ace", TiedToBuffer
);
425 // Write of data to empty buffer that is greater than buffer size flushes
427 TiedStream
<< "hijklm";
428 EXPECT_EQ("aceg", TiedToBuffer
);
430 // Write of data that overflows buffer size also flushes TiedTo.
435 EXPECT_EQ("acego", TiedToBuffer
);
437 // Streams can be tied to each other safely.
440 TiedTo
.tie(&TiedStream
);
441 TiedTo
.SetBufferSize(2);
444 EXPECT_EQ("", Buffer
);
445 EXPECT_EQ("acego", TiedToBuffer
);
447 EXPECT_EQ("r", Buffer
);
449 EXPECT_EQ("acegostuv", TiedToBuffer
);
450 // The x remains in the buffer, since it was written after the flush of
452 EXPECT_EQ("rwx", Buffer
);
455 // Calling tie with nullptr unties stream.
456 TiedStream
.SetUnbuffered();
457 TiedStream
.tie(nullptr);
460 EXPECT_EQ("acegostuv", TiedToBuffer
);
466 TEST(raw_ostreamTest
, reserve_stream
) {
468 raw_string_ostream
OS(Str
);
469 OS
<< "11111111111111111111";
470 uint64_t CurrentPos
= OS
.tell();
471 OS
.reserveExtraSpace(1000);
472 EXPECT_GE(Str
.capacity(), CurrentPos
+ 1000);
475 OS
<< 'w' << 'o' << 'r' << 'l' << 'd';
477 EXPECT_EQ("11111111111111111111hello1world", Str
);
480 static void checkFileData(StringRef FileName
, StringRef GoldenData
) {
481 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufOrErr
=
482 MemoryBuffer::getFileOrSTDIN(FileName
);
483 EXPECT_FALSE(BufOrErr
.getError());
485 EXPECT_EQ((*BufOrErr
)->getBufferSize(), GoldenData
.size());
486 EXPECT_EQ(memcmp((*BufOrErr
)->getBufferStart(), GoldenData
.data(),
491 TEST(raw_ostreamTest
, writeToOutputFile
) {
492 SmallString
<64> Path
;
494 ASSERT_FALSE(sys::fs::createTemporaryFile("foo", "bar", FD
, Path
));
495 FileRemover
Cleanup(Path
);
497 ASSERT_THAT_ERROR(writeToOutput(Path
,
498 [](raw_ostream
&Out
) -> Error
{
500 return Error::success();
503 checkFileData(Path
, "HelloWorld");
506 TEST(raw_ostreamTest
, writeToNonexistingPath
) {
507 StringRef FileName
= "/_bad/_path";
508 std::string ErrorMessage
= toString(createFileError(
509 FileName
, make_error_code(errc::no_such_file_or_directory
)));
511 EXPECT_THAT_ERROR(writeToOutput(FileName
,
512 [](raw_ostream
&Out
) -> Error
{
514 return Error::success();
516 FailedWithMessage(ErrorMessage
));
519 TEST(raw_ostreamTest
, writeToDevNull
) {
520 bool DevNullIsUsed
= false;
523 writeToOutput("/dev/null",
524 [&](raw_ostream
&Out
) -> Error
{
526 testing::internal::CheckedDowncastToActualType
<
527 raw_null_ostream
, raw_ostream
>(&Out
);
528 return Error::success();
532 EXPECT_TRUE(DevNullIsUsed
);
535 TEST(raw_ostreamTest
, writeToStdOut
) {
537 testing::internal::CaptureStdout();
539 EXPECT_THAT_ERROR(writeToOutput("-",
540 [](raw_ostream
&Out
) -> Error
{
542 return Error::success();
547 std::string CapturedStdOut
= testing::internal::GetCapturedStdout();
548 EXPECT_EQ(CapturedStdOut
, "HelloWorld");