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 format_object_base;
24 class FormattedString;
25 class FormattedNumber;
26 template <typename T> class SmallVectorImpl;
30 enum OpenFlags : unsigned;
34 /// This class implements an extremely fast bulk output stream that can *only*
35 /// output to a stream. It does not support seeking, reopening, rewinding, line
36 /// buffered disciplines etc. It is a simple buffer that outputs
37 /// a chunk at a time.
40 void operator=(const raw_ostream &) = delete;
41 raw_ostream(const raw_ostream &) = delete;
43 /// The buffer is handled in such a way that the buffer is
44 /// uninitialized, unbuffered, or out of space when OutBufCur >=
45 /// OutBufEnd. Thus a single comparison suffices to determine if we
46 /// need to take the slow path to write a single character.
48 /// The buffer is in one of three states:
49 /// 1. Unbuffered (BufferMode == Unbuffered)
50 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
51 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
52 /// OutBufEnd - OutBufStart >= 1).
54 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
55 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
56 /// managed by the subclass.
58 /// If a subclass installs an external buffer using SetBuffer then it can wait
59 /// for a \see write_impl() call to handle the data which has been put into
61 char *OutBufStart, *OutBufEnd, *OutBufCur;
70 // color order matches ANSI escape sequence, don't change
83 explicit raw_ostream(bool unbuffered = false)
84 : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
85 // Start out ready to flush.
86 OutBufStart = OutBufEnd = OutBufCur = nullptr;
89 virtual ~raw_ostream();
91 /// tell - Return the current offset with the file.
92 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
94 //===--------------------------------------------------------------------===//
95 // Configuration Interface
96 //===--------------------------------------------------------------------===//
98 /// Set the stream to be buffered, with an automatically determined buffer
102 /// Set the stream to be buffered, using the specified buffer size.
103 void SetBufferSize(size_t Size) {
105 SetBufferAndMode(new char[Size], Size, InternalBuffer);
108 size_t GetBufferSize() const {
109 // If we're supposed to be buffered but haven't actually gotten around
110 // to allocating the buffer yet, return the value that would be used.
111 if (BufferMode != Unbuffered && OutBufStart == nullptr)
112 return preferred_buffer_size();
114 // Otherwise just return the size of the allocated buffer.
115 return OutBufEnd - OutBufStart;
118 /// Set the stream to be unbuffered. When unbuffered, the stream will flush
119 /// after every write. This routine will also flush the buffer immediately
120 /// when the stream is being set to unbuffered.
121 void SetUnbuffered() {
123 SetBufferAndMode(nullptr, 0, Unbuffered);
126 size_t GetNumBytesInBuffer() const {
127 return OutBufCur - OutBufStart;
130 //===--------------------------------------------------------------------===//
131 // Data Output Interface
132 //===--------------------------------------------------------------------===//
135 if (OutBufCur != OutBufStart)
139 raw_ostream &operator<<(char C) {
140 if (OutBufCur >= OutBufEnd)
146 raw_ostream &operator<<(unsigned char C) {
147 if (OutBufCur >= OutBufEnd)
153 raw_ostream &operator<<(signed char C) {
154 if (OutBufCur >= OutBufEnd)
160 raw_ostream &operator<<(StringRef Str) {
161 // Inline fast path, particularly for strings with a known length.
162 size_t Size = Str.size();
164 // Make sure we can use the fast path.
165 if (Size > (size_t)(OutBufEnd - OutBufCur))
166 return write(Str.data(), Size);
169 memcpy(OutBufCur, Str.data(), Size);
175 raw_ostream &operator<<(const char *Str) {
176 // Inline fast path, particularly for constant strings where a sufficiently
177 // smart compiler will simplify strlen.
179 return this->operator<<(StringRef(Str));
182 raw_ostream &operator<<(const std::string &Str) {
183 // Avoid the fast path, it would only increase code size for a marginal win.
184 return write(Str.data(), Str.length());
187 raw_ostream &operator<<(const llvm::SmallVectorImpl<char> &Str) {
188 return write(Str.data(), Str.size());
191 raw_ostream &operator<<(unsigned long N);
192 raw_ostream &operator<<(long N);
193 raw_ostream &operator<<(unsigned long long N);
194 raw_ostream &operator<<(long long N);
195 raw_ostream &operator<<(const void *P);
196 raw_ostream &operator<<(unsigned int N) {
197 return this->operator<<(static_cast<unsigned long>(N));
200 raw_ostream &operator<<(int N) {
201 return this->operator<<(static_cast<long>(N));
204 raw_ostream &operator<<(double N);
206 /// Output \p N in hexadecimal, without any prefix or padding.
207 raw_ostream &write_hex(unsigned long long N);
209 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
210 /// satisfy std::isprint into an escape sequence.
211 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
213 raw_ostream &write(unsigned char C);
214 raw_ostream &write(const char *Ptr, size_t Size);
216 // Formatted output, see the format() function in Support/Format.h.
217 raw_ostream &operator<<(const format_object_base &Fmt);
219 // Formatted output, see the leftJustify() function in Support/Format.h.
220 raw_ostream &operator<<(const FormattedString &);
222 // Formatted output, see the formatHex() function in Support/Format.h.
223 raw_ostream &operator<<(const FormattedNumber &);
225 /// indent - Insert 'NumSpaces' spaces.
226 raw_ostream &indent(unsigned NumSpaces);
228 /// Changes the foreground color of text that will be output from this point
230 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
231 /// change only the bold attribute, and keep colors untouched
232 /// @param Bold bold/brighter text, default false
233 /// @param BG if true change the background, default: change foreground
234 /// @returns itself so it can be used within << invocations
235 virtual raw_ostream &changeColor(enum Colors Color,
244 /// Resets the colors to terminal defaults. Call this when you are done
245 /// outputting colored text, or before program exit.
246 virtual raw_ostream &resetColor() { return *this; }
248 /// Reverses the foreground and background colors.
249 virtual raw_ostream &reverseColor() { return *this; }
251 /// This function determines if this stream is connected to a "tty" or
252 /// "console" window. That is, the output would be displayed to the user
253 /// rather than being put on a pipe or stored in a file.
254 virtual bool is_displayed() const { return false; }
256 /// This function determines if this stream is displayed and supports colors.
257 virtual bool has_colors() const { return is_displayed(); }
259 //===--------------------------------------------------------------------===//
260 // Subclass Interface
261 //===--------------------------------------------------------------------===//
264 /// The is the piece of the class that is implemented by subclasses. This
265 /// writes the \p Size bytes starting at
266 /// \p Ptr to the underlying stream.
268 /// This function is guaranteed to only be called at a point at which it is
269 /// safe for the subclass to install a new buffer via SetBuffer.
271 /// \param Ptr The start of the data to be written. For buffered streams this
272 /// is guaranteed to be the start of the buffer.
274 /// \param Size The number of bytes to be written.
276 /// \invariant { Size > 0 }
277 virtual void write_impl(const char *Ptr, size_t Size) = 0;
279 // An out of line virtual method to provide a home for the class vtable.
280 virtual void handle();
282 /// Return the current position within the stream, not counting the bytes
283 /// currently in the buffer.
284 virtual uint64_t current_pos() const = 0;
287 /// Use the provided buffer as the raw_ostream buffer. This is intended for
288 /// use only by subclasses which can arrange for the output to go directly
289 /// into the desired output buffer, instead of being copied on each flush.
290 void SetBuffer(char *BufferStart, size_t Size) {
291 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
294 /// Return an efficient buffer size for the underlying output mechanism.
295 virtual size_t preferred_buffer_size() const;
297 /// Return the beginning of the current stream buffer, or 0 if the stream is
299 const char *getBufferStart() const { return OutBufStart; }
301 //===--------------------------------------------------------------------===//
303 //===--------------------------------------------------------------------===//
305 /// Install the given buffer and mode.
306 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
308 /// Flush the current buffer, which is known to be non-empty. This outputs the
309 /// currently buffered data and resets the buffer to empty.
310 void flush_nonempty();
312 /// Copy data into the buffer. Size must not be greater than the number of
313 /// unused bytes in the buffer.
314 void copy_to_buffer(const char *Ptr, size_t Size);
317 /// An abstract base class for streams implementations that also support a
318 /// pwrite operation. This is useful for code that can mostly stream out data,
319 /// but needs to patch in a header that needs to know the output size.
320 class raw_pwrite_stream : public raw_ostream {
321 virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
324 explicit raw_pwrite_stream(bool Unbuffered = false)
325 : raw_ostream(Unbuffered) {}
326 void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
328 uint64_t Pos = tell();
329 // /dev/null always reports a pos of 0, so we cannot perform this check
332 assert(Size + Offset <= Pos && "We don't support extending the stream");
334 pwrite_impl(Ptr, Size, Offset);
338 //===----------------------------------------------------------------------===//
339 // File Output Streams
340 //===----------------------------------------------------------------------===//
342 /// A raw_ostream that writes to a file descriptor.
344 class raw_fd_ostream : public raw_pwrite_stream {
348 /// Error This flag is true if an error of any kind has been detected.
352 /// Controls whether the stream should attempt to use atomic writes, when
354 bool UseAtomicWrites;
358 bool SupportsSeeking;
360 /// See raw_ostream::write_impl.
361 void write_impl(const char *Ptr, size_t Size) override;
363 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
365 /// Return the current position within the stream, not counting the bytes
366 /// currently in the buffer.
367 uint64_t current_pos() const override { return pos; }
369 /// Determine an efficient buffer size.
370 size_t preferred_buffer_size() const override;
372 /// Set the flag indicating that an output error has been encountered.
373 void error_detected() { Error = true; }
376 /// Open the specified file for writing. If an error occurs, information
377 /// about the error is put into EC, and the stream should be immediately
379 /// \p Flags allows optional flags to control how the file will be opened.
381 /// As a special case, if Filename is "-", then the stream will use
382 /// STDOUT_FILENO instead of opening a file. Note that it will still consider
383 /// itself to own the file descriptor. In particular, it will close the
384 /// file descriptor when it is done (this is necessary to detect
386 raw_fd_ostream(StringRef Filename, std::error_code &EC,
387 sys::fs::OpenFlags Flags);
389 /// FD is the file descriptor that this writes to. If ShouldClose is true,
390 /// this closes the file when the stream is destroyed.
391 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
393 ~raw_fd_ostream() override;
395 /// Manually flush the stream and close the file. Note that this does not call
399 bool supportsSeeking() { return SupportsSeeking; }
401 /// Flushes the stream and repositions the underlying file descriptor position
402 /// to the offset specified from the beginning of the file.
403 uint64_t seek(uint64_t off);
405 /// Set the stream to attempt to use atomic writes for individual output
406 /// routines where possible.
408 /// Note that because raw_ostream's are typically buffered, this flag is only
409 /// sensible when used on unbuffered streams which will flush their output
411 void SetUseAtomicWrites(bool Value) {
412 UseAtomicWrites = Value;
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 /// Return the value of the flag in this raw_fd_ostream indicating whether an
426 /// output error has been encountered.
427 /// This doesn't implicitly flush any pending output. Also, it doesn't
428 /// guarantee to detect all errors unless the stream has been closed.
429 bool has_error() const {
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
447 /// This returns a reference to a raw_ostream for standard output. Use it like:
448 /// outs() << "foo" << "bar";
451 /// This returns a reference to a raw_ostream for standard error. Use it like:
452 /// errs() << "foo" << "bar";
455 /// This returns a reference to a raw_ostream which simply discards output.
456 raw_ostream &nulls();
458 //===----------------------------------------------------------------------===//
459 // Output Stream Adaptors
460 //===----------------------------------------------------------------------===//
462 /// A raw_ostream that writes to an std::string. This is a simple adaptor
463 /// class. This class does not encounter output errors.
464 class raw_string_ostream : public raw_ostream {
467 /// See raw_ostream::write_impl.
468 void write_impl(const char *Ptr, size_t Size) override;
470 /// Return the current position within the stream, not counting the bytes
471 /// currently in the buffer.
472 uint64_t current_pos() const override { return OS.size(); }
475 explicit raw_string_ostream(std::string &O) : OS(O) {}
476 ~raw_string_ostream() override;
478 /// Flushes the stream contents to the target string and returns the string's
486 /// A raw_ostream that writes to an SmallVector or SmallString. This is a
487 /// simple adaptor class. This class does not encounter output errors.
488 /// raw_svector_ostream operates without a buffer, delegating all memory
489 /// management to the SmallString. Thus the SmallString is always up-to-date,
490 /// may be used directly and there is no need to call flush().
491 class raw_svector_ostream : public raw_pwrite_stream {
492 SmallVectorImpl<char> &OS;
494 /// See raw_ostream::write_impl.
495 void write_impl(const char *Ptr, size_t Size) override;
497 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
499 /// Return the current position within the stream.
500 uint64_t current_pos() const override;
503 /// Construct a new raw_svector_ostream.
505 /// \param O The vector to write to; this should generally have at least 128
506 /// bytes free to avoid any extraneous memory overhead.
507 explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
510 ~raw_svector_ostream() override {}
512 void flush() = delete;
514 /// Return a StringRef for the vector contents.
515 StringRef str() { return StringRef(OS.data(), OS.size()); }
518 /// A raw_ostream that discards all output.
519 class raw_null_ostream : public raw_pwrite_stream {
520 /// See raw_ostream::write_impl.
521 void write_impl(const char *Ptr, size_t size) override;
522 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
524 /// Return the current position within the stream, not counting the bytes
525 /// currently in the buffer.
526 uint64_t current_pos() const override;
529 explicit raw_null_ostream() {}
530 ~raw_null_ostream() override;
533 class buffer_ostream : public raw_svector_ostream {
535 SmallVector<char, 0> Buffer;
538 buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {}
539 ~buffer_ostream() override { OS << str(); }
542 } // end llvm namespace
544 #endif // LLVM_SUPPORT_RAW_OSTREAM_H