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/StringRef.h"
18 #include "llvm/Support/Compiler.h"
19 #include "llvm/Support/DataTypes.h"
20 #include <system_error>
23 class format_object_base;
25 class SmallVectorImpl;
29 enum OpenFlags : unsigned;
33 /// raw_ostream - This class implements an extremely fast bulk output stream
34 /// that can *only* output to a stream. It does not support seeking, reopening,
35 /// rewinding, line buffered disciplines etc. It is a simple buffer that outputs
36 /// a chunk at a time.
39 void operator=(const raw_ostream &) LLVM_DELETED_FUNCTION;
40 raw_ostream(const raw_ostream &) LLVM_DELETED_FUNCTION;
42 /// The buffer is handled in such a way that the buffer is
43 /// uninitialized, unbuffered, or out of space when OutBufCur >=
44 /// OutBufEnd. Thus a single comparison suffices to determine if we
45 /// need to take the slow path to write a single character.
47 /// The buffer is in one of three states:
48 /// 1. Unbuffered (BufferMode == Unbuffered)
49 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
50 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
51 /// OutBufEnd - OutBufStart >= 1).
53 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
54 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
55 /// managed by the subclass.
57 /// If a subclass installs an external buffer using SetBuffer then it can wait
58 /// for a \see write_impl() call to handle the data which has been put into
60 char *OutBufStart, *OutBufEnd, *OutBufCur;
69 // color order matches ANSI escape sequence, don't change
82 explicit raw_ostream(bool unbuffered=false)
83 : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
84 // Start out ready to flush.
85 OutBufStart = OutBufEnd = OutBufCur = nullptr;
88 virtual ~raw_ostream();
90 /// tell - Return the current offset with the file.
91 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
93 //===--------------------------------------------------------------------===//
94 // Configuration Interface
95 //===--------------------------------------------------------------------===//
97 /// SetBuffered - Set the stream to be buffered, with an automatically
98 /// determined buffer size.
101 /// SetBufferSize - Set the stream to be buffered, using the
102 /// 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 /// SetUnbuffered - Set the stream to be unbuffered. When
119 /// unbuffered, the stream will flush after every write. This routine
120 /// will also flush the buffer immediately when the stream is being
121 /// set to unbuffered.
122 void SetUnbuffered() {
124 SetBufferAndMode(nullptr, 0, Unbuffered);
127 size_t GetNumBytesInBuffer() const {
128 return OutBufCur - OutBufStart;
131 //===--------------------------------------------------------------------===//
132 // Data Output Interface
133 //===--------------------------------------------------------------------===//
136 if (OutBufCur != OutBufStart)
140 raw_ostream &operator<<(char C) {
141 if (OutBufCur >= OutBufEnd)
147 raw_ostream &operator<<(unsigned char C) {
148 if (OutBufCur >= OutBufEnd)
154 raw_ostream &operator<<(signed char C) {
155 if (OutBufCur >= OutBufEnd)
161 raw_ostream &operator<<(StringRef Str) {
162 // Inline fast path, particularly for strings with a known length.
163 size_t Size = Str.size();
165 // Make sure we can use the fast path.
166 if (Size > (size_t)(OutBufEnd - OutBufCur))
167 return write(Str.data(), Size);
169 memcpy(OutBufCur, Str.data(), Size);
174 raw_ostream &operator<<(const char *Str) {
175 // Inline fast path, particularly for constant strings where a sufficiently
176 // smart compiler will simplify strlen.
178 return this->operator<<(StringRef(Str));
181 raw_ostream &operator<<(const std::string &Str) {
182 // Avoid the fast path, it would only increase code size for a marginal win.
183 return write(Str.data(), Str.length());
186 raw_ostream &operator<<(unsigned long N);
187 raw_ostream &operator<<(long N);
188 raw_ostream &operator<<(unsigned long long N);
189 raw_ostream &operator<<(long long N);
190 raw_ostream &operator<<(const void *P);
191 raw_ostream &operator<<(unsigned int N) {
192 return this->operator<<(static_cast<unsigned long>(N));
195 raw_ostream &operator<<(int N) {
196 return this->operator<<(static_cast<long>(N));
199 raw_ostream &operator<<(double N);
201 /// write_hex - Output \p N in hexadecimal, without any prefix or padding.
202 raw_ostream &write_hex(unsigned long long N);
204 /// write_escaped - Output \p Str, turning '\\', '\t', '\n', '"', and
205 /// anything that doesn't satisfy std::isprint into an escape sequence.
206 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
208 raw_ostream &write(unsigned char C);
209 raw_ostream &write(const char *Ptr, size_t Size);
211 // Formatted output, see the format() function in Support/Format.h.
212 raw_ostream &operator<<(const format_object_base &Fmt);
214 /// indent - Insert 'NumSpaces' spaces.
215 raw_ostream &indent(unsigned NumSpaces);
218 /// Changes the foreground color of text that will be output from this point
220 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
221 /// change only the bold attribute, and keep colors untouched
222 /// @param Bold bold/brighter text, default false
223 /// @param BG if true change the background, default: change foreground
224 /// @returns itself so it can be used within << invocations
225 virtual raw_ostream &changeColor(enum Colors Color,
234 /// Resets the colors to terminal defaults. Call this when you are done
235 /// outputting colored text, or before program exit.
236 virtual raw_ostream &resetColor() { return *this; }
238 /// Reverses the forground and background colors.
239 virtual raw_ostream &reverseColor() { return *this; }
241 /// This function determines if this stream is connected to a "tty" or
242 /// "console" window. That is, the output would be displayed to the user
243 /// rather than being put on a pipe or stored in a file.
244 virtual bool is_displayed() const { return false; }
246 /// This function determines if this stream is displayed and supports colors.
247 virtual bool has_colors() const { return is_displayed(); }
249 //===--------------------------------------------------------------------===//
250 // Subclass Interface
251 //===--------------------------------------------------------------------===//
254 /// write_impl - The is the piece of the class that is implemented
255 /// by subclasses. This writes the \p Size bytes starting at
256 /// \p Ptr to the underlying stream.
258 /// This function is guaranteed to only be called at a point at which it is
259 /// safe for the subclass to install a new buffer via SetBuffer.
261 /// \param Ptr The start of the data to be written. For buffered streams this
262 /// is guaranteed to be the start of the buffer.
264 /// \param Size The number of bytes to be written.
266 /// \invariant { Size > 0 }
267 virtual void write_impl(const char *Ptr, size_t Size) = 0;
269 // An out of line virtual method to provide a home for the class vtable.
270 virtual void handle();
272 /// current_pos - Return the current position within the stream, not
273 /// counting the bytes currently in the buffer.
274 virtual uint64_t current_pos() const = 0;
277 /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is
278 /// intended for use only by subclasses which can arrange for the output to go
279 /// directly into the desired output buffer, instead of being copied on each
281 void SetBuffer(char *BufferStart, size_t Size) {
282 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
285 /// preferred_buffer_size - Return an efficient buffer size for the
286 /// underlying output mechanism.
287 virtual size_t preferred_buffer_size() const;
289 /// getBufferStart - Return the beginning of the current stream buffer, or 0
290 /// if the stream is unbuffered.
291 const char *getBufferStart() const { return OutBufStart; }
293 //===--------------------------------------------------------------------===//
295 //===--------------------------------------------------------------------===//
297 /// SetBufferAndMode - Install the given buffer and mode.
298 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
300 /// flush_nonempty - Flush the current buffer, which is known to be
301 /// non-empty. This outputs the currently buffered data and resets
302 /// the buffer to empty.
303 void flush_nonempty();
305 /// copy_to_buffer - Copy data into the buffer. Size must not be
306 /// greater than the number of unused bytes in the buffer.
307 void copy_to_buffer(const char *Ptr, size_t Size);
310 //===----------------------------------------------------------------------===//
311 // File Output Streams
312 //===----------------------------------------------------------------------===//
314 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
316 class raw_fd_ostream : public raw_ostream {
320 /// Error This flag is true if an error of any kind has been detected.
324 /// Controls whether the stream should attempt to use atomic writes, when
326 bool UseAtomicWrites;
330 /// write_impl - See raw_ostream::write_impl.
331 void write_impl(const char *Ptr, size_t Size) override;
333 /// current_pos - Return the current position within the stream, not
334 /// counting the bytes currently in the buffer.
335 uint64_t current_pos() const override { return pos; }
337 /// preferred_buffer_size - Determine an efficient buffer size.
338 size_t preferred_buffer_size() const override;
340 /// error_detected - Set the flag indicating that an output error has
341 /// been encountered.
342 void error_detected() { Error = true; }
345 /// Open the specified file for writing. If an error occurs, information
346 /// about the error is put into EC, and the stream should be immediately
348 /// \p Flags allows optional flags to control how the file will be opened.
350 /// As a special case, if Filename is "-", then the stream will use
351 /// STDOUT_FILENO instead of opening a file. Note that it will still consider
352 /// itself to own the file descriptor. In particular, it will close the
353 /// file descriptor when it is done (this is necessary to detect
355 raw_fd_ostream(StringRef Filename, std::error_code &EC,
356 sys::fs::OpenFlags Flags);
358 /// raw_fd_ostream ctor - FD is the file descriptor that this writes to. If
359 /// ShouldClose is true, this closes the file when the stream is destroyed.
360 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
364 /// close - Manually flush the stream and close the file.
365 /// Note that this does not call fsync.
368 /// seek - Flushes the stream and repositions the underlying file descriptor
369 /// position to the offset specified from the beginning of the file.
370 uint64_t seek(uint64_t off);
372 /// SetUseAtomicWrite - Set the stream to attempt to use atomic writes for
373 /// individual output routines where possible.
375 /// Note that because raw_ostream's are typically buffered, this flag is only
376 /// sensible when used on unbuffered streams which will flush their output
378 void SetUseAtomicWrites(bool Value) {
379 UseAtomicWrites = Value;
382 raw_ostream &changeColor(enum Colors colors, bool bold=false,
383 bool bg=false) override;
384 raw_ostream &resetColor() override;
386 raw_ostream &reverseColor() override;
388 bool is_displayed() const override;
390 bool has_colors() const override;
392 /// has_error - Return the value of the flag in this raw_fd_ostream indicating
393 /// whether an output error has been encountered.
394 /// This doesn't implicitly flush any pending output. Also, it doesn't
395 /// guarantee to detect all errors unless the stream has been closed.
396 bool has_error() const {
400 /// clear_error - Set the flag read by has_error() to false. If the error
401 /// flag is set at the time when this raw_ostream's destructor is called,
402 /// report_fatal_error is called to report the error. Use clear_error()
403 /// after handling the error to avoid this behavior.
405 /// "Errors should never pass silently.
406 /// Unless explicitly silenced."
407 /// - from The Zen of Python, by Tim Peters
414 /// outs() - This returns a reference to a raw_ostream for standard output.
415 /// Use it like: outs() << "foo" << "bar";
418 /// errs() - This returns a reference to a raw_ostream for standard error.
419 /// Use it like: errs() << "foo" << "bar";
422 /// nulls() - This returns a reference to a raw_ostream which simply discards
424 raw_ostream &nulls();
426 //===----------------------------------------------------------------------===//
427 // Output Stream Adaptors
428 //===----------------------------------------------------------------------===//
430 /// raw_string_ostream - A raw_ostream that writes to an std::string. This is a
431 /// simple adaptor class. This class does not encounter output errors.
432 class raw_string_ostream : public raw_ostream {
435 /// write_impl - See raw_ostream::write_impl.
436 void write_impl(const char *Ptr, size_t Size) override;
438 /// current_pos - Return the current position within the stream, not
439 /// counting the bytes currently in the buffer.
440 uint64_t current_pos() const override { return OS.size(); }
442 explicit raw_string_ostream(std::string &O) : OS(O) {}
443 ~raw_string_ostream();
445 /// str - Flushes the stream contents to the target string and returns
446 /// the string's reference.
453 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
454 /// SmallString. This is a simple adaptor class. This class does not
455 /// encounter output errors.
456 class raw_svector_ostream : public raw_ostream {
457 SmallVectorImpl<char> &OS;
459 /// write_impl - See raw_ostream::write_impl.
460 void write_impl(const char *Ptr, size_t Size) override;
462 /// current_pos - Return the current position within the stream, not
463 /// counting the bytes currently in the buffer.
464 uint64_t current_pos() const override;
466 /// Construct a new raw_svector_ostream.
468 /// \param O The vector to write to; this should generally have at least 128
469 /// bytes free to avoid any extraneous memory overhead.
470 explicit raw_svector_ostream(SmallVectorImpl<char> &O);
471 ~raw_svector_ostream();
473 /// resync - This is called when the SmallVector we're appending to is changed
474 /// outside of the raw_svector_ostream's control. It is only safe to do this
475 /// if the raw_svector_ostream has previously been flushed.
478 /// str - Flushes the stream contents to the target vector and return a
479 /// StringRef for the vector contents.
483 /// raw_null_ostream - A raw_ostream that discards all output.
484 class raw_null_ostream : public raw_ostream {
485 /// write_impl - See raw_ostream::write_impl.
486 void write_impl(const char *Ptr, size_t size) override;
488 /// current_pos - Return the current position within the stream, not
489 /// counting the bytes currently in the buffer.
490 uint64_t current_pos() const override;
493 explicit raw_null_ostream() {}
497 } // end llvm namespace