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;
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 &) LLVM_DELETED_FUNCTION;
42 raw_ostream(const raw_ostream &) LLVM_DELETED_FUNCTION;
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<<(unsigned long N);
189 raw_ostream &operator<<(long N);
190 raw_ostream &operator<<(unsigned long long N);
191 raw_ostream &operator<<(long long N);
192 raw_ostream &operator<<(const void *P);
193 raw_ostream &operator<<(unsigned int N) {
194 return this->operator<<(static_cast<unsigned long>(N));
197 raw_ostream &operator<<(int N) {
198 return this->operator<<(static_cast<long>(N));
201 raw_ostream &operator<<(double N);
203 /// write_hex - Output \p N in hexadecimal, without any prefix or padding.
204 raw_ostream &write_hex(unsigned long long N);
206 /// write_escaped - Output \p Str, turning '\\', '\t', '\n', '"', and
207 /// anything that doesn't satisfy std::isprint into an escape sequence.
208 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
210 raw_ostream &write(unsigned char C);
211 raw_ostream &write(const char *Ptr, size_t Size);
213 // Formatted output, see the format() function in Support/Format.h.
214 raw_ostream &operator<<(const format_object_base &Fmt);
216 // Formatted output, see the leftJustify() function in Support/Format.h.
217 raw_ostream &operator<<(const FormattedString &);
219 // Formatted output, see the formatHex() function in Support/Format.h.
220 raw_ostream &operator<<(const FormattedNumber &);
222 /// indent - Insert 'NumSpaces' spaces.
223 raw_ostream &indent(unsigned NumSpaces);
226 /// Changes the foreground color of text that will be output from this point
228 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
229 /// change only the bold attribute, and keep colors untouched
230 /// @param Bold bold/brighter text, default false
231 /// @param BG if true change the background, default: change foreground
232 /// @returns itself so it can be used within << invocations
233 virtual raw_ostream &changeColor(enum Colors Color,
242 /// Resets the colors to terminal defaults. Call this when you are done
243 /// outputting colored text, or before program exit.
244 virtual raw_ostream &resetColor() { return *this; }
246 /// Reverses the forground and background colors.
247 virtual raw_ostream &reverseColor() { return *this; }
249 /// This function determines if this stream is connected to a "tty" or
250 /// "console" window. That is, the output would be displayed to the user
251 /// rather than being put on a pipe or stored in a file.
252 virtual bool is_displayed() const { return false; }
254 /// This function determines if this stream is displayed and supports colors.
255 virtual bool has_colors() const { return is_displayed(); }
257 //===--------------------------------------------------------------------===//
258 // Subclass Interface
259 //===--------------------------------------------------------------------===//
262 /// write_impl - The is the piece of the class that is implemented
263 /// by subclasses. This writes the \p Size bytes starting at
264 /// \p Ptr to the underlying stream.
266 /// This function is guaranteed to only be called at a point at which it is
267 /// safe for the subclass to install a new buffer via SetBuffer.
269 /// \param Ptr The start of the data to be written. For buffered streams this
270 /// is guaranteed to be the start of the buffer.
272 /// \param Size The number of bytes to be written.
274 /// \invariant { Size > 0 }
275 virtual void write_impl(const char *Ptr, size_t Size) = 0;
277 // An out of line virtual method to provide a home for the class vtable.
278 virtual void handle();
280 /// current_pos - Return the current position within the stream, not
281 /// counting the bytes currently in the buffer.
282 virtual uint64_t current_pos() const = 0;
285 /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is
286 /// intended for use only by subclasses which can arrange for the output to go
287 /// directly into the desired output buffer, instead of being copied on each
289 void SetBuffer(char *BufferStart, size_t Size) {
290 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
293 /// preferred_buffer_size - Return an efficient buffer size for the
294 /// underlying output mechanism.
295 virtual size_t preferred_buffer_size() const;
297 /// getBufferStart - Return the beginning of the current stream buffer, or 0
298 /// if the stream is unbuffered.
299 const char *getBufferStart() const { return OutBufStart; }
301 //===--------------------------------------------------------------------===//
303 //===--------------------------------------------------------------------===//
305 /// SetBufferAndMode - Install the given buffer and mode.
306 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
308 /// flush_nonempty - Flush the current buffer, which is known to be
309 /// non-empty. This outputs the currently buffered data and resets
310 /// the buffer to empty.
311 void flush_nonempty();
313 /// copy_to_buffer - Copy data into the buffer. Size must not be
314 /// greater than the number of unused bytes in the buffer.
315 void copy_to_buffer(const char *Ptr, size_t Size);
318 //===----------------------------------------------------------------------===//
319 // File Output Streams
320 //===----------------------------------------------------------------------===//
322 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
324 class raw_fd_ostream : public raw_ostream {
328 /// Error This flag is true if an error of any kind has been detected.
332 /// Controls whether the stream should attempt to use atomic writes, when
334 bool UseAtomicWrites;
338 /// write_impl - See raw_ostream::write_impl.
339 void write_impl(const char *Ptr, size_t Size) override;
341 /// current_pos - Return the current position within the stream, not
342 /// counting the bytes currently in the buffer.
343 uint64_t current_pos() const override { return pos; }
345 /// preferred_buffer_size - Determine an efficient buffer size.
346 size_t preferred_buffer_size() const override;
348 /// error_detected - Set the flag indicating that an output error has
349 /// been encountered.
350 void error_detected() { Error = true; }
353 /// Open the specified file for writing. If an error occurs, information
354 /// about the error is put into EC, and the stream should be immediately
356 /// \p Flags allows optional flags to control how the file will be opened.
358 /// As a special case, if Filename is "-", then the stream will use
359 /// STDOUT_FILENO instead of opening a file. Note that it will still consider
360 /// itself to own the file descriptor. In particular, it will close the
361 /// file descriptor when it is done (this is necessary to detect
363 raw_fd_ostream(StringRef Filename, std::error_code &EC,
364 sys::fs::OpenFlags Flags);
366 /// raw_fd_ostream ctor - FD is the file descriptor that this writes to. If
367 /// ShouldClose is true, this closes the file when the stream is destroyed.
368 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
372 /// close - Manually flush the stream and close the file.
373 /// Note that this does not call fsync.
376 /// seek - Flushes the stream and repositions the underlying file descriptor
377 /// position to the offset specified from the beginning of the file.
378 uint64_t seek(uint64_t off);
380 /// SetUseAtomicWrite - Set the stream to attempt to use atomic writes for
381 /// individual output routines where possible.
383 /// Note that because raw_ostream's are typically buffered, this flag is only
384 /// sensible when used on unbuffered streams which will flush their output
386 void SetUseAtomicWrites(bool Value) {
387 UseAtomicWrites = Value;
390 raw_ostream &changeColor(enum Colors colors, bool bold=false,
391 bool bg=false) override;
392 raw_ostream &resetColor() override;
394 raw_ostream &reverseColor() override;
396 bool is_displayed() const override;
398 bool has_colors() const override;
400 /// has_error - Return the value of the flag in this raw_fd_ostream indicating
401 /// whether an output error has been encountered.
402 /// This doesn't implicitly flush any pending output. Also, it doesn't
403 /// guarantee to detect all errors unless the stream has been closed.
404 bool has_error() const {
408 /// clear_error - Set the flag read by has_error() to false. If the error
409 /// flag is set at the time when this raw_ostream's destructor is called,
410 /// report_fatal_error is called to report the error. Use clear_error()
411 /// after handling the error to avoid this behavior.
413 /// "Errors should never pass silently.
414 /// Unless explicitly silenced."
415 /// - from The Zen of Python, by Tim Peters
422 /// outs() - This returns a reference to a raw_ostream for standard output.
423 /// Use it like: outs() << "foo" << "bar";
426 /// errs() - This returns a reference to a raw_ostream for standard error.
427 /// Use it like: errs() << "foo" << "bar";
430 /// nulls() - This returns a reference to a raw_ostream which simply discards
432 raw_ostream &nulls();
434 //===----------------------------------------------------------------------===//
435 // Output Stream Adaptors
436 //===----------------------------------------------------------------------===//
438 /// raw_string_ostream - A raw_ostream that writes to an std::string. This is a
439 /// simple adaptor class. This class does not encounter output errors.
440 class raw_string_ostream : public raw_ostream {
443 /// write_impl - See raw_ostream::write_impl.
444 void write_impl(const char *Ptr, size_t Size) override;
446 /// current_pos - Return the current position within the stream, not
447 /// counting the bytes currently in the buffer.
448 uint64_t current_pos() const override { return OS.size(); }
450 explicit raw_string_ostream(std::string &O) : OS(O) {}
451 ~raw_string_ostream();
453 /// str - Flushes the stream contents to the target string and returns
454 /// the string's reference.
461 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
462 /// SmallString. This is a simple adaptor class. This class does not
463 /// encounter output errors.
464 class raw_svector_ostream : public raw_ostream {
465 SmallVectorImpl<char> &OS;
467 /// write_impl - See raw_ostream::write_impl.
468 void write_impl(const char *Ptr, size_t Size) override;
470 /// current_pos - Return the current position within the stream, not
471 /// counting the bytes currently in the buffer.
472 uint64_t current_pos() const override;
474 /// Construct a new raw_svector_ostream.
476 /// \param O The vector to write to; this should generally have at least 128
477 /// bytes free to avoid any extraneous memory overhead.
478 explicit raw_svector_ostream(SmallVectorImpl<char> &O);
479 ~raw_svector_ostream();
481 /// resync - This is called when the SmallVector we're appending to is changed
482 /// outside of the raw_svector_ostream's control. It is only safe to do this
483 /// if the raw_svector_ostream has previously been flushed.
486 /// str - Flushes the stream contents to the target vector and return a
487 /// StringRef for the vector contents.
491 /// raw_null_ostream - A raw_ostream that discards all output.
492 class raw_null_ostream : public raw_ostream {
493 /// write_impl - See raw_ostream::write_impl.
494 void write_impl(const char *Ptr, size_t size) override;
496 /// current_pos - Return the current position within the stream, not
497 /// counting the bytes currently in the buffer.
498 uint64_t current_pos() const override;
501 explicit raw_null_ostream() {}
505 } // end llvm namespace