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;
27 class SmallVectorImpl;
31 enum OpenFlags : unsigned;
35 /// raw_ostream - This class implements an extremely fast bulk output stream
36 /// that can *only* output to a stream. It does not support seeking, reopening,
37 /// rewinding, line 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;
71 // color order matches ANSI escape sequence, don't change
84 explicit raw_ostream(bool unbuffered=false)
85 : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
86 // Start out ready to flush.
87 OutBufStart = OutBufEnd = OutBufCur = nullptr;
90 virtual ~raw_ostream();
92 /// tell - Return the current offset with the file.
93 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
95 //===--------------------------------------------------------------------===//
96 // Configuration Interface
97 //===--------------------------------------------------------------------===//
99 /// SetBuffered - Set the stream to be buffered, with an automatically
100 /// determined buffer size.
103 /// SetBufferSize - Set the stream to be buffered, using the
104 /// 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 /// SetUnbuffered - Set the stream to be unbuffered. When
121 /// unbuffered, the stream will flush after every write. This routine
122 /// will also flush the buffer immediately when the stream is being
123 /// set to unbuffered.
124 void SetUnbuffered() {
126 SetBufferAndMode(nullptr, 0, Unbuffered);
129 size_t GetNumBytesInBuffer() const {
130 return OutBufCur - OutBufStart;
133 //===--------------------------------------------------------------------===//
134 // Data Output Interface
135 //===--------------------------------------------------------------------===//
138 if (OutBufCur != OutBufStart)
142 raw_ostream &operator<<(char C) {
143 if (OutBufCur >= OutBufEnd)
149 raw_ostream &operator<<(unsigned char C) {
150 if (OutBufCur >= OutBufEnd)
156 raw_ostream &operator<<(signed char C) {
157 if (OutBufCur >= OutBufEnd)
163 raw_ostream &operator<<(StringRef Str) {
164 // Inline fast path, particularly for strings with a known length.
165 size_t Size = Str.size();
167 // Make sure we can use the fast path.
168 if (Size > (size_t)(OutBufEnd - OutBufCur))
169 return write(Str.data(), Size);
171 memcpy(OutBufCur, Str.data(), Size);
176 raw_ostream &operator<<(const char *Str) {
177 // Inline fast path, particularly for constant strings where a sufficiently
178 // smart compiler will simplify strlen.
180 return this->operator<<(StringRef(Str));
183 raw_ostream &operator<<(const std::string &Str) {
184 // Avoid the fast path, it would only increase code size for a marginal win.
185 return write(Str.data(), Str.length());
188 raw_ostream &operator<<(const llvm::SmallVectorImpl<char> &Str) {
189 return write(Str.data(), Str.size());
192 raw_ostream &operator<<(unsigned long N);
193 raw_ostream &operator<<(long N);
194 raw_ostream &operator<<(unsigned long long N);
195 raw_ostream &operator<<(long long N);
196 raw_ostream &operator<<(const void *P);
197 raw_ostream &operator<<(unsigned int N) {
198 return this->operator<<(static_cast<unsigned long>(N));
201 raw_ostream &operator<<(int N) {
202 return this->operator<<(static_cast<long>(N));
205 raw_ostream &operator<<(double N);
207 /// write_hex - Output \p N in hexadecimal, without any prefix or padding.
208 raw_ostream &write_hex(unsigned long long N);
210 /// write_escaped - Output \p Str, turning '\\', '\t', '\n', '"', and
211 /// anything that doesn't satisfy std::isprint into an escape sequence.
212 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
214 raw_ostream &write(unsigned char C);
215 raw_ostream &write(const char *Ptr, size_t Size);
217 // Formatted output, see the format() function in Support/Format.h.
218 raw_ostream &operator<<(const format_object_base &Fmt);
220 // Formatted output, see the leftJustify() function in Support/Format.h.
221 raw_ostream &operator<<(const FormattedString &);
223 // Formatted output, see the formatHex() function in Support/Format.h.
224 raw_ostream &operator<<(const FormattedNumber &);
226 /// indent - Insert 'NumSpaces' spaces.
227 raw_ostream &indent(unsigned NumSpaces);
230 /// Changes the foreground color of text that will be output from this point
232 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
233 /// change only the bold attribute, and keep colors untouched
234 /// @param Bold bold/brighter text, default false
235 /// @param BG if true change the background, default: change foreground
236 /// @returns itself so it can be used within << invocations
237 virtual raw_ostream &changeColor(enum Colors Color,
246 /// Resets the colors to terminal defaults. Call this when you are done
247 /// outputting colored text, or before program exit.
248 virtual raw_ostream &resetColor() { return *this; }
250 /// Reverses the forground and background colors.
251 virtual raw_ostream &reverseColor() { return *this; }
253 /// This function determines if this stream is connected to a "tty" or
254 /// "console" window. That is, the output would be displayed to the user
255 /// rather than being put on a pipe or stored in a file.
256 virtual bool is_displayed() const { return false; }
258 /// This function determines if this stream is displayed and supports colors.
259 virtual bool has_colors() const { return is_displayed(); }
261 //===--------------------------------------------------------------------===//
262 // Subclass Interface
263 //===--------------------------------------------------------------------===//
266 /// write_impl - The is the piece of the class that is implemented
267 /// by subclasses. This writes the \p Size bytes starting at
268 /// \p Ptr to the underlying stream.
270 /// This function is guaranteed to only be called at a point at which it is
271 /// safe for the subclass to install a new buffer via SetBuffer.
273 /// \param Ptr The start of the data to be written. For buffered streams this
274 /// is guaranteed to be the start of the buffer.
276 /// \param Size The number of bytes to be written.
278 /// \invariant { Size > 0 }
279 virtual void write_impl(const char *Ptr, size_t Size) = 0;
281 // An out of line virtual method to provide a home for the class vtable.
282 virtual void handle();
284 /// current_pos - Return the current position within the stream, not
285 /// counting the bytes currently in the buffer.
286 virtual uint64_t current_pos() const = 0;
289 /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is
290 /// intended for use only by subclasses which can arrange for the output to go
291 /// directly into the desired output buffer, instead of being copied on each
293 void SetBuffer(char *BufferStart, size_t Size) {
294 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
297 /// preferred_buffer_size - Return an efficient buffer size for the
298 /// underlying output mechanism.
299 virtual size_t preferred_buffer_size() const;
301 /// getBufferStart - Return the beginning of the current stream buffer, or 0
302 /// if the stream is unbuffered.
303 const char *getBufferStart() const { return OutBufStart; }
305 //===--------------------------------------------------------------------===//
307 //===--------------------------------------------------------------------===//
309 /// SetBufferAndMode - Install the given buffer and mode.
310 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
312 /// flush_nonempty - Flush the current buffer, which is known to be
313 /// non-empty. This outputs the currently buffered data and resets
314 /// the buffer to empty.
315 void flush_nonempty();
317 /// copy_to_buffer - Copy data into the buffer. Size must not be
318 /// greater than the number of unused bytes in the buffer.
319 void copy_to_buffer(const char *Ptr, size_t Size);
322 //===----------------------------------------------------------------------===//
323 // File Output Streams
324 //===----------------------------------------------------------------------===//
326 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
328 class raw_fd_ostream : public raw_ostream {
332 /// Error This flag is true if an error of any kind has been detected.
336 /// Controls whether the stream should attempt to use atomic writes, when
338 bool UseAtomicWrites;
342 /// write_impl - See raw_ostream::write_impl.
343 void write_impl(const char *Ptr, size_t Size) override;
345 /// current_pos - Return the current position within the stream, not
346 /// counting the bytes currently in the buffer.
347 uint64_t current_pos() const override { return pos; }
349 /// preferred_buffer_size - Determine an efficient buffer size.
350 size_t preferred_buffer_size() const override;
352 /// error_detected - Set the flag indicating that an output error has
353 /// been encountered.
354 void error_detected() { Error = true; }
357 /// Open the specified file for writing. If an error occurs, information
358 /// about the error is put into EC, and the stream should be immediately
360 /// \p Flags allows optional flags to control how the file will be opened.
362 /// As a special case, if Filename is "-", then the stream will use
363 /// STDOUT_FILENO instead of opening a file. Note that it will still consider
364 /// itself to own the file descriptor. In particular, it will close the
365 /// file descriptor when it is done (this is necessary to detect
367 raw_fd_ostream(StringRef Filename, std::error_code &EC,
368 sys::fs::OpenFlags Flags);
370 /// raw_fd_ostream ctor - FD is the file descriptor that this writes to. If
371 /// ShouldClose is true, this closes the file when the stream is destroyed.
372 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
376 /// close - Manually flush the stream and close the file.
377 /// Note that this does not call fsync.
380 /// seek - Flushes the stream and repositions the underlying file descriptor
381 /// position to the offset specified from the beginning of the file.
382 uint64_t seek(uint64_t off);
384 /// SetUseAtomicWrite - Set the stream to attempt to use atomic writes for
385 /// individual output routines where possible.
387 /// Note that because raw_ostream's are typically buffered, this flag is only
388 /// sensible when used on unbuffered streams which will flush their output
390 void SetUseAtomicWrites(bool Value) {
391 UseAtomicWrites = Value;
394 raw_ostream &changeColor(enum Colors colors, bool bold=false,
395 bool bg=false) override;
396 raw_ostream &resetColor() override;
398 raw_ostream &reverseColor() override;
400 bool is_displayed() const override;
402 bool has_colors() const override;
404 /// has_error - Return the value of the flag in this raw_fd_ostream indicating
405 /// whether an output error has been encountered.
406 /// This doesn't implicitly flush any pending output. Also, it doesn't
407 /// guarantee to detect all errors unless the stream has been closed.
408 bool has_error() const {
412 /// clear_error - Set the flag read by has_error() to false. If the error
413 /// flag is set at the time when this raw_ostream's destructor is called,
414 /// report_fatal_error is called to report the error. Use clear_error()
415 /// after handling the error to avoid this behavior.
417 /// "Errors should never pass silently.
418 /// Unless explicitly silenced."
419 /// - from The Zen of Python, by Tim Peters
426 /// outs() - This returns a reference to a raw_ostream for standard output.
427 /// Use it like: outs() << "foo" << "bar";
430 /// errs() - This returns a reference to a raw_ostream for standard error.
431 /// Use it like: errs() << "foo" << "bar";
434 /// nulls() - This returns a reference to a raw_ostream which simply discards
436 raw_ostream &nulls();
438 //===----------------------------------------------------------------------===//
439 // Output Stream Adaptors
440 //===----------------------------------------------------------------------===//
442 /// raw_string_ostream - A raw_ostream that writes to an std::string. This is a
443 /// simple adaptor class. This class does not encounter output errors.
444 class raw_string_ostream : public raw_ostream {
447 /// write_impl - See raw_ostream::write_impl.
448 void write_impl(const char *Ptr, size_t Size) override;
450 /// current_pos - Return the current position within the stream, not
451 /// counting the bytes currently in the buffer.
452 uint64_t current_pos() const override { return OS.size(); }
454 explicit raw_string_ostream(std::string &O) : OS(O) {}
455 ~raw_string_ostream();
457 /// str - Flushes the stream contents to the target string and returns
458 /// the string's reference.
465 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
466 /// SmallString. This is a simple adaptor class. This class does not
467 /// encounter output errors.
468 class raw_svector_ostream : public raw_ostream {
469 SmallVectorImpl<char> &OS;
471 /// write_impl - See raw_ostream::write_impl.
472 void write_impl(const char *Ptr, size_t Size) override;
474 /// current_pos - Return the current position within the stream, not
475 /// counting the bytes currently in the buffer.
476 uint64_t current_pos() const override;
478 /// Construct a new raw_svector_ostream.
480 /// \param O The vector to write to; this should generally have at least 128
481 /// bytes free to avoid any extraneous memory overhead.
482 explicit raw_svector_ostream(SmallVectorImpl<char> &O);
483 ~raw_svector_ostream();
485 /// resync - This is called when the SmallVector we're appending to is changed
486 /// outside of the raw_svector_ostream's control. It is only safe to do this
487 /// if the raw_svector_ostream has previously been flushed.
490 /// str - Flushes the stream contents to the target vector and return a
491 /// StringRef for the vector contents.
495 /// raw_null_ostream - A raw_ostream that discards all output.
496 class raw_null_ostream : public raw_ostream {
497 /// write_impl - See raw_ostream::write_impl.
498 void write_impl(const char *Ptr, size_t size) override;
500 /// current_pos - Return the current position within the stream, not
501 /// counting the bytes currently in the buffer.
502 uint64_t current_pos() const override;
505 explicit raw_null_ostream() {}
509 } // end llvm namespace