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"
20 #include <system_error>
23 class formatv_object_base;
24 class format_object_base;
25 class FormattedString;
26 class FormattedNumber;
28 template <typename T> class SmallVectorImpl;
32 enum OpenFlags : unsigned;
36 /// This class implements an extremely fast bulk output stream that can *only*
37 /// output to a stream. It does not support seeking, reopening, rewinding, line
38 /// buffered disciplines etc. It is a simple buffer that outputs
39 /// a chunk at a time.
42 void operator=(const raw_ostream &) = delete;
43 raw_ostream(const raw_ostream &) = delete;
45 /// The buffer is handled in such a way that the buffer is
46 /// uninitialized, unbuffered, or out of space when OutBufCur >=
47 /// OutBufEnd. Thus a single comparison suffices to determine if we
48 /// need to take the slow path to write a single character.
50 /// The buffer is in one of three states:
51 /// 1. Unbuffered (BufferMode == Unbuffered)
52 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
53 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
54 /// OutBufEnd - OutBufStart >= 1).
56 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
57 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
58 /// managed by the subclass.
60 /// If a subclass installs an external buffer using SetBuffer then it can wait
61 /// for a \see write_impl() call to handle the data which has been put into
63 char *OutBufStart, *OutBufEnd, *OutBufCur;
72 // color order matches ANSI escape sequence, don't change
85 explicit raw_ostream(bool unbuffered = false)
86 : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
87 // Start out ready to flush.
88 OutBufStart = OutBufEnd = OutBufCur = nullptr;
91 virtual ~raw_ostream();
93 /// tell - Return the current offset with the file.
94 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
96 //===--------------------------------------------------------------------===//
97 // Configuration Interface
98 //===--------------------------------------------------------------------===//
100 /// Set the stream to be buffered, with an automatically determined buffer
104 /// Set the stream to be buffered, using the specified buffer size.
105 void SetBufferSize(size_t Size) {
107 SetBufferAndMode(new char[Size], Size, InternalBuffer);
110 size_t GetBufferSize() const {
111 // If we're supposed to be buffered but haven't actually gotten around
112 // to allocating the buffer yet, return the value that would be used.
113 if (BufferMode != Unbuffered && OutBufStart == nullptr)
114 return preferred_buffer_size();
116 // Otherwise just return the size of the allocated buffer.
117 return OutBufEnd - OutBufStart;
120 /// Set the stream to be unbuffered. When unbuffered, the stream will flush
121 /// after every write. This routine will also flush the buffer immediately
122 /// when the stream is being set to unbuffered.
123 void SetUnbuffered() {
125 SetBufferAndMode(nullptr, 0, Unbuffered);
128 size_t GetNumBytesInBuffer() const {
129 return OutBufCur - OutBufStart;
132 //===--------------------------------------------------------------------===//
133 // Data Output Interface
134 //===--------------------------------------------------------------------===//
137 if (OutBufCur != OutBufStart)
141 raw_ostream &operator<<(char C) {
142 if (OutBufCur >= OutBufEnd)
148 raw_ostream &operator<<(unsigned char C) {
149 if (OutBufCur >= OutBufEnd)
155 raw_ostream &operator<<(signed char C) {
156 if (OutBufCur >= OutBufEnd)
162 raw_ostream &operator<<(StringRef Str) {
163 // Inline fast path, particularly for strings with a known length.
164 size_t Size = Str.size();
166 // Make sure we can use the fast path.
167 if (Size > (size_t)(OutBufEnd - OutBufCur))
168 return write(Str.data(), Size);
171 memcpy(OutBufCur, Str.data(), Size);
177 raw_ostream &operator<<(const char *Str) {
178 // Inline fast path, particularly for constant strings where a sufficiently
179 // smart compiler will simplify strlen.
181 return this->operator<<(StringRef(Str));
184 raw_ostream &operator<<(const std::string &Str) {
185 // Avoid the fast path, it would only increase code size for a marginal win.
186 return write(Str.data(), Str.length());
189 raw_ostream &operator<<(const llvm::SmallVectorImpl<char> &Str) {
190 return write(Str.data(), Str.size());
193 raw_ostream &operator<<(unsigned long N);
194 raw_ostream &operator<<(long N);
195 raw_ostream &operator<<(unsigned long long N);
196 raw_ostream &operator<<(long long N);
197 raw_ostream &operator<<(const void *P);
198 raw_ostream &operator<<(unsigned int N) {
199 return this->operator<<(static_cast<unsigned long>(N));
202 raw_ostream &operator<<(int N) {
203 return this->operator<<(static_cast<long>(N));
206 raw_ostream &operator<<(double N);
208 /// Output \p N in hexadecimal, without any prefix or padding.
209 raw_ostream &write_hex(unsigned long long N);
211 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
212 /// satisfy std::isprint into an escape sequence.
213 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
215 raw_ostream &write(unsigned char C);
216 raw_ostream &write(const char *Ptr, size_t Size);
218 // Formatted output, see the format() function in Support/Format.h.
219 raw_ostream &operator<<(const format_object_base &Fmt);
221 // Formatted output, see the leftJustify() function in Support/Format.h.
222 raw_ostream &operator<<(const FormattedString &);
224 // Formatted output, see the formatHex() function in Support/Format.h.
225 raw_ostream &operator<<(const FormattedNumber &);
227 // Formatted output, see the formatv() function in Support/FormatVariadic.h.
228 raw_ostream &operator<<(const formatv_object_base &);
230 // Formatted output, see the format_bytes() function in Support/Format.h.
231 raw_ostream &operator<<(const FormattedBytes &);
233 /// indent - Insert 'NumSpaces' spaces.
234 raw_ostream &indent(unsigned NumSpaces);
236 /// Changes the foreground color of text that will be output from this point
238 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
239 /// change only the bold attribute, and keep colors untouched
240 /// @param Bold bold/brighter text, default false
241 /// @param BG if true change the background, default: change foreground
242 /// @returns itself so it can be used within << invocations
243 virtual raw_ostream &changeColor(enum Colors Color,
252 /// Resets the colors to terminal defaults. Call this when you are done
253 /// outputting colored text, or before program exit.
254 virtual raw_ostream &resetColor() { return *this; }
256 /// Reverses the foreground and background colors.
257 virtual raw_ostream &reverseColor() { return *this; }
259 /// This function determines if this stream is connected to a "tty" or
260 /// "console" window. That is, the output would be displayed to the user
261 /// rather than being put on a pipe or stored in a file.
262 virtual bool is_displayed() const { return false; }
264 /// This function determines if this stream is displayed and supports colors.
265 virtual bool has_colors() const { return is_displayed(); }
267 //===--------------------------------------------------------------------===//
268 // Subclass Interface
269 //===--------------------------------------------------------------------===//
272 /// The is the piece of the class that is implemented by subclasses. This
273 /// writes the \p Size bytes starting at
274 /// \p Ptr to the underlying stream.
276 /// This function is guaranteed to only be called at a point at which it is
277 /// safe for the subclass to install a new buffer via SetBuffer.
279 /// \param Ptr The start of the data to be written. For buffered streams this
280 /// is guaranteed to be the start of the buffer.
282 /// \param Size The number of bytes to be written.
284 /// \invariant { Size > 0 }
285 virtual void write_impl(const char *Ptr, size_t Size) = 0;
287 // An out of line virtual method to provide a home for the class vtable.
288 virtual void handle();
290 /// Return the current position within the stream, not counting the bytes
291 /// currently in the buffer.
292 virtual uint64_t current_pos() const = 0;
295 /// Use the provided buffer as the raw_ostream buffer. This is intended for
296 /// use only by subclasses which can arrange for the output to go directly
297 /// into the desired output buffer, instead of being copied on each flush.
298 void SetBuffer(char *BufferStart, size_t Size) {
299 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
302 /// Return an efficient buffer size for the underlying output mechanism.
303 virtual size_t preferred_buffer_size() const;
305 /// Return the beginning of the current stream buffer, or 0 if the stream is
307 const char *getBufferStart() const { return OutBufStart; }
309 //===--------------------------------------------------------------------===//
311 //===--------------------------------------------------------------------===//
313 /// Install the given buffer and mode.
314 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
316 /// Flush the current buffer, which is known to be non-empty. This outputs the
317 /// currently buffered data and resets the buffer to empty.
318 void flush_nonempty();
320 /// Copy data into the buffer. Size must not be greater than the number of
321 /// unused bytes in the buffer.
322 void copy_to_buffer(const char *Ptr, size_t Size);
325 /// An abstract base class for streams implementations that also support a
326 /// pwrite operation. This is useful for code that can mostly stream out data,
327 /// but needs to patch in a header that needs to know the output size.
328 class raw_pwrite_stream : public raw_ostream {
329 virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
332 explicit raw_pwrite_stream(bool Unbuffered = false)
333 : raw_ostream(Unbuffered) {}
334 void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
336 uint64_t Pos = tell();
337 // /dev/null always reports a pos of 0, so we cannot perform this check
340 assert(Size + Offset <= Pos && "We don't support extending the stream");
342 pwrite_impl(Ptr, Size, Offset);
346 //===----------------------------------------------------------------------===//
347 // File Output Streams
348 //===----------------------------------------------------------------------===//
350 /// A raw_ostream that writes to a file descriptor.
352 class raw_fd_ostream : public raw_pwrite_stream {
356 /// Error This flag is true if an error of any kind has been detected.
362 bool SupportsSeeking;
364 /// See raw_ostream::write_impl.
365 void write_impl(const char *Ptr, size_t Size) override;
367 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
369 /// Return the current position within the stream, not counting the bytes
370 /// currently in the buffer.
371 uint64_t current_pos() const override { return pos; }
373 /// Determine an efficient buffer size.
374 size_t preferred_buffer_size() const override;
376 /// Set the flag indicating that an output error has been encountered.
377 void error_detected() { Error = true; }
380 /// Open the specified file for writing. If an error occurs, information
381 /// about the error is put into EC, and the stream should be immediately
383 /// \p Flags allows optional flags to control how the file will be opened.
385 /// As a special case, if Filename is "-", then the stream will use
386 /// STDOUT_FILENO instead of opening a file. Note that it will still consider
387 /// itself to own the file descriptor. In particular, it will close the
388 /// file descriptor when it is done (this is necessary to detect
390 raw_fd_ostream(StringRef Filename, std::error_code &EC,
391 sys::fs::OpenFlags Flags);
393 /// FD is the file descriptor that this writes to. If ShouldClose is true,
394 /// this closes the file when the stream is destroyed.
395 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
397 ~raw_fd_ostream() override;
399 /// Manually flush the stream and close the file. Note that this does not call
403 bool supportsSeeking() { return SupportsSeeking; }
405 /// Flushes the stream and repositions the underlying file descriptor position
406 /// to the offset specified from the beginning of the file.
407 uint64_t seek(uint64_t off);
409 raw_ostream &changeColor(enum Colors colors, bool bold=false,
410 bool bg=false) override;
411 raw_ostream &resetColor() override;
413 raw_ostream &reverseColor() override;
415 bool is_displayed() const override;
417 bool has_colors() const override;
419 /// Return the value of the flag in this raw_fd_ostream indicating whether an
420 /// output error has been encountered.
421 /// This doesn't implicitly flush any pending output. Also, it doesn't
422 /// guarantee to detect all errors unless the stream has been closed.
423 bool has_error() const {
427 /// Set the flag read by has_error() to false. If the error flag is set at the
428 /// time when this raw_ostream's destructor is called, report_fatal_error is
429 /// called to report the error. Use clear_error() after handling the error to
430 /// avoid this behavior.
432 /// "Errors should never pass silently.
433 /// Unless explicitly silenced."
434 /// - from The Zen of Python, by Tim Peters
441 /// This returns a reference to a raw_ostream for standard output. Use it like:
442 /// outs() << "foo" << "bar";
445 /// This returns a reference to a raw_ostream for standard error. Use it like:
446 /// errs() << "foo" << "bar";
449 /// This returns a reference to a raw_ostream which simply discards output.
450 raw_ostream &nulls();
452 //===----------------------------------------------------------------------===//
453 // Output Stream Adaptors
454 //===----------------------------------------------------------------------===//
456 /// A raw_ostream that writes to an std::string. This is a simple adaptor
457 /// class. This class does not encounter output errors.
458 class raw_string_ostream : public raw_ostream {
461 /// See raw_ostream::write_impl.
462 void write_impl(const char *Ptr, size_t Size) override;
464 /// Return the current position within the stream, not counting the bytes
465 /// currently in the buffer.
466 uint64_t current_pos() const override { return OS.size(); }
469 explicit raw_string_ostream(std::string &O) : OS(O) {}
470 ~raw_string_ostream() override;
472 /// Flushes the stream contents to the target string and returns the string's
480 /// A raw_ostream that writes to an SmallVector or SmallString. This is a
481 /// simple adaptor class. This class does not encounter output errors.
482 /// raw_svector_ostream operates without a buffer, delegating all memory
483 /// management to the SmallString. Thus the SmallString is always up-to-date,
484 /// may be used directly and there is no need to call flush().
485 class raw_svector_ostream : public raw_pwrite_stream {
486 SmallVectorImpl<char> &OS;
488 /// See raw_ostream::write_impl.
489 void write_impl(const char *Ptr, size_t Size) override;
491 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
493 /// Return the current position within the stream.
494 uint64_t current_pos() const override;
497 /// Construct a new raw_svector_ostream.
499 /// \param O The vector to write to; this should generally have at least 128
500 /// bytes free to avoid any extraneous memory overhead.
501 explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
504 ~raw_svector_ostream() override {}
506 void flush() = delete;
508 /// Return a StringRef for the vector contents.
509 StringRef str() { return StringRef(OS.data(), OS.size()); }
512 /// A raw_ostream that discards all output.
513 class raw_null_ostream : public raw_pwrite_stream {
514 /// See raw_ostream::write_impl.
515 void write_impl(const char *Ptr, size_t size) override;
516 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
518 /// Return the current position within the stream, not counting the bytes
519 /// currently in the buffer.
520 uint64_t current_pos() const override;
523 explicit raw_null_ostream() {}
524 ~raw_null_ostream() override;
527 class buffer_ostream : public raw_svector_ostream {
529 SmallVector<char, 0> Buffer;
532 buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {}
533 ~buffer_ostream() override { OS << str(); }
536 } // end llvm namespace
538 #endif // LLVM_SUPPORT_RAW_OSTREAM_H