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/Compiler.h"
20 #include "llvm/Support/DataTypes.h"
21 #include <system_error>
24 class format_object_base;
25 class FormattedString;
26 class FormattedNumber;
28 class SmallVectorImpl;
32 enum OpenFlags : unsigned;
36 /// raw_ostream - This class implements an extremely fast bulk output stream
37 /// that can *only* output to a stream. It does not support seeking, reopening,
38 /// rewinding, line 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 /// SetBuffered - Set the stream to be buffered, with an automatically
101 /// determined buffer size.
104 /// SetBufferSize - Set the stream to be buffered, using the
105 /// specified buffer size.
106 void SetBufferSize(size_t Size) {
108 SetBufferAndMode(new char[Size], Size, InternalBuffer);
111 size_t GetBufferSize() const {
112 // If we're supposed to be buffered but haven't actually gotten around
113 // to allocating the buffer yet, return the value that would be used.
114 if (BufferMode != Unbuffered && OutBufStart == nullptr)
115 return preferred_buffer_size();
117 // Otherwise just return the size of the allocated buffer.
118 return OutBufEnd - OutBufStart;
121 /// SetUnbuffered - Set the stream to be unbuffered. When
122 /// unbuffered, the stream will flush after every write. This routine
123 /// will also flush the buffer immediately when the stream is being
124 /// set to unbuffered.
125 void SetUnbuffered() {
127 SetBufferAndMode(nullptr, 0, Unbuffered);
130 size_t GetNumBytesInBuffer() const {
131 return OutBufCur - OutBufStart;
134 //===--------------------------------------------------------------------===//
135 // Data Output Interface
136 //===--------------------------------------------------------------------===//
139 if (OutBufCur != OutBufStart)
143 raw_ostream &operator<<(char C) {
144 if (OutBufCur >= OutBufEnd)
150 raw_ostream &operator<<(unsigned char C) {
151 if (OutBufCur >= OutBufEnd)
157 raw_ostream &operator<<(signed char C) {
158 if (OutBufCur >= OutBufEnd)
164 raw_ostream &operator<<(StringRef Str) {
165 // Inline fast path, particularly for strings with a known length.
166 size_t Size = Str.size();
168 // Make sure we can use the fast path.
169 if (Size > (size_t)(OutBufEnd - OutBufCur))
170 return write(Str.data(), Size);
172 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 /// write_hex - Output \p N in hexadecimal, without any prefix or padding.
209 raw_ostream &write_hex(unsigned long long N);
211 /// write_escaped - Output \p Str, turning '\\', '\t', '\n', '"', and
212 /// anything that doesn't 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 /// indent - Insert 'NumSpaces' spaces.
228 raw_ostream &indent(unsigned NumSpaces);
231 /// Changes the foreground color of text that will be output from this point
233 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
234 /// change only the bold attribute, and keep colors untouched
235 /// @param Bold bold/brighter text, default false
236 /// @param BG if true change the background, default: change foreground
237 /// @returns itself so it can be used within << invocations
238 virtual raw_ostream &changeColor(enum Colors Color,
247 /// Resets the colors to terminal defaults. Call this when you are done
248 /// outputting colored text, or before program exit.
249 virtual raw_ostream &resetColor() { return *this; }
251 /// Reverses the forground and background colors.
252 virtual raw_ostream &reverseColor() { return *this; }
254 /// This function determines if this stream is connected to a "tty" or
255 /// "console" window. That is, the output would be displayed to the user
256 /// rather than being put on a pipe or stored in a file.
257 virtual bool is_displayed() const { return false; }
259 /// This function determines if this stream is displayed and supports colors.
260 virtual bool has_colors() const { return is_displayed(); }
262 //===--------------------------------------------------------------------===//
263 // Subclass Interface
264 //===--------------------------------------------------------------------===//
267 /// write_impl - The is the piece of the class that is implemented
268 /// by subclasses. This writes the \p Size bytes starting at
269 /// \p Ptr to the underlying stream.
271 /// This function is guaranteed to only be called at a point at which it is
272 /// safe for the subclass to install a new buffer via SetBuffer.
274 /// \param Ptr The start of the data to be written. For buffered streams this
275 /// is guaranteed to be the start of the buffer.
277 /// \param Size The number of bytes to be written.
279 /// \invariant { Size > 0 }
280 virtual void write_impl(const char *Ptr, size_t Size) = 0;
282 // An out of line virtual method to provide a home for the class vtable.
283 virtual void handle();
285 /// current_pos - Return the current position within the stream, not
286 /// counting the bytes currently in the buffer.
287 virtual uint64_t current_pos() const = 0;
290 /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is
291 /// intended for use only by subclasses which can arrange for the output to go
292 /// directly into the desired output buffer, instead of being copied on each
294 void SetBuffer(char *BufferStart, size_t Size) {
295 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
298 /// preferred_buffer_size - Return an efficient buffer size for the
299 /// underlying output mechanism.
300 virtual size_t preferred_buffer_size() const;
302 /// getBufferStart - Return the beginning of the current stream buffer, or 0
303 /// if the stream is unbuffered.
304 const char *getBufferStart() const { return OutBufStart; }
306 //===--------------------------------------------------------------------===//
308 //===--------------------------------------------------------------------===//
310 /// SetBufferAndMode - Install the given buffer and mode.
311 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
313 /// flush_nonempty - Flush the current buffer, which is known to be
314 /// non-empty. This outputs the currently buffered data and resets
315 /// the buffer to empty.
316 void flush_nonempty();
318 /// copy_to_buffer - Copy data into the buffer. Size must not be
319 /// greater than the number of unused bytes in the buffer.
320 void copy_to_buffer(const char *Ptr, size_t Size);
323 //===----------------------------------------------------------------------===//
324 // File Output Streams
325 //===----------------------------------------------------------------------===//
327 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
329 class raw_fd_ostream : public raw_ostream {
333 /// Error This flag is true if an error of any kind has been detected.
337 /// Controls whether the stream should attempt to use atomic writes, when
339 bool UseAtomicWrites;
343 /// write_impl - See raw_ostream::write_impl.
344 void write_impl(const char *Ptr, size_t Size) override;
346 /// current_pos - Return the current position within the stream, not
347 /// counting the bytes currently in the buffer.
348 uint64_t current_pos() const override { return pos; }
350 /// preferred_buffer_size - Determine an efficient buffer size.
351 size_t preferred_buffer_size() const override;
353 /// error_detected - Set the flag indicating that an output error has
354 /// been encountered.
355 void error_detected() { Error = true; }
358 /// Open the specified file for writing. If an error occurs, information
359 /// about the error is put into EC, and the stream should be immediately
361 /// \p Flags allows optional flags to control how the file will be opened.
363 /// As a special case, if Filename is "-", then the stream will use
364 /// STDOUT_FILENO instead of opening a file. Note that it will still consider
365 /// itself to own the file descriptor. In particular, it will close the
366 /// file descriptor when it is done (this is necessary to detect
368 raw_fd_ostream(StringRef Filename, std::error_code &EC,
369 sys::fs::OpenFlags Flags);
371 /// raw_fd_ostream ctor - FD is the file descriptor that this writes to. If
372 /// ShouldClose is true, this closes the file when the stream is destroyed.
373 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
377 /// close - Manually flush the stream and close the file.
378 /// Note that this does not call fsync.
381 /// seek - Flushes the stream and repositions the underlying file descriptor
382 /// position to the offset specified from the beginning of the file.
383 uint64_t seek(uint64_t off);
385 /// SetUseAtomicWrite - Set the stream to attempt to use atomic writes for
386 /// individual output routines where possible.
388 /// Note that because raw_ostream's are typically buffered, this flag is only
389 /// sensible when used on unbuffered streams which will flush their output
391 void SetUseAtomicWrites(bool Value) {
392 UseAtomicWrites = Value;
395 raw_ostream &changeColor(enum Colors colors, bool bold=false,
396 bool bg=false) override;
397 raw_ostream &resetColor() override;
399 raw_ostream &reverseColor() override;
401 bool is_displayed() const override;
403 bool has_colors() const override;
405 /// has_error - Return the value of the flag in this raw_fd_ostream indicating
406 /// whether an output error has been encountered.
407 /// This doesn't implicitly flush any pending output. Also, it doesn't
408 /// guarantee to detect all errors unless the stream has been closed.
409 bool has_error() const {
413 /// clear_error - Set the flag read by has_error() to false. If the error
414 /// flag is set at the time when this raw_ostream's destructor is called,
415 /// report_fatal_error is called to report the error. Use clear_error()
416 /// after handling the error to avoid this behavior.
418 /// "Errors should never pass silently.
419 /// Unless explicitly silenced."
420 /// - from The Zen of Python, by Tim Peters
427 /// outs() - This returns a reference to a raw_ostream for standard output.
428 /// Use it like: outs() << "foo" << "bar";
431 /// errs() - This returns a reference to a raw_ostream for standard error.
432 /// Use it like: errs() << "foo" << "bar";
435 /// nulls() - This returns a reference to a raw_ostream which simply discards
437 raw_ostream &nulls();
439 //===----------------------------------------------------------------------===//
440 // Output Stream Adaptors
441 //===----------------------------------------------------------------------===//
443 /// raw_string_ostream - A raw_ostream that writes to an std::string. This is a
444 /// simple adaptor class. This class does not encounter output errors.
445 class raw_string_ostream : public raw_ostream {
448 /// write_impl - See raw_ostream::write_impl.
449 void write_impl(const char *Ptr, size_t Size) override;
451 /// current_pos - Return the current position within the stream, not
452 /// counting the bytes currently in the buffer.
453 uint64_t current_pos() const override { return OS.size(); }
455 explicit raw_string_ostream(std::string &O) : OS(O) {}
456 ~raw_string_ostream();
458 /// str - Flushes the stream contents to the target string and returns
459 /// the string's reference.
466 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
467 /// SmallString. This is a simple adaptor class. This class does not
468 /// encounter output errors.
469 class raw_svector_ostream : public raw_ostream {
470 SmallVectorImpl<char> &OS;
472 /// write_impl - See raw_ostream::write_impl.
473 void write_impl(const char *Ptr, size_t Size) override;
475 /// current_pos - Return the current position within the stream, not
476 /// counting the bytes currently in the buffer.
477 uint64_t current_pos() const override;
479 /// Construct a new raw_svector_ostream.
481 /// \param O The vector to write to; this should generally have at least 128
482 /// bytes free to avoid any extraneous memory overhead.
483 explicit raw_svector_ostream(SmallVectorImpl<char> &O);
484 ~raw_svector_ostream();
486 /// resync - This is called when the SmallVector we're appending to is changed
487 /// outside of the raw_svector_ostream's control. It is only safe to do this
488 /// if the raw_svector_ostream has previously been flushed.
491 /// str - Flushes the stream contents to the target vector and return a
492 /// StringRef for the vector contents.
496 /// raw_null_ostream - A raw_ostream that discards all output.
497 class raw_null_ostream : public raw_ostream {
498 /// write_impl - See raw_ostream::write_impl.
499 void write_impl(const char *Ptr, size_t size) override;
501 /// current_pos - Return the current position within the stream, not
502 /// counting the bytes currently in the buffer.
503 uint64_t current_pos() const override;
506 explicit raw_null_ostream() {}
510 } // end llvm namespace