1 //===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the raw_ostream class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_SUPPORT_RAW_OSTREAM_H
15 #define LLVM_SUPPORT_RAW_OSTREAM_H
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
24 #include <system_error>
28 class formatv_object_base;
29 class format_object_base;
30 class FormattedString;
31 class FormattedNumber;
36 enum OpenFlags : unsigned;
38 } // end namespace sys
40 /// This class implements an extremely fast bulk output stream that can *only*
41 /// output to a stream. It does not support seeking, reopening, rewinding, line
42 /// buffered disciplines etc. It is a simple buffer that outputs
43 /// a chunk at a time.
46 /// The buffer is handled in such a way that the buffer is
47 /// uninitialized, unbuffered, or out of space when OutBufCur >=
48 /// OutBufEnd. Thus a single comparison suffices to determine if we
49 /// need to take the slow path to write a single character.
51 /// The buffer is in one of three states:
52 /// 1. Unbuffered (BufferMode == Unbuffered)
53 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
54 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
55 /// OutBufEnd - OutBufStart >= 1).
57 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
58 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
59 /// managed by the subclass.
61 /// If a subclass installs an external buffer using SetBuffer then it can wait
62 /// for a \see write_impl() call to handle the data which has been put into
64 char *OutBufStart, *OutBufEnd, *OutBufCur;
73 // color order matches ANSI escape sequence, don't change
86 explicit raw_ostream(bool unbuffered = false)
87 : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
88 // Start out ready to flush.
89 OutBufStart = OutBufEnd = OutBufCur = nullptr;
92 raw_ostream(const raw_ostream &) = delete;
93 void operator=(const raw_ostream &) = delete;
95 virtual ~raw_ostream();
97 /// tell - Return the current offset with the file.
98 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
100 //===--------------------------------------------------------------------===//
101 // Configuration Interface
102 //===--------------------------------------------------------------------===//
104 /// Set the stream to be buffered, with an automatically determined buffer
108 /// Set the stream to be buffered, using the specified buffer size.
109 void SetBufferSize(size_t Size) {
111 SetBufferAndMode(new char[Size], Size, InternalBuffer);
114 size_t GetBufferSize() const {
115 // If we're supposed to be buffered but haven't actually gotten around
116 // to allocating the buffer yet, return the value that would be used.
117 if (BufferMode != Unbuffered && OutBufStart == nullptr)
118 return preferred_buffer_size();
120 // Otherwise just return the size of the allocated buffer.
121 return OutBufEnd - OutBufStart;
124 /// Set the stream to be unbuffered. When unbuffered, the stream will flush
125 /// after every write. This routine will also flush the buffer immediately
126 /// when the stream is being set to unbuffered.
127 void SetUnbuffered() {
129 SetBufferAndMode(nullptr, 0, Unbuffered);
132 size_t GetNumBytesInBuffer() const {
133 return OutBufCur - OutBufStart;
136 //===--------------------------------------------------------------------===//
137 // Data Output Interface
138 //===--------------------------------------------------------------------===//
141 if (OutBufCur != OutBufStart)
145 raw_ostream &operator<<(char C) {
146 if (OutBufCur >= OutBufEnd)
152 raw_ostream &operator<<(unsigned char C) {
153 if (OutBufCur >= OutBufEnd)
159 raw_ostream &operator<<(signed char C) {
160 if (OutBufCur >= OutBufEnd)
166 raw_ostream &operator<<(StringRef Str) {
167 // Inline fast path, particularly for strings with a known length.
168 size_t Size = Str.size();
170 // Make sure we can use the fast path.
171 if (Size > (size_t)(OutBufEnd - OutBufCur))
172 return write(Str.data(), Size);
175 memcpy(OutBufCur, Str.data(), Size);
181 raw_ostream &operator<<(const char *Str) {
182 // Inline fast path, particularly for constant strings where a sufficiently
183 // smart compiler will simplify strlen.
185 return this->operator<<(StringRef(Str));
188 raw_ostream &operator<<(const std::string &Str) {
189 // Avoid the fast path, it would only increase code size for a marginal win.
190 return write(Str.data(), Str.length());
193 raw_ostream &operator<<(const SmallVectorImpl<char> &Str) {
194 return write(Str.data(), Str.size());
197 raw_ostream &operator<<(unsigned long N);
198 raw_ostream &operator<<(long N);
199 raw_ostream &operator<<(unsigned long long N);
200 raw_ostream &operator<<(long long N);
201 raw_ostream &operator<<(const void *P);
203 raw_ostream &operator<<(unsigned int N) {
204 return this->operator<<(static_cast<unsigned long>(N));
207 raw_ostream &operator<<(int N) {
208 return this->operator<<(static_cast<long>(N));
211 raw_ostream &operator<<(double N);
213 /// Output \p N in hexadecimal, without any prefix or padding.
214 raw_ostream &write_hex(unsigned long long N);
216 /// Output a formatted UUID with dash separators.
217 using uuid_t = uint8_t[16];
218 raw_ostream &write_uuid(const uuid_t UUID);
220 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
221 /// satisfy std::isprint into an escape sequence.
222 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
224 raw_ostream &write(unsigned char C);
225 raw_ostream &write(const char *Ptr, size_t Size);
227 // Formatted output, see the format() function in Support/Format.h.
228 raw_ostream &operator<<(const format_object_base &Fmt);
230 // Formatted output, see the leftJustify() function in Support/Format.h.
231 raw_ostream &operator<<(const FormattedString &);
233 // Formatted output, see the formatHex() function in Support/Format.h.
234 raw_ostream &operator<<(const FormattedNumber &);
236 // Formatted output, see the formatv() function in Support/FormatVariadic.h.
237 raw_ostream &operator<<(const formatv_object_base &);
239 // Formatted output, see the format_bytes() function in Support/Format.h.
240 raw_ostream &operator<<(const FormattedBytes &);
242 /// indent - Insert 'NumSpaces' spaces.
243 raw_ostream &indent(unsigned NumSpaces);
245 /// Changes the foreground color of text that will be output from this point
247 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
248 /// change only the bold attribute, and keep colors untouched
249 /// @param Bold bold/brighter text, default false
250 /// @param BG if true change the background, default: change foreground
251 /// @returns itself so it can be used within << invocations
252 virtual raw_ostream &changeColor(enum Colors Color,
261 /// Resets the colors to terminal defaults. Call this when you are done
262 /// outputting colored text, or before program exit.
263 virtual raw_ostream &resetColor() { return *this; }
265 /// Reverses the foreground and background colors.
266 virtual raw_ostream &reverseColor() { return *this; }
268 /// This function determines if this stream is connected to a "tty" or
269 /// "console" window. That is, the output would be displayed to the user
270 /// rather than being put on a pipe or stored in a file.
271 virtual bool is_displayed() const { return false; }
273 /// This function determines if this stream is displayed and supports colors.
274 virtual bool has_colors() const { return is_displayed(); }
276 //===--------------------------------------------------------------------===//
277 // Subclass Interface
278 //===--------------------------------------------------------------------===//
281 /// The is the piece of the class that is implemented by subclasses. This
282 /// writes the \p Size bytes starting at
283 /// \p Ptr to the underlying stream.
285 /// This function is guaranteed to only be called at a point at which it is
286 /// safe for the subclass to install a new buffer via SetBuffer.
288 /// \param Ptr The start of the data to be written. For buffered streams this
289 /// is guaranteed to be the start of the buffer.
291 /// \param Size The number of bytes to be written.
293 /// \invariant { Size > 0 }
294 virtual void write_impl(const char *Ptr, size_t Size) = 0;
296 // An out of line virtual method to provide a home for the class vtable.
297 virtual void handle();
299 /// Return the current position within the stream, not counting the bytes
300 /// currently in the buffer.
301 virtual uint64_t current_pos() const = 0;
304 /// Use the provided buffer as the raw_ostream buffer. This is intended for
305 /// use only by subclasses which can arrange for the output to go directly
306 /// into the desired output buffer, instead of being copied on each flush.
307 void SetBuffer(char *BufferStart, size_t Size) {
308 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
311 /// Return an efficient buffer size for the underlying output mechanism.
312 virtual size_t preferred_buffer_size() const;
314 /// Return the beginning of the current stream buffer, or 0 if the stream is
316 const char *getBufferStart() const { return OutBufStart; }
318 //===--------------------------------------------------------------------===//
320 //===--------------------------------------------------------------------===//
322 /// Install the given buffer and mode.
323 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
325 /// Flush the current buffer, which is known to be non-empty. This outputs the
326 /// currently buffered data and resets the buffer to empty.
327 void flush_nonempty();
329 /// Copy data into the buffer. Size must not be greater than the number of
330 /// unused bytes in the buffer.
331 void copy_to_buffer(const char *Ptr, size_t Size);
334 /// An abstract base class for streams implementations that also support a
335 /// pwrite operation. This is useful for code that can mostly stream out data,
336 /// but needs to patch in a header that needs to know the output size.
337 class raw_pwrite_stream : public raw_ostream {
338 virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
341 explicit raw_pwrite_stream(bool Unbuffered = false)
342 : raw_ostream(Unbuffered) {}
343 void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
345 uint64_t Pos = tell();
346 // /dev/null always reports a pos of 0, so we cannot perform this check
349 assert(Size + Offset <= Pos && "We don't support extending the stream");
351 pwrite_impl(Ptr, Size, Offset);
355 //===----------------------------------------------------------------------===//
356 // File Output Streams
357 //===----------------------------------------------------------------------===//
359 /// A raw_ostream that writes to a file descriptor.
361 class raw_fd_ostream : public raw_pwrite_stream {
369 bool SupportsSeeking;
371 /// See raw_ostream::write_impl.
372 void write_impl(const char *Ptr, size_t Size) override;
374 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
376 /// Return the current position within the stream, not counting the bytes
377 /// currently in the buffer.
378 uint64_t current_pos() const override { return pos; }
380 /// Determine an efficient buffer size.
381 size_t preferred_buffer_size() const override;
383 /// Set the flag indicating that an output error has been encountered.
384 void error_detected(std::error_code EC) { this->EC = EC; }
387 /// Open the specified file for writing. If an error occurs, information
388 /// about the error is put into EC, and the stream should be immediately
390 /// \p Flags allows optional flags to control how the file will be opened.
392 /// As a special case, if Filename is "-", then the stream will use
393 /// STDOUT_FILENO instead of opening a file. This will not close the stdout
395 raw_fd_ostream(StringRef Filename, std::error_code &EC,
396 sys::fs::OpenFlags Flags);
398 /// FD is the file descriptor that this writes to. If ShouldClose is true,
399 /// this closes the file when the stream is destroyed. If FD is for stdout or
400 /// stderr, it will not be closed.
401 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
403 ~raw_fd_ostream() override;
405 /// Manually flush the stream and close the file. Note that this does not call
409 bool supportsSeeking() { return SupportsSeeking; }
411 /// Flushes the stream and repositions the underlying file descriptor position
412 /// to the offset specified from the beginning of the file.
413 uint64_t seek(uint64_t off);
415 raw_ostream &changeColor(enum Colors colors, bool bold=false,
416 bool bg=false) override;
417 raw_ostream &resetColor() override;
419 raw_ostream &reverseColor() override;
421 bool is_displayed() const override;
423 bool has_colors() const override;
425 std::error_code error() const { return EC; }
427 /// Return the value of the flag in this raw_fd_ostream indicating whether an
428 /// output error has been encountered.
429 /// This doesn't implicitly flush any pending output. Also, it doesn't
430 /// guarantee to detect all errors unless the stream has been closed.
431 bool has_error() const { return bool(EC); }
433 /// Set the flag read by has_error() to false. If the error flag is set at the
434 /// time when this raw_ostream's destructor is called, report_fatal_error is
435 /// called to report the error. Use clear_error() after handling the error to
436 /// avoid this behavior.
438 /// "Errors should never pass silently.
439 /// Unless explicitly silenced."
440 /// - from The Zen of Python, by Tim Peters
442 void clear_error() { EC = std::error_code(); }
445 /// This returns a reference to a raw_ostream for standard output. Use it like:
446 /// outs() << "foo" << "bar";
449 /// This returns a reference to a raw_ostream for standard error. Use it like:
450 /// errs() << "foo" << "bar";
453 /// This returns a reference to a raw_ostream which simply discards output.
454 raw_ostream &nulls();
456 //===----------------------------------------------------------------------===//
457 // Output Stream Adaptors
458 //===----------------------------------------------------------------------===//
460 /// A raw_ostream that writes to an std::string. This is a simple adaptor
461 /// class. This class does not encounter output errors.
462 class raw_string_ostream : public raw_ostream {
465 /// See raw_ostream::write_impl.
466 void write_impl(const char *Ptr, size_t Size) override;
468 /// Return the current position within the stream, not counting the bytes
469 /// currently in the buffer.
470 uint64_t current_pos() const override { return OS.size(); }
473 explicit raw_string_ostream(std::string &O) : OS(O) {}
474 ~raw_string_ostream() override;
476 /// Flushes the stream contents to the target string and returns the string's
484 /// A raw_ostream that writes to an SmallVector or SmallString. This is a
485 /// simple adaptor class. This class does not encounter output errors.
486 /// raw_svector_ostream operates without a buffer, delegating all memory
487 /// management to the SmallString. Thus the SmallString is always up-to-date,
488 /// may be used directly and there is no need to call flush().
489 class raw_svector_ostream : public raw_pwrite_stream {
490 SmallVectorImpl<char> &OS;
492 /// See raw_ostream::write_impl.
493 void write_impl(const char *Ptr, size_t Size) override;
495 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
497 /// Return the current position within the stream.
498 uint64_t current_pos() const override;
501 /// Construct a new raw_svector_ostream.
503 /// \param O The vector to write to; this should generally have at least 128
504 /// bytes free to avoid any extraneous memory overhead.
505 explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
509 ~raw_svector_ostream() override = default;
511 void flush() = delete;
513 /// Return a StringRef for the vector contents.
514 StringRef str() { return StringRef(OS.data(), OS.size()); }
517 /// A raw_ostream that discards all output.
518 class raw_null_ostream : public raw_pwrite_stream {
519 /// See raw_ostream::write_impl.
520 void write_impl(const char *Ptr, size_t size) override;
521 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
523 /// Return the current position within the stream, not counting the bytes
524 /// currently in the buffer.
525 uint64_t current_pos() const override;
528 explicit raw_null_ostream() = default;
529 ~raw_null_ostream() override;
532 class buffer_ostream : public raw_svector_ostream {
534 SmallVector<char, 0> Buffer;
537 buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {}
538 ~buffer_ostream() override { OS << str(); }
541 } // end namespace llvm
543 #endif // LLVM_SUPPORT_RAW_OSTREAM_H