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"
19 #include "llvm/Support/DataTypes.h"
21 #include <system_error>
24 class format_object_base;
25 class FormattedString;
26 class FormattedNumber;
28 template <typename T> class SmallVectorImpl;
32 enum OpenFlags : unsigned;
36 /// Type of function that prints to raw_ostream.
39 /// Printable PrintFoo(Foo x) {
40 /// return [] (raw_ostream &os) { os << /* ... */; };
42 /// os << "Foo: " << PrintFoo(foo) << '\n';
43 typedef std::function<void(raw_ostream&)> Printable;
45 /// This class implements an extremely fast bulk output stream that can *only*
46 /// output to a stream. It does not support seeking, reopening, rewinding, line
47 /// buffered disciplines etc. It is a simple buffer that outputs
48 /// a chunk at a time.
51 void operator=(const raw_ostream &) = delete;
52 raw_ostream(const raw_ostream &) = delete;
54 /// The buffer is handled in such a way that the buffer is
55 /// uninitialized, unbuffered, or out of space when OutBufCur >=
56 /// OutBufEnd. Thus a single comparison suffices to determine if we
57 /// need to take the slow path to write a single character.
59 /// The buffer is in one of three states:
60 /// 1. Unbuffered (BufferMode == Unbuffered)
61 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
62 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
63 /// OutBufEnd - OutBufStart >= 1).
65 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
66 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
67 /// managed by the subclass.
69 /// If a subclass installs an external buffer using SetBuffer then it can wait
70 /// for a \see write_impl() call to handle the data which has been put into
72 char *OutBufStart, *OutBufEnd, *OutBufCur;
81 // color order matches ANSI escape sequence, don't change
94 explicit raw_ostream(bool unbuffered = false)
95 : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
96 // Start out ready to flush.
97 OutBufStart = OutBufEnd = OutBufCur = nullptr;
100 virtual ~raw_ostream();
102 /// tell - Return the current offset with the file.
103 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
105 //===--------------------------------------------------------------------===//
106 // Configuration Interface
107 //===--------------------------------------------------------------------===//
109 /// Set the stream to be buffered, with an automatically determined buffer
113 /// Set the stream to be buffered, using the specified buffer size.
114 void SetBufferSize(size_t Size) {
116 SetBufferAndMode(new char[Size], Size, InternalBuffer);
119 size_t GetBufferSize() const {
120 // If we're supposed to be buffered but haven't actually gotten around
121 // to allocating the buffer yet, return the value that would be used.
122 if (BufferMode != Unbuffered && OutBufStart == nullptr)
123 return preferred_buffer_size();
125 // Otherwise just return the size of the allocated buffer.
126 return OutBufEnd - OutBufStart;
129 /// Set the stream to be unbuffered. When unbuffered, the stream will flush
130 /// after every write. This routine will also flush the buffer immediately
131 /// when the stream is being set to unbuffered.
132 void SetUnbuffered() {
134 SetBufferAndMode(nullptr, 0, Unbuffered);
137 size_t GetNumBytesInBuffer() const {
138 return OutBufCur - OutBufStart;
141 //===--------------------------------------------------------------------===//
142 // Data Output Interface
143 //===--------------------------------------------------------------------===//
146 if (OutBufCur != OutBufStart)
150 raw_ostream &operator<<(char C) {
151 if (OutBufCur >= OutBufEnd)
157 raw_ostream &operator<<(unsigned char C) {
158 if (OutBufCur >= OutBufEnd)
164 raw_ostream &operator<<(signed char C) {
165 if (OutBufCur >= OutBufEnd)
171 raw_ostream &operator<<(StringRef Str) {
172 // Inline fast path, particularly for strings with a known length.
173 size_t Size = Str.size();
175 // Make sure we can use the fast path.
176 if (Size > (size_t)(OutBufEnd - OutBufCur))
177 return write(Str.data(), Size);
180 memcpy(OutBufCur, Str.data(), Size);
186 raw_ostream &operator<<(const char *Str) {
187 // Inline fast path, particularly for constant strings where a sufficiently
188 // smart compiler will simplify strlen.
190 return this->operator<<(StringRef(Str));
193 raw_ostream &operator<<(const std::string &Str) {
194 // Avoid the fast path, it would only increase code size for a marginal win.
195 return write(Str.data(), Str.length());
198 raw_ostream &operator<<(const llvm::SmallVectorImpl<char> &Str) {
199 return write(Str.data(), Str.size());
202 raw_ostream &operator<<(unsigned long N);
203 raw_ostream &operator<<(long N);
204 raw_ostream &operator<<(unsigned long long N);
205 raw_ostream &operator<<(long long N);
206 raw_ostream &operator<<(const void *P);
207 raw_ostream &operator<<(unsigned int N) {
208 return this->operator<<(static_cast<unsigned long>(N));
211 raw_ostream &operator<<(int N) {
212 return this->operator<<(static_cast<long>(N));
215 raw_ostream &operator<<(double N);
217 /// IO manipulator, \see Printable.
218 raw_ostream &operator<<(Printable P);
220 /// Output \p N in hexadecimal, without any prefix or padding.
221 raw_ostream &write_hex(unsigned long long N);
223 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
224 /// satisfy std::isprint into an escape sequence.
225 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
227 raw_ostream &write(unsigned char C);
228 raw_ostream &write(const char *Ptr, size_t Size);
230 // Formatted output, see the format() function in Support/Format.h.
231 raw_ostream &operator<<(const format_object_base &Fmt);
233 // Formatted output, see the leftJustify() function in Support/Format.h.
234 raw_ostream &operator<<(const FormattedString &);
236 // Formatted output, see the formatHex() function in Support/Format.h.
237 raw_ostream &operator<<(const FormattedNumber &);
239 /// indent - Insert 'NumSpaces' spaces.
240 raw_ostream &indent(unsigned NumSpaces);
242 /// Changes the foreground color of text that will be output from this point
244 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
245 /// change only the bold attribute, and keep colors untouched
246 /// @param Bold bold/brighter text, default false
247 /// @param BG if true change the background, default: change foreground
248 /// @returns itself so it can be used within << invocations
249 virtual raw_ostream &changeColor(enum Colors Color,
258 /// Resets the colors to terminal defaults. Call this when you are done
259 /// outputting colored text, or before program exit.
260 virtual raw_ostream &resetColor() { return *this; }
262 /// Reverses the foreground and background colors.
263 virtual raw_ostream &reverseColor() { return *this; }
265 /// This function determines if this stream is connected to a "tty" or
266 /// "console" window. That is, the output would be displayed to the user
267 /// rather than being put on a pipe or stored in a file.
268 virtual bool is_displayed() const { return false; }
270 /// This function determines if this stream is displayed and supports colors.
271 virtual bool has_colors() const { return is_displayed(); }
273 //===--------------------------------------------------------------------===//
274 // Subclass Interface
275 //===--------------------------------------------------------------------===//
278 /// The is the piece of the class that is implemented by subclasses. This
279 /// writes the \p Size bytes starting at
280 /// \p Ptr to the underlying stream.
282 /// This function is guaranteed to only be called at a point at which it is
283 /// safe for the subclass to install a new buffer via SetBuffer.
285 /// \param Ptr The start of the data to be written. For buffered streams this
286 /// is guaranteed to be the start of the buffer.
288 /// \param Size The number of bytes to be written.
290 /// \invariant { Size > 0 }
291 virtual void write_impl(const char *Ptr, size_t Size) = 0;
293 // An out of line virtual method to provide a home for the class vtable.
294 virtual void handle();
296 /// Return the current position within the stream, not counting the bytes
297 /// currently in the buffer.
298 virtual uint64_t current_pos() const = 0;
301 /// Use the provided buffer as the raw_ostream buffer. This is intended for
302 /// use only by subclasses which can arrange for the output to go directly
303 /// into the desired output buffer, instead of being copied on each flush.
304 void SetBuffer(char *BufferStart, size_t Size) {
305 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
308 /// Return an efficient buffer size for the underlying output mechanism.
309 virtual size_t preferred_buffer_size() const;
311 /// Return the beginning of the current stream buffer, or 0 if the stream is
313 const char *getBufferStart() const { return OutBufStart; }
315 //===--------------------------------------------------------------------===//
317 //===--------------------------------------------------------------------===//
319 /// Install the given buffer and mode.
320 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
322 /// Flush the current buffer, which is known to be non-empty. This outputs the
323 /// currently buffered data and resets the buffer to empty.
324 void flush_nonempty();
326 /// Copy data into the buffer. Size must not be greater than the number of
327 /// unused bytes in the buffer.
328 void copy_to_buffer(const char *Ptr, size_t Size);
331 /// An abstract base class for streams implementations that also support a
332 /// pwrite operation. This is useful for code that can mostly stream out data,
333 /// but needs to patch in a header that needs to know the output size.
334 class raw_pwrite_stream : public raw_ostream {
335 virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
338 explicit raw_pwrite_stream(bool Unbuffered = false)
339 : raw_ostream(Unbuffered) {}
340 void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
342 uint64_t Pos = tell();
343 // /dev/null always reports a pos of 0, so we cannot perform this check
346 assert(Size + Offset <= Pos && "We don't support extending the stream");
348 pwrite_impl(Ptr, Size, Offset);
352 //===----------------------------------------------------------------------===//
353 // File Output Streams
354 //===----------------------------------------------------------------------===//
356 /// A raw_ostream that writes to a file descriptor.
358 class raw_fd_ostream : public raw_pwrite_stream {
362 /// Error This flag is true if an error of any kind has been detected.
366 /// Controls whether the stream should attempt to use atomic writes, when
368 bool UseAtomicWrites;
372 bool SupportsSeeking;
374 /// See raw_ostream::write_impl.
375 void write_impl(const char *Ptr, size_t Size) override;
377 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
379 /// Return the current position within the stream, not counting the bytes
380 /// currently in the buffer.
381 uint64_t current_pos() const override { return pos; }
383 /// Determine an efficient buffer size.
384 size_t preferred_buffer_size() const override;
386 /// Set the flag indicating that an output error has been encountered.
387 void error_detected() { Error = true; }
390 /// Open the specified file for writing. If an error occurs, information
391 /// about the error is put into EC, and the stream should be immediately
393 /// \p Flags allows optional flags to control how the file will be opened.
395 /// As a special case, if Filename is "-", then the stream will use
396 /// STDOUT_FILENO instead of opening a file. Note that it will still consider
397 /// itself to own the file descriptor. In particular, it will close the
398 /// file descriptor when it is done (this is necessary to detect
400 raw_fd_ostream(StringRef Filename, std::error_code &EC,
401 sys::fs::OpenFlags Flags);
403 /// FD is the file descriptor that this writes to. If ShouldClose is true,
404 /// this closes the file when the stream is destroyed.
405 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
407 ~raw_fd_ostream() override;
409 /// Manually flush the stream and close the file. Note that this does not call
413 bool supportsSeeking() { return SupportsSeeking; }
415 /// Flushes the stream and repositions the underlying file descriptor position
416 /// to the offset specified from the beginning of the file.
417 uint64_t seek(uint64_t off);
419 /// Set the stream to attempt to use atomic writes for individual output
420 /// routines where possible.
422 /// Note that because raw_ostream's are typically buffered, this flag is only
423 /// sensible when used on unbuffered streams which will flush their output
425 void SetUseAtomicWrites(bool Value) {
426 UseAtomicWrites = Value;
429 raw_ostream &changeColor(enum Colors colors, bool bold=false,
430 bool bg=false) override;
431 raw_ostream &resetColor() override;
433 raw_ostream &reverseColor() override;
435 bool is_displayed() const override;
437 bool has_colors() const override;
439 /// Return the value of the flag in this raw_fd_ostream indicating whether an
440 /// output error has been encountered.
441 /// This doesn't implicitly flush any pending output. Also, it doesn't
442 /// guarantee to detect all errors unless the stream has been closed.
443 bool has_error() const {
447 /// Set the flag read by has_error() to false. If the error flag is set at the
448 /// time when this raw_ostream's destructor is called, report_fatal_error is
449 /// called to report the error. Use clear_error() after handling the error to
450 /// avoid this behavior.
452 /// "Errors should never pass silently.
453 /// Unless explicitly silenced."
454 /// - from The Zen of Python, by Tim Peters
461 /// This returns a reference to a raw_ostream for standard output. Use it like:
462 /// outs() << "foo" << "bar";
465 /// This returns a reference to a raw_ostream for standard error. Use it like:
466 /// errs() << "foo" << "bar";
469 /// This returns a reference to a raw_ostream which simply discards output.
470 raw_ostream &nulls();
472 //===----------------------------------------------------------------------===//
473 // Output Stream Adaptors
474 //===----------------------------------------------------------------------===//
476 /// A raw_ostream that writes to an std::string. This is a simple adaptor
477 /// class. This class does not encounter output errors.
478 class raw_string_ostream : public raw_ostream {
481 /// See raw_ostream::write_impl.
482 void write_impl(const char *Ptr, size_t Size) override;
484 /// Return the current position within the stream, not counting the bytes
485 /// currently in the buffer.
486 uint64_t current_pos() const override { return OS.size(); }
489 explicit raw_string_ostream(std::string &O) : OS(O) {}
490 ~raw_string_ostream() override;
492 /// Flushes the stream contents to the target string and returns the string's
500 /// A raw_ostream that writes to an SmallVector or SmallString. This is a
501 /// simple adaptor class. This class does not encounter output errors.
502 /// raw_svector_ostream operates without a buffer, delegating all memory
503 /// management to the SmallString. Thus the SmallString is always up-to-date,
504 /// may be used directly and there is no need to call flush().
505 class raw_svector_ostream : public raw_pwrite_stream {
506 SmallVectorImpl<char> &OS;
508 /// See raw_ostream::write_impl.
509 void write_impl(const char *Ptr, size_t Size) override;
511 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
513 /// Return the current position within the stream.
514 uint64_t current_pos() const override;
517 /// Construct a new raw_svector_ostream.
519 /// \param O The vector to write to; this should generally have at least 128
520 /// bytes free to avoid any extraneous memory overhead.
521 explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
524 ~raw_svector_ostream() override {}
526 void flush() = delete;
528 /// Return a StringRef for the vector contents.
529 StringRef str() { return StringRef(OS.data(), OS.size()); }
532 /// A raw_ostream that discards all output.
533 class raw_null_ostream : public raw_pwrite_stream {
534 /// See raw_ostream::write_impl.
535 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, not counting the bytes
539 /// currently in the buffer.
540 uint64_t current_pos() const override;
543 explicit raw_null_ostream() {}
544 ~raw_null_ostream() override;
547 class buffer_ostream : public raw_svector_ostream {
549 SmallVector<char, 0> Buffer;
552 buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {}
553 ~buffer_ostream() override { OS << str(); }
556 } // end llvm namespace
558 #endif // LLVM_SUPPORT_RAW_OSTREAM_H