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/Casting.h"
20 #include "llvm/Support/DataTypes.h"
21 #include <system_error>
24 class format_object_base;
25 class FormattedString;
26 class FormattedNumber;
27 template <typename T> class SmallVectorImpl;
31 enum OpenFlags : unsigned;
35 /// This class implements an extremely fast bulk output stream that can *only*
36 /// output to a stream. It does not support seeking, reopening, rewinding, line
37 /// buffered disciplines etc. It is a simple buffer that outputs
38 /// a chunk at a time.
41 void operator=(const raw_ostream &) = delete;
42 raw_ostream(const raw_ostream &) = delete;
44 /// The buffer is handled in such a way that the buffer is
45 /// uninitialized, unbuffered, or out of space when OutBufCur >=
46 /// OutBufEnd. Thus a single comparison suffices to determine if we
47 /// need to take the slow path to write a single character.
49 /// The buffer is in one of three states:
50 /// 1. Unbuffered (BufferMode == Unbuffered)
51 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
52 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
53 /// OutBufEnd - OutBufStart >= 1).
55 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
56 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
57 /// managed by the subclass.
59 /// If a subclass installs an external buffer using SetBuffer then it can wait
60 /// for a \see write_impl() call to handle the data which has been put into
62 char *OutBufStart, *OutBufEnd, *OutBufCur;
82 // color order matches ANSI escape sequence, don't change
95 explicit raw_ostream(StreamKind Kind, bool unbuffered = false)
96 : BufferMode(unbuffered ? Unbuffered : InternalBuffer), Kind(Kind) {
97 // Start out ready to flush.
98 OutBufStart = OutBufEnd = OutBufCur = nullptr;
101 virtual ~raw_ostream();
103 /// tell - Return the current offset with the file.
104 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
106 //===--------------------------------------------------------------------===//
107 // Configuration Interface
108 //===--------------------------------------------------------------------===//
110 /// Set the stream to be buffered, with an automatically determined buffer
114 /// Set the stream to be buffered, using the specified buffer size.
115 void SetBufferSize(size_t Size) {
117 SetBufferAndMode(new char[Size], Size, InternalBuffer);
120 size_t GetBufferSize() const {
121 // If we're supposed to be buffered but haven't actually gotten around
122 // to allocating the buffer yet, return the value that would be used.
123 if (BufferMode != Unbuffered && OutBufStart == nullptr)
124 return preferred_buffer_size();
126 // Otherwise just return the size of the allocated buffer.
127 return OutBufEnd - OutBufStart;
130 /// Set the stream to be unbuffered. When unbuffered, the stream will flush
131 /// after every write. This routine will also flush the buffer immediately
132 /// when the stream is being set to unbuffered.
133 void SetUnbuffered() {
135 SetBufferAndMode(nullptr, 0, Unbuffered);
138 size_t GetNumBytesInBuffer() const {
139 return OutBufCur - OutBufStart;
142 //===--------------------------------------------------------------------===//
143 // Data Output Interface
144 //===--------------------------------------------------------------------===//
147 if (OutBufCur != OutBufStart)
151 raw_ostream &operator<<(char C) {
152 if (OutBufCur >= OutBufEnd)
158 raw_ostream &operator<<(unsigned char C) {
159 if (OutBufCur >= OutBufEnd)
165 raw_ostream &operator<<(signed char C) {
166 if (OutBufCur >= OutBufEnd)
172 raw_ostream &operator<<(StringRef Str) {
173 // Inline fast path, particularly for strings with a known length.
174 size_t Size = Str.size();
176 // Make sure we can use the fast path.
177 if (Size > (size_t)(OutBufEnd - OutBufCur))
178 return write(Str.data(), Size);
180 memcpy(OutBufCur, Str.data(), Size);
185 raw_ostream &operator<<(const char *Str) {
186 // Inline fast path, particularly for constant strings where a sufficiently
187 // smart compiler will simplify strlen.
189 return this->operator<<(StringRef(Str));
192 raw_ostream &operator<<(const std::string &Str) {
193 // Avoid the fast path, it would only increase code size for a marginal win.
194 return write(Str.data(), Str.length());
197 raw_ostream &operator<<(const llvm::SmallVectorImpl<char> &Str) {
198 return write(Str.data(), Str.size());
201 raw_ostream &operator<<(unsigned long N);
202 raw_ostream &operator<<(long N);
203 raw_ostream &operator<<(unsigned long long N);
204 raw_ostream &operator<<(long long N);
205 raw_ostream &operator<<(const void *P);
206 raw_ostream &operator<<(unsigned int N) {
207 return this->operator<<(static_cast<unsigned long>(N));
210 raw_ostream &operator<<(int N) {
211 return this->operator<<(static_cast<long>(N));
214 raw_ostream &operator<<(double N);
216 /// Output \p N in hexadecimal, without any prefix or padding.
217 raw_ostream &write_hex(unsigned long long N);
219 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
220 /// satisfy std::isprint into an escape sequence.
221 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
223 raw_ostream &write(unsigned char C);
224 raw_ostream &write(const char *Ptr, size_t Size);
226 // Formatted output, see the format() function in Support/Format.h.
227 raw_ostream &operator<<(const format_object_base &Fmt);
229 // Formatted output, see the leftJustify() function in Support/Format.h.
230 raw_ostream &operator<<(const FormattedString &);
232 // Formatted output, see the formatHex() function in Support/Format.h.
233 raw_ostream &operator<<(const FormattedNumber &);
235 /// indent - Insert 'NumSpaces' spaces.
236 raw_ostream &indent(unsigned NumSpaces);
239 /// Changes the foreground color of text that will be output from this point
241 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
242 /// change only the bold attribute, and keep colors untouched
243 /// @param Bold bold/brighter text, default false
244 /// @param BG if true change the background, default: change foreground
245 /// @returns itself so it can be used within << invocations
246 virtual raw_ostream &changeColor(enum Colors Color,
255 /// Resets the colors to terminal defaults. Call this when you are done
256 /// outputting colored text, or before program exit.
257 virtual raw_ostream &resetColor() { return *this; }
259 /// Reverses the forground and background colors.
260 virtual raw_ostream &reverseColor() { return *this; }
262 /// This function determines if this stream is connected to a "tty" or
263 /// "console" window. That is, the output would be displayed to the user
264 /// rather than being put on a pipe or stored in a file.
265 virtual bool is_displayed() const { return false; }
267 /// This function determines if this stream is displayed and supports colors.
268 virtual bool has_colors() const { return is_displayed(); }
270 //===--------------------------------------------------------------------===//
271 // Subclass Interface
272 //===--------------------------------------------------------------------===//
274 StreamKind getKind() const { return Kind; }
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 //===----------------------------------------------------------------------===//
332 // File Output Streams
333 //===----------------------------------------------------------------------===//
335 /// A raw_ostream that writes to a file descriptor.
337 class raw_fd_ostream : public raw_ostream {
341 /// Error This flag is true if an error of any kind has been detected.
345 /// Controls whether the stream should attempt to use atomic writes, when
347 bool UseAtomicWrites;
351 /// See raw_ostream::write_impl.
352 void write_impl(const char *Ptr, size_t Size) override;
354 /// Return the current position within the stream, not counting the bytes
355 /// currently in the buffer.
356 uint64_t current_pos() const override { return pos; }
358 /// Determine an efficient buffer size.
359 size_t preferred_buffer_size() const override;
361 /// Set the flag indicating that an output error has been encountered.
362 void error_detected() { Error = true; }
365 /// Open the specified file for writing. If an error occurs, information
366 /// about the error is put into EC, and the stream should be immediately
368 /// \p Flags allows optional flags to control how the file will be opened.
370 /// As a special case, if Filename is "-", then the stream will use
371 /// STDOUT_FILENO instead of opening a file. Note that it will still consider
372 /// itself to own the file descriptor. In particular, it will close the
373 /// file descriptor when it is done (this is necessary to detect
375 raw_fd_ostream(StringRef Filename, std::error_code &EC,
376 sys::fs::OpenFlags Flags);
378 /// FD is the file descriptor that this writes to. If ShouldClose is true,
379 /// this closes the file when the stream is destroyed.
380 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
382 static bool classof(const raw_ostream *OS) { return OS->getKind() == SK_FD; }
386 /// Manually flush the stream and close the file. Note that this does not call
390 /// Flushes the stream and repositions the underlying file descriptor position
391 /// to the offset specified from the beginning of the file.
392 uint64_t seek(uint64_t off);
394 /// Set the stream to attempt to use atomic writes for individual output
395 /// routines where possible.
397 /// Note that because raw_ostream's are typically buffered, this flag is only
398 /// sensible when used on unbuffered streams which will flush their output
400 void SetUseAtomicWrites(bool Value) {
401 UseAtomicWrites = Value;
404 raw_ostream &changeColor(enum Colors colors, bool bold=false,
405 bool bg=false) override;
406 raw_ostream &resetColor() override;
408 raw_ostream &reverseColor() override;
410 bool is_displayed() const override;
412 bool has_colors() const override;
414 /// Return the value of the flag in this raw_fd_ostream indicating whether an
415 /// output error has been encountered.
416 /// This doesn't implicitly flush any pending output. Also, it doesn't
417 /// guarantee to detect all errors unless the stream has been closed.
418 bool has_error() const {
422 /// Set the flag read by has_error() to false. If the error flag is set at the
423 /// time when this raw_ostream's destructor is called, report_fatal_error is
424 /// called to report the error. Use clear_error() after handling the error to
425 /// avoid this behavior.
427 /// "Errors should never pass silently.
428 /// Unless explicitly silenced."
429 /// - from The Zen of Python, by Tim Peters
436 /// This returns a reference to a raw_ostream for standard output. Use it like:
437 /// outs() << "foo" << "bar";
440 /// This returns a reference to a raw_ostream for standard error. Use it like:
441 /// errs() << "foo" << "bar";
444 /// This returns a reference to a raw_ostream which simply discards output.
445 raw_ostream &nulls();
447 //===----------------------------------------------------------------------===//
448 // Output Stream Adaptors
449 //===----------------------------------------------------------------------===//
451 /// A raw_ostream that writes to an std::string. This is a simple adaptor
452 /// class. This class does not encounter output errors.
453 class raw_string_ostream : public raw_ostream {
456 /// See raw_ostream::write_impl.
457 void write_impl(const char *Ptr, size_t Size) override;
459 /// Return the current position within the stream, not counting the bytes
460 /// currently in the buffer.
461 uint64_t current_pos() const override { return OS.size(); }
463 explicit raw_string_ostream(std::string &O) : raw_ostream(SK_STRING), OS(O) {}
464 ~raw_string_ostream();
466 static bool classof(const raw_ostream *OS) {
467 return OS->getKind() == SK_STRING;
470 /// Flushes the stream contents to the target string and returns the string's
478 /// A raw_ostream that writes to an SmallVector or SmallString. This is a
479 /// simple adaptor class. This class does not encounter output errors.
480 class raw_svector_ostream : public raw_ostream {
481 SmallVectorImpl<char> &OS;
483 /// See raw_ostream::write_impl.
484 void write_impl(const char *Ptr, size_t Size) override;
486 /// Return the current position within the stream, not counting the bytes
487 /// currently in the buffer.
488 uint64_t current_pos() const override;
490 /// Construct a new raw_svector_ostream.
492 /// \param O The vector to write to; this should generally have at least 128
493 /// bytes free to avoid any extraneous memory overhead.
494 explicit raw_svector_ostream(SmallVectorImpl<char> &O);
495 ~raw_svector_ostream();
497 static bool classof(const raw_ostream *OS) {
498 return OS->getKind() == SK_SVECTOR;
501 /// This is called when the SmallVector we're appending to is changed outside
502 /// of the raw_svector_ostream's control. It is only safe to do this if the
503 /// raw_svector_ostream has previously been flushed.
506 /// Flushes the stream contents to the target vector and return a StringRef
507 /// for the vector contents.
511 /// A raw_ostream that discards all output.
512 class raw_null_ostream : public raw_ostream {
513 /// See raw_ostream::write_impl.
514 void write_impl(const char *Ptr, size_t size) override;
516 /// Return the current position within the stream, not counting the bytes
517 /// currently in the buffer.
518 uint64_t current_pos() const override;
521 explicit raw_null_ostream() : raw_ostream(SK_NULL) {}
523 static bool classof(const raw_ostream *OS) {
524 return OS->getKind() == SK_NULL;
528 } // end llvm namespace