1 //===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
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 // This file defines the raw_ostream class.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_SUPPORT_RAW_OSTREAM_H
14 #define LLVM_SUPPORT_RAW_OSTREAM_H
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringRef.h"
23 #include <system_error>
27 class formatv_object_base
;
28 class format_object_base
;
29 class FormattedString
;
30 class FormattedNumber
;
35 enum FileAccess
: unsigned;
36 enum OpenFlags
: unsigned;
37 enum CreationDisposition
: unsigned;
39 } // end namespace sys
41 /// This class implements an extremely fast bulk output stream that can *only*
42 /// output to a stream. It does not support seeking, reopening, rewinding, line
43 /// buffered disciplines etc. It is a simple buffer that outputs
44 /// a chunk at a time.
47 /// The buffer is handled in such a way that the buffer is
48 /// uninitialized, unbuffered, or out of space when OutBufCur >=
49 /// OutBufEnd. Thus a single comparison suffices to determine if we
50 /// need to take the slow path to write a single character.
52 /// The buffer is in one of three states:
53 /// 1. Unbuffered (BufferMode == Unbuffered)
54 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
55 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
56 /// OutBufEnd - OutBufStart >= 1).
58 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
59 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
60 /// managed by the subclass.
62 /// If a subclass installs an external buffer using SetBuffer then it can wait
63 /// for a \see write_impl() call to handle the data which has been put into
65 char *OutBufStart
, *OutBufEnd
, *OutBufCur
;
74 // color order matches ANSI escape sequence, don't change
88 static const Colors BLACK
= Colors::BLACK
;
89 static const Colors RED
= Colors::RED
;
90 static const Colors GREEN
= Colors::GREEN
;
91 static const Colors YELLOW
= Colors::YELLOW
;
92 static const Colors BLUE
= Colors::BLUE
;
93 static const Colors MAGENTA
= Colors::MAGENTA
;
94 static const Colors CYAN
= Colors::CYAN
;
95 static const Colors WHITE
= Colors::WHITE
;
96 static const Colors SAVEDCOLOR
= Colors::SAVEDCOLOR
;
97 static const Colors RESET
= Colors::RESET
;
99 explicit raw_ostream(bool unbuffered
= false)
100 : BufferMode(unbuffered
? Unbuffered
: InternalBuffer
) {
101 // Start out ready to flush.
102 OutBufStart
= OutBufEnd
= OutBufCur
= nullptr;
105 raw_ostream(const raw_ostream
&) = delete;
106 void operator=(const raw_ostream
&) = delete;
108 virtual ~raw_ostream();
110 /// tell - Return the current offset with the file.
111 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
113 //===--------------------------------------------------------------------===//
114 // Configuration Interface
115 //===--------------------------------------------------------------------===//
117 /// Set the stream to be buffered, with an automatically determined buffer
121 /// Set the stream to be buffered, using the specified buffer size.
122 void SetBufferSize(size_t Size
) {
124 SetBufferAndMode(new char[Size
], Size
, InternalBuffer
);
127 size_t GetBufferSize() const {
128 // If we're supposed to be buffered but haven't actually gotten around
129 // to allocating the buffer yet, return the value that would be used.
130 if (BufferMode
!= Unbuffered
&& OutBufStart
== nullptr)
131 return preferred_buffer_size();
133 // Otherwise just return the size of the allocated buffer.
134 return OutBufEnd
- OutBufStart
;
137 /// Set the stream to be unbuffered. When unbuffered, the stream will flush
138 /// after every write. This routine will also flush the buffer immediately
139 /// when the stream is being set to unbuffered.
140 void SetUnbuffered() {
142 SetBufferAndMode(nullptr, 0, Unbuffered
);
145 size_t GetNumBytesInBuffer() const {
146 return OutBufCur
- OutBufStart
;
149 //===--------------------------------------------------------------------===//
150 // Data Output Interface
151 //===--------------------------------------------------------------------===//
154 if (OutBufCur
!= OutBufStart
)
158 raw_ostream
&operator<<(char C
) {
159 if (OutBufCur
>= OutBufEnd
)
165 raw_ostream
&operator<<(unsigned char C
) {
166 if (OutBufCur
>= OutBufEnd
)
172 raw_ostream
&operator<<(signed char C
) {
173 if (OutBufCur
>= OutBufEnd
)
179 raw_ostream
&operator<<(StringRef Str
) {
180 // Inline fast path, particularly for strings with a known length.
181 size_t Size
= Str
.size();
183 // Make sure we can use the fast path.
184 if (Size
> (size_t)(OutBufEnd
- OutBufCur
))
185 return write(Str
.data(), Size
);
188 memcpy(OutBufCur
, Str
.data(), Size
);
194 raw_ostream
&operator<<(const char *Str
) {
195 // Inline fast path, particularly for constant strings where a sufficiently
196 // smart compiler will simplify strlen.
198 return this->operator<<(StringRef(Str
));
201 raw_ostream
&operator<<(const std::string
&Str
) {
202 // Avoid the fast path, it would only increase code size for a marginal win.
203 return write(Str
.data(), Str
.length());
206 raw_ostream
&operator<<(const SmallVectorImpl
<char> &Str
) {
207 return write(Str
.data(), Str
.size());
210 raw_ostream
&operator<<(unsigned long N
);
211 raw_ostream
&operator<<(long N
);
212 raw_ostream
&operator<<(unsigned long long N
);
213 raw_ostream
&operator<<(long long N
);
214 raw_ostream
&operator<<(const void *P
);
216 raw_ostream
&operator<<(unsigned int N
) {
217 return this->operator<<(static_cast<unsigned long>(N
));
220 raw_ostream
&operator<<(int N
) {
221 return this->operator<<(static_cast<long>(N
));
224 raw_ostream
&operator<<(double N
);
226 /// Output \p N in hexadecimal, without any prefix or padding.
227 raw_ostream
&write_hex(unsigned long long N
);
229 // Change the foreground color of text.
230 raw_ostream
&operator<<(Colors C
);
232 /// Output a formatted UUID with dash separators.
233 using uuid_t
= uint8_t[16];
234 raw_ostream
&write_uuid(const uuid_t UUID
);
236 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
237 /// satisfy llvm::isPrint into an escape sequence.
238 raw_ostream
&write_escaped(StringRef Str
, bool UseHexEscapes
= false);
240 raw_ostream
&write(unsigned char C
);
241 raw_ostream
&write(const char *Ptr
, size_t Size
);
243 // Formatted output, see the format() function in Support/Format.h.
244 raw_ostream
&operator<<(const format_object_base
&Fmt
);
246 // Formatted output, see the leftJustify() function in Support/Format.h.
247 raw_ostream
&operator<<(const FormattedString
&);
249 // Formatted output, see the formatHex() function in Support/Format.h.
250 raw_ostream
&operator<<(const FormattedNumber
&);
252 // Formatted output, see the formatv() function in Support/FormatVariadic.h.
253 raw_ostream
&operator<<(const formatv_object_base
&);
255 // Formatted output, see the format_bytes() function in Support/Format.h.
256 raw_ostream
&operator<<(const FormattedBytes
&);
258 /// indent - Insert 'NumSpaces' spaces.
259 raw_ostream
&indent(unsigned NumSpaces
);
261 /// write_zeros - Insert 'NumZeros' nulls.
262 raw_ostream
&write_zeros(unsigned NumZeros
);
264 /// Changes the foreground color of text that will be output from this point
266 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
267 /// change only the bold attribute, and keep colors untouched
268 /// @param Bold bold/brighter text, default false
269 /// @param BG if true change the background, default: change foreground
270 /// @returns itself so it can be used within << invocations
271 virtual raw_ostream
&changeColor(enum Colors Color
,
280 /// Resets the colors to terminal defaults. Call this when you are done
281 /// outputting colored text, or before program exit.
282 virtual raw_ostream
&resetColor() { return *this; }
284 /// Reverses the foreground and background colors.
285 virtual raw_ostream
&reverseColor() { return *this; }
287 /// This function determines if this stream is connected to a "tty" or
288 /// "console" window. That is, the output would be displayed to the user
289 /// rather than being put on a pipe or stored in a file.
290 virtual bool is_displayed() const { return false; }
292 /// This function determines if this stream is displayed and supports colors.
293 virtual bool has_colors() const { return is_displayed(); }
295 // Enable or disable colors. Once disable_colors() is called,
296 // changeColor() has no effect until enable_colors() is called.
297 virtual void enable_colors(bool /*enable*/) {}
299 //===--------------------------------------------------------------------===//
300 // Subclass Interface
301 //===--------------------------------------------------------------------===//
304 /// The is the piece of the class that is implemented by subclasses. This
305 /// writes the \p Size bytes starting at
306 /// \p Ptr to the underlying stream.
308 /// This function is guaranteed to only be called at a point at which it is
309 /// safe for the subclass to install a new buffer via SetBuffer.
311 /// \param Ptr The start of the data to be written. For buffered streams this
312 /// is guaranteed to be the start of the buffer.
314 /// \param Size The number of bytes to be written.
316 /// \invariant { Size > 0 }
317 virtual void write_impl(const char *Ptr
, size_t Size
) = 0;
319 /// Return the current position within the stream, not counting the bytes
320 /// currently in the buffer.
321 virtual uint64_t current_pos() const = 0;
324 /// Use the provided buffer as the raw_ostream buffer. This is intended for
325 /// use only by subclasses which can arrange for the output to go directly
326 /// into the desired output buffer, instead of being copied on each flush.
327 void SetBuffer(char *BufferStart
, size_t Size
) {
328 SetBufferAndMode(BufferStart
, Size
, ExternalBuffer
);
331 /// Return an efficient buffer size for the underlying output mechanism.
332 virtual size_t preferred_buffer_size() const;
334 /// Return the beginning of the current stream buffer, or 0 if the stream is
336 const char *getBufferStart() const { return OutBufStart
; }
338 //===--------------------------------------------------------------------===//
340 //===--------------------------------------------------------------------===//
342 /// Install the given buffer and mode.
343 void SetBufferAndMode(char *BufferStart
, size_t Size
, BufferKind Mode
);
345 /// Flush the current buffer, which is known to be non-empty. This outputs the
346 /// currently buffered data and resets the buffer to empty.
347 void flush_nonempty();
349 /// Copy data into the buffer. Size must not be greater than the number of
350 /// unused bytes in the buffer.
351 void copy_to_buffer(const char *Ptr
, size_t Size
);
353 virtual void anchor();
356 /// An abstract base class for streams implementations that also support a
357 /// pwrite operation. This is useful for code that can mostly stream out data,
358 /// but needs to patch in a header that needs to know the output size.
359 class raw_pwrite_stream
: public raw_ostream
{
360 virtual void pwrite_impl(const char *Ptr
, size_t Size
, uint64_t Offset
) = 0;
361 void anchor() override
;
364 explicit raw_pwrite_stream(bool Unbuffered
= false)
365 : raw_ostream(Unbuffered
) {}
366 void pwrite(const char *Ptr
, size_t Size
, uint64_t Offset
) {
368 uint64_t Pos
= tell();
369 // /dev/null always reports a pos of 0, so we cannot perform this check
372 assert(Size
+ Offset
<= Pos
&& "We don't support extending the stream");
374 pwrite_impl(Ptr
, Size
, Offset
);
378 //===----------------------------------------------------------------------===//
379 // File Output Streams
380 //===----------------------------------------------------------------------===//
382 /// A raw_ostream that writes to a file descriptor.
384 class raw_fd_ostream
: public raw_pwrite_stream
{
387 bool SupportsSeeking
;
388 bool ColorEnabled
= true;
391 /// True if this fd refers to a Windows console device. Mintty and other
392 /// terminal emulators are TTYs, but they are not consoles.
393 bool IsWindowsConsole
= false;
400 /// See raw_ostream::write_impl.
401 void write_impl(const char *Ptr
, size_t Size
) override
;
403 void pwrite_impl(const char *Ptr
, size_t Size
, uint64_t Offset
) override
;
405 /// Return the current position within the stream, not counting the bytes
406 /// currently in the buffer.
407 uint64_t current_pos() const override
{ return pos
; }
409 /// Determine an efficient buffer size.
410 size_t preferred_buffer_size() const override
;
412 /// Set the flag indicating that an output error has been encountered.
413 void error_detected(std::error_code EC
) { this->EC
= EC
; }
415 void anchor() override
;
418 /// Open the specified file for writing. If an error occurs, information
419 /// about the error is put into EC, and the stream should be immediately
421 /// \p Flags allows optional flags to control how the file will be opened.
423 /// As a special case, if Filename is "-", then the stream will use
424 /// STDOUT_FILENO instead of opening a file. This will not close the stdout
426 raw_fd_ostream(StringRef Filename
, std::error_code
&EC
);
427 raw_fd_ostream(StringRef Filename
, std::error_code
&EC
,
428 sys::fs::CreationDisposition Disp
);
429 raw_fd_ostream(StringRef Filename
, std::error_code
&EC
,
430 sys::fs::FileAccess Access
);
431 raw_fd_ostream(StringRef Filename
, std::error_code
&EC
,
432 sys::fs::OpenFlags Flags
);
433 raw_fd_ostream(StringRef Filename
, std::error_code
&EC
,
434 sys::fs::CreationDisposition Disp
, sys::fs::FileAccess Access
,
435 sys::fs::OpenFlags Flags
);
437 /// FD is the file descriptor that this writes to. If ShouldClose is true,
438 /// this closes the file when the stream is destroyed. If FD is for stdout or
439 /// stderr, it will not be closed.
440 raw_fd_ostream(int fd
, bool shouldClose
, bool unbuffered
=false);
442 ~raw_fd_ostream() override
;
444 /// Manually flush the stream and close the file. Note that this does not call
448 bool supportsSeeking() { return SupportsSeeking
; }
450 /// Flushes the stream and repositions the underlying file descriptor position
451 /// to the offset specified from the beginning of the file.
452 uint64_t seek(uint64_t off
);
454 raw_ostream
&changeColor(enum Colors colors
, bool bold
=false,
455 bool bg
=false) override
;
456 raw_ostream
&resetColor() override
;
458 raw_ostream
&reverseColor() override
;
460 bool is_displayed() const override
;
462 bool has_colors() const override
;
464 void enable_colors(bool enable
) override
{ ColorEnabled
= enable
; }
466 std::error_code
error() const { return EC
; }
468 /// Return the value of the flag in this raw_fd_ostream indicating whether an
469 /// output error has been encountered.
470 /// This doesn't implicitly flush any pending output. Also, it doesn't
471 /// guarantee to detect all errors unless the stream has been closed.
472 bool has_error() const { return bool(EC
); }
474 /// Set the flag read by has_error() to false. If the error flag is set at the
475 /// time when this raw_ostream's destructor is called, report_fatal_error is
476 /// called to report the error. Use clear_error() after handling the error to
477 /// avoid this behavior.
479 /// "Errors should never pass silently.
480 /// Unless explicitly silenced."
481 /// - from The Zen of Python, by Tim Peters
483 void clear_error() { EC
= std::error_code(); }
486 /// This returns a reference to a raw_ostream for standard output. Use it like:
487 /// outs() << "foo" << "bar";
490 /// This returns a reference to a raw_ostream for standard error. Use it like:
491 /// errs() << "foo" << "bar";
494 /// This returns a reference to a raw_ostream which simply discards output.
495 raw_ostream
&nulls();
497 //===----------------------------------------------------------------------===//
498 // Output Stream Adaptors
499 //===----------------------------------------------------------------------===//
501 /// A raw_ostream that writes to an std::string. This is a simple adaptor
502 /// class. This class does not encounter output errors.
503 class raw_string_ostream
: public raw_ostream
{
506 /// See raw_ostream::write_impl.
507 void write_impl(const char *Ptr
, size_t Size
) override
;
509 /// Return the current position within the stream, not counting the bytes
510 /// currently in the buffer.
511 uint64_t current_pos() const override
{ return OS
.size(); }
514 explicit raw_string_ostream(std::string
&O
) : OS(O
) {}
515 ~raw_string_ostream() override
;
517 /// Flushes the stream contents to the target string and returns the string's
525 /// A raw_ostream that writes to an SmallVector or SmallString. This is a
526 /// simple adaptor class. This class does not encounter output errors.
527 /// raw_svector_ostream operates without a buffer, delegating all memory
528 /// management to the SmallString. Thus the SmallString is always up-to-date,
529 /// may be used directly and there is no need to call flush().
530 class raw_svector_ostream
: public raw_pwrite_stream
{
531 SmallVectorImpl
<char> &OS
;
533 /// See raw_ostream::write_impl.
534 void write_impl(const char *Ptr
, size_t Size
) override
;
536 void pwrite_impl(const char *Ptr
, size_t Size
, uint64_t Offset
) override
;
538 /// Return the current position within the stream.
539 uint64_t current_pos() const override
;
542 /// Construct a new raw_svector_ostream.
544 /// \param O The vector to write to; this should generally have at least 128
545 /// bytes free to avoid any extraneous memory overhead.
546 explicit raw_svector_ostream(SmallVectorImpl
<char> &O
) : OS(O
) {
550 ~raw_svector_ostream() override
= default;
552 void flush() = delete;
554 /// Return a StringRef for the vector contents.
555 StringRef
str() { return StringRef(OS
.data(), OS
.size()); }
558 /// A raw_ostream that discards all output.
559 class raw_null_ostream
: public raw_pwrite_stream
{
560 /// See raw_ostream::write_impl.
561 void write_impl(const char *Ptr
, size_t size
) override
;
562 void pwrite_impl(const char *Ptr
, size_t Size
, uint64_t Offset
) override
;
564 /// Return the current position within the stream, not counting the bytes
565 /// currently in the buffer.
566 uint64_t current_pos() const override
;
569 explicit raw_null_ostream() = default;
570 ~raw_null_ostream() override
;
573 class buffer_ostream
: public raw_svector_ostream
{
575 SmallVector
<char, 0> Buffer
;
577 virtual void anchor() override
;
580 buffer_ostream(raw_ostream
&OS
) : raw_svector_ostream(Buffer
), OS(OS
) {}
581 ~buffer_ostream() override
{ OS
<< str(); }
584 } // end namespace llvm
586 #endif // LLVM_SUPPORT_RAW_OSTREAM_H