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>
24 #include <type_traits>
28 class formatv_object_base;
29 class format_object_base;
30 class FormattedString;
31 class FormattedNumber;
36 enum FileAccess : unsigned;
37 enum OpenFlags : unsigned;
38 enum CreationDisposition : unsigned;
40 } // end namespace sys
42 /// This class implements an extremely fast bulk output stream that can *only*
43 /// output to a stream. It does not support seeking, reopening, rewinding, line
44 /// buffered disciplines etc. It is a simple buffer that outputs
45 /// a chunk at a time.
48 /// The buffer is handled in such a way that the buffer is
49 /// uninitialized, unbuffered, or out of space when OutBufCur >=
50 /// OutBufEnd. Thus a single comparison suffices to determine if we
51 /// need to take the slow path to write a single character.
53 /// The buffer is in one of three states:
54 /// 1. Unbuffered (BufferMode == Unbuffered)
55 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
56 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
57 /// OutBufEnd - OutBufStart >= 1).
59 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
60 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
61 /// managed by the subclass.
63 /// If a subclass installs an external buffer using SetBuffer then it can wait
64 /// for a \see write_impl() call to handle the data which has been put into
66 char *OutBufStart, *OutBufEnd, *OutBufCur;
68 enum class BufferKind {
75 // color order matches ANSI escape sequence, don't change
89 static const Colors BLACK = Colors::BLACK;
90 static const Colors RED = Colors::RED;
91 static const Colors GREEN = Colors::GREEN;
92 static const Colors YELLOW = Colors::YELLOW;
93 static const Colors BLUE = Colors::BLUE;
94 static const Colors MAGENTA = Colors::MAGENTA;
95 static const Colors CYAN = Colors::CYAN;
96 static const Colors WHITE = Colors::WHITE;
97 static const Colors SAVEDCOLOR = Colors::SAVEDCOLOR;
98 static const Colors RESET = Colors::RESET;
100 explicit raw_ostream(bool unbuffered = false)
101 : BufferMode(unbuffered ? BufferKind::Unbuffered
102 : BufferKind::InternalBuffer) {
103 // Start out ready to flush.
104 OutBufStart = OutBufEnd = OutBufCur = nullptr;
107 raw_ostream(const raw_ostream &) = delete;
108 void operator=(const raw_ostream &) = delete;
110 virtual ~raw_ostream();
112 /// tell - Return the current offset with the file.
113 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
115 //===--------------------------------------------------------------------===//
116 // Configuration Interface
117 //===--------------------------------------------------------------------===//
119 /// Set the stream to be buffered, with an automatically determined buffer
123 /// Set the stream to be buffered, using the specified buffer size.
124 void SetBufferSize(size_t Size) {
126 SetBufferAndMode(new char[Size], Size, BufferKind::InternalBuffer);
129 size_t GetBufferSize() const {
130 // If we're supposed to be buffered but haven't actually gotten around
131 // to allocating the buffer yet, return the value that would be used.
132 if (BufferMode != BufferKind::Unbuffered && OutBufStart == nullptr)
133 return preferred_buffer_size();
135 // Otherwise just return the size of the allocated buffer.
136 return OutBufEnd - OutBufStart;
139 /// Set the stream to be unbuffered. When unbuffered, the stream will flush
140 /// after every write. This routine will also flush the buffer immediately
141 /// when the stream is being set to unbuffered.
142 void SetUnbuffered() {
144 SetBufferAndMode(nullptr, 0, BufferKind::Unbuffered);
147 size_t GetNumBytesInBuffer() const {
148 return OutBufCur - OutBufStart;
151 //===--------------------------------------------------------------------===//
152 // Data Output Interface
153 //===--------------------------------------------------------------------===//
156 if (OutBufCur != OutBufStart)
160 raw_ostream &operator<<(char C) {
161 if (OutBufCur >= OutBufEnd)
167 raw_ostream &operator<<(unsigned char C) {
168 if (OutBufCur >= OutBufEnd)
174 raw_ostream &operator<<(signed char C) {
175 if (OutBufCur >= OutBufEnd)
181 raw_ostream &operator<<(StringRef Str) {
182 // Inline fast path, particularly for strings with a known length.
183 size_t Size = Str.size();
185 // Make sure we can use the fast path.
186 if (Size > (size_t)(OutBufEnd - OutBufCur))
187 return write(Str.data(), Size);
190 memcpy(OutBufCur, Str.data(), Size);
196 raw_ostream &operator<<(const char *Str) {
197 // Inline fast path, particularly for constant strings where a sufficiently
198 // smart compiler will simplify strlen.
200 return this->operator<<(StringRef(Str));
203 raw_ostream &operator<<(const std::string &Str) {
204 // Avoid the fast path, it would only increase code size for a marginal win.
205 return write(Str.data(), Str.length());
208 raw_ostream &operator<<(const SmallVectorImpl<char> &Str) {
209 return write(Str.data(), Str.size());
212 raw_ostream &operator<<(unsigned long N);
213 raw_ostream &operator<<(long N);
214 raw_ostream &operator<<(unsigned long long N);
215 raw_ostream &operator<<(long long N);
216 raw_ostream &operator<<(const void *P);
218 raw_ostream &operator<<(unsigned int N) {
219 return this->operator<<(static_cast<unsigned long>(N));
222 raw_ostream &operator<<(int N) {
223 return this->operator<<(static_cast<long>(N));
226 raw_ostream &operator<<(double N);
228 /// Output \p N in hexadecimal, without any prefix or padding.
229 raw_ostream &write_hex(unsigned long long N);
231 // Change the foreground color of text.
232 raw_ostream &operator<<(Colors C);
234 /// Output a formatted UUID with dash separators.
235 using uuid_t = uint8_t[16];
236 raw_ostream &write_uuid(const uuid_t UUID);
238 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
239 /// satisfy llvm::isPrint into an escape sequence.
240 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
242 raw_ostream &write(unsigned char C);
243 raw_ostream &write(const char *Ptr, size_t Size);
245 // Formatted output, see the format() function in Support/Format.h.
246 raw_ostream &operator<<(const format_object_base &Fmt);
248 // Formatted output, see the leftJustify() function in Support/Format.h.
249 raw_ostream &operator<<(const FormattedString &);
251 // Formatted output, see the formatHex() function in Support/Format.h.
252 raw_ostream &operator<<(const FormattedNumber &);
254 // Formatted output, see the formatv() function in Support/FormatVariadic.h.
255 raw_ostream &operator<<(const formatv_object_base &);
257 // Formatted output, see the format_bytes() function in Support/Format.h.
258 raw_ostream &operator<<(const FormattedBytes &);
260 /// indent - Insert 'NumSpaces' spaces.
261 raw_ostream &indent(unsigned NumSpaces);
263 /// write_zeros - Insert 'NumZeros' nulls.
264 raw_ostream &write_zeros(unsigned NumZeros);
266 /// Changes the foreground color of text that will be output from this point
268 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
269 /// change only the bold attribute, and keep colors untouched
270 /// @param Bold bold/brighter text, default false
271 /// @param BG if true change the background, default: change foreground
272 /// @returns itself so it can be used within << invocations
273 virtual raw_ostream &changeColor(enum Colors Color,
282 /// Resets the colors to terminal defaults. Call this when you are done
283 /// outputting colored text, or before program exit.
284 virtual raw_ostream &resetColor() { return *this; }
286 /// Reverses the foreground and background colors.
287 virtual raw_ostream &reverseColor() { return *this; }
289 /// This function determines if this stream is connected to a "tty" or
290 /// "console" window. That is, the output would be displayed to the user
291 /// rather than being put on a pipe or stored in a file.
292 virtual bool is_displayed() const { return false; }
294 /// This function determines if this stream is displayed and supports colors.
295 virtual bool has_colors() const { return is_displayed(); }
297 // Enable or disable colors. Once disable_colors() is called,
298 // changeColor() has no effect until enable_colors() is called.
299 virtual void enable_colors(bool /*enable*/) {}
301 //===--------------------------------------------------------------------===//
302 // Subclass Interface
303 //===--------------------------------------------------------------------===//
306 /// The is the piece of the class that is implemented by subclasses. This
307 /// writes the \p Size bytes starting at
308 /// \p Ptr to the underlying stream.
310 /// This function is guaranteed to only be called at a point at which it is
311 /// safe for the subclass to install a new buffer via SetBuffer.
313 /// \param Ptr The start of the data to be written. For buffered streams this
314 /// is guaranteed to be the start of the buffer.
316 /// \param Size The number of bytes to be written.
318 /// \invariant { Size > 0 }
319 virtual void write_impl(const char *Ptr, size_t Size) = 0;
321 /// Return the current position within the stream, not counting the bytes
322 /// currently in the buffer.
323 virtual uint64_t current_pos() const = 0;
326 /// Use the provided buffer as the raw_ostream buffer. This is intended for
327 /// use only by subclasses which can arrange for the output to go directly
328 /// into the desired output buffer, instead of being copied on each flush.
329 void SetBuffer(char *BufferStart, size_t Size) {
330 SetBufferAndMode(BufferStart, Size, BufferKind::ExternalBuffer);
333 /// Return an efficient buffer size for the underlying output mechanism.
334 virtual size_t preferred_buffer_size() const;
336 /// Return the beginning of the current stream buffer, or 0 if the stream is
338 const char *getBufferStart() const { return OutBufStart; }
340 //===--------------------------------------------------------------------===//
342 //===--------------------------------------------------------------------===//
344 /// Install the given buffer and mode.
345 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
347 /// Flush the current buffer, which is known to be non-empty. This outputs the
348 /// currently buffered data and resets the buffer to empty.
349 void flush_nonempty();
351 /// Copy data into the buffer. Size must not be greater than the number of
352 /// unused bytes in the buffer.
353 void copy_to_buffer(const char *Ptr, size_t Size);
355 virtual void anchor();
358 /// Call the appropriate insertion operator, given an rvalue reference to a
359 /// raw_ostream object and return a stream of the same type as the argument.
360 template <typename OStream, typename T>
361 typename std::enable_if<!std::is_reference<OStream>::value &&
362 std::is_base_of<raw_ostream, OStream>::value,
364 operator<<(OStream &&OS, const T &Value) {
366 return std::move(OS);
369 /// An abstract base class for streams implementations that also support a
370 /// pwrite operation. This is useful for code that can mostly stream out data,
371 /// but needs to patch in a header that needs to know the output size.
372 class raw_pwrite_stream : public raw_ostream {
373 virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
374 void anchor() override;
377 explicit raw_pwrite_stream(bool Unbuffered = false)
378 : raw_ostream(Unbuffered) {}
379 void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
381 uint64_t Pos = tell();
382 // /dev/null always reports a pos of 0, so we cannot perform this check
385 assert(Size + Offset <= Pos && "We don't support extending the stream");
387 pwrite_impl(Ptr, Size, Offset);
391 //===----------------------------------------------------------------------===//
392 // File Output Streams
393 //===----------------------------------------------------------------------===//
395 /// A raw_ostream that writes to a file descriptor.
397 class raw_fd_ostream : public raw_pwrite_stream {
400 bool SupportsSeeking = false;
401 bool ColorEnabled = true;
404 /// True if this fd refers to a Windows console device. Mintty and other
405 /// terminal emulators are TTYs, but they are not consoles.
406 bool IsWindowsConsole = false;
413 /// See raw_ostream::write_impl.
414 void write_impl(const char *Ptr, size_t Size) override;
416 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
418 /// Return the current position within the stream, not counting the bytes
419 /// currently in the buffer.
420 uint64_t current_pos() const override { return pos; }
422 /// Determine an efficient buffer size.
423 size_t preferred_buffer_size() const override;
425 /// Set the flag indicating that an output error has been encountered.
426 void error_detected(std::error_code EC) { this->EC = EC; }
428 void anchor() override;
431 /// Open the specified file for writing. If an error occurs, information
432 /// about the error is put into EC, and the stream should be immediately
434 /// \p Flags allows optional flags to control how the file will be opened.
436 /// As a special case, if Filename is "-", then the stream will use
437 /// STDOUT_FILENO instead of opening a file. This will not close the stdout
439 raw_fd_ostream(StringRef Filename, std::error_code &EC);
440 raw_fd_ostream(StringRef Filename, std::error_code &EC,
441 sys::fs::CreationDisposition Disp);
442 raw_fd_ostream(StringRef Filename, std::error_code &EC,
443 sys::fs::FileAccess Access);
444 raw_fd_ostream(StringRef Filename, std::error_code &EC,
445 sys::fs::OpenFlags Flags);
446 raw_fd_ostream(StringRef Filename, std::error_code &EC,
447 sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access,
448 sys::fs::OpenFlags Flags);
450 /// FD is the file descriptor that this writes to. If ShouldClose is true,
451 /// this closes the file when the stream is destroyed. If FD is for stdout or
452 /// stderr, it will not be closed.
453 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
455 ~raw_fd_ostream() override;
457 /// Manually flush the stream and close the file. Note that this does not call
461 bool supportsSeeking() { return SupportsSeeking; }
463 /// Flushes the stream and repositions the underlying file descriptor position
464 /// to the offset specified from the beginning of the file.
465 uint64_t seek(uint64_t off);
467 raw_ostream &changeColor(enum Colors colors, bool bold=false,
468 bool bg=false) override;
469 raw_ostream &resetColor() override;
471 raw_ostream &reverseColor() override;
473 bool is_displayed() const override;
475 bool has_colors() const override;
477 void enable_colors(bool enable) override { ColorEnabled = enable; }
479 std::error_code error() const { return EC; }
481 /// Return the value of the flag in this raw_fd_ostream indicating whether an
482 /// output error has been encountered.
483 /// This doesn't implicitly flush any pending output. Also, it doesn't
484 /// guarantee to detect all errors unless the stream has been closed.
485 bool has_error() const { return bool(EC); }
487 /// Set the flag read by has_error() to false. If the error flag is set at the
488 /// time when this raw_ostream's destructor is called, report_fatal_error is
489 /// called to report the error. Use clear_error() after handling the error to
490 /// avoid this behavior.
492 /// "Errors should never pass silently.
493 /// Unless explicitly silenced."
494 /// - from The Zen of Python, by Tim Peters
496 void clear_error() { EC = std::error_code(); }
499 /// This returns a reference to a raw_ostream for standard output. Use it like:
500 /// outs() << "foo" << "bar";
503 /// This returns a reference to a raw_ostream for standard error. Use it like:
504 /// errs() << "foo" << "bar";
507 /// This returns a reference to a raw_ostream which simply discards output.
508 raw_ostream &nulls();
510 //===----------------------------------------------------------------------===//
511 // Output Stream Adaptors
512 //===----------------------------------------------------------------------===//
514 /// A raw_ostream that writes to an std::string. This is a simple adaptor
515 /// class. This class does not encounter output errors.
516 class raw_string_ostream : public raw_ostream {
519 /// See raw_ostream::write_impl.
520 void write_impl(const char *Ptr, size_t Size) override;
522 /// Return the current position within the stream, not counting the bytes
523 /// currently in the buffer.
524 uint64_t current_pos() const override { return OS.size(); }
527 explicit raw_string_ostream(std::string &O) : OS(O) {}
528 ~raw_string_ostream() override;
530 /// Flushes the stream contents to the target string and returns the string's
538 /// A raw_ostream that writes to an SmallVector or SmallString. This is a
539 /// simple adaptor class. This class does not encounter output errors.
540 /// raw_svector_ostream operates without a buffer, delegating all memory
541 /// management to the SmallString. Thus the SmallString is always up-to-date,
542 /// may be used directly and there is no need to call flush().
543 class raw_svector_ostream : public raw_pwrite_stream {
544 SmallVectorImpl<char> &OS;
546 /// See raw_ostream::write_impl.
547 void write_impl(const char *Ptr, size_t Size) override;
549 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
551 /// Return the current position within the stream.
552 uint64_t current_pos() const override;
555 /// Construct a new raw_svector_ostream.
557 /// \param O The vector to write to; this should generally have at least 128
558 /// bytes free to avoid any extraneous memory overhead.
559 explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
563 ~raw_svector_ostream() override = default;
565 void flush() = delete;
567 /// Return a StringRef for the vector contents.
568 StringRef str() { return StringRef(OS.data(), OS.size()); }
571 /// A raw_ostream that discards all output.
572 class raw_null_ostream : public raw_pwrite_stream {
573 /// See raw_ostream::write_impl.
574 void write_impl(const char *Ptr, size_t size) override;
575 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
577 /// Return the current position within the stream, not counting the bytes
578 /// currently in the buffer.
579 uint64_t current_pos() const override;
582 explicit raw_null_ostream() = default;
583 ~raw_null_ostream() override;
586 class buffer_ostream : public raw_svector_ostream {
588 SmallVector<char, 0> Buffer;
590 virtual void anchor() override;
593 buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {}
594 ~buffer_ostream() override { OS << str(); }
597 } // end namespace llvm
599 #endif // LLVM_SUPPORT_RAW_OSTREAM_H