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/DataTypes.h"
21 class format_object_base;
23 class SmallVectorImpl;
25 /// raw_ostream - This class implements an extremely fast bulk output stream
26 /// that can *only* output to a stream. It does not support seeking, reopening,
27 /// rewinding, line buffered disciplines etc. It is a simple buffer that outputs
28 /// a chunk at a time.
31 // Do not implement. raw_ostream is noncopyable.
32 void operator=(const raw_ostream &);
33 raw_ostream(const raw_ostream &);
35 /// The buffer is handled in such a way that the buffer is
36 /// uninitialized, unbuffered, or out of space when OutBufCur >=
37 /// OutBufEnd. Thus a single comparison suffices to determine if we
38 /// need to take the slow path to write a single character.
40 /// The buffer is in one of three states:
41 /// 1. Unbuffered (BufferMode == Unbuffered)
42 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
43 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
44 /// OutBufEnd - OutBufStart >= 1).
46 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
47 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
48 /// managed by the subclass.
50 /// If a subclass installs an external buffer using SetBuffer then it can wait
51 /// for a \see write_impl() call to handle the data which has been put into
53 char *OutBufStart, *OutBufEnd, *OutBufCur;
62 // color order matches ANSI escape sequence, don't change
75 explicit raw_ostream(bool unbuffered=false)
76 : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
77 // Start out ready to flush.
78 OutBufStart = OutBufEnd = OutBufCur = 0;
81 virtual ~raw_ostream();
83 /// tell - Return the current offset with the file.
84 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
86 //===--------------------------------------------------------------------===//
87 // Configuration Interface
88 //===--------------------------------------------------------------------===//
90 /// SetBuffered - Set the stream to be buffered, with an automatically
91 /// determined buffer size.
94 /// SetBufferSize - Set the stream to be buffered, using the
95 /// specified buffer size.
96 void SetBufferSize(size_t Size) {
98 SetBufferAndMode(new char[Size], Size, InternalBuffer);
101 size_t GetBufferSize() const {
102 // If we're supposed to be buffered but haven't actually gotten around
103 // to allocating the buffer yet, return the value that would be used.
104 if (BufferMode != Unbuffered && OutBufStart == 0)
105 return preferred_buffer_size();
107 // Otherwise just return the size of the allocated buffer.
108 return OutBufEnd - OutBufStart;
111 /// SetUnbuffered - Set the stream to be unbuffered. When
112 /// unbuffered, the stream will flush after every write. This routine
113 /// will also flush the buffer immediately when the stream is being
114 /// set to unbuffered.
115 void SetUnbuffered() {
117 SetBufferAndMode(0, 0, Unbuffered);
120 size_t GetNumBytesInBuffer() const {
121 return OutBufCur - OutBufStart;
124 //===--------------------------------------------------------------------===//
125 // Data Output Interface
126 //===--------------------------------------------------------------------===//
129 if (OutBufCur != OutBufStart)
133 raw_ostream &operator<<(char C) {
134 if (OutBufCur >= OutBufEnd)
140 raw_ostream &operator<<(unsigned char C) {
141 if (OutBufCur >= OutBufEnd)
147 raw_ostream &operator<<(signed char C) {
148 if (OutBufCur >= OutBufEnd)
154 raw_ostream &operator<<(StringRef Str) {
155 // Inline fast path, particularly for strings with a known length.
156 size_t Size = Str.size();
158 // Make sure we can use the fast path.
159 if (OutBufCur+Size > OutBufEnd)
160 return write(Str.data(), Size);
162 memcpy(OutBufCur, Str.data(), Size);
167 raw_ostream &operator<<(const char *Str) {
168 // Inline fast path, particularly for constant strings where a sufficiently
169 // smart compiler will simplify strlen.
171 return this->operator<<(StringRef(Str));
174 raw_ostream &operator<<(const std::string &Str) {
175 // Avoid the fast path, it would only increase code size for a marginal win.
176 return write(Str.data(), Str.length());
179 raw_ostream &operator<<(unsigned long N);
180 raw_ostream &operator<<(long N);
181 raw_ostream &operator<<(unsigned long long N);
182 raw_ostream &operator<<(long long N);
183 raw_ostream &operator<<(const void *P);
184 raw_ostream &operator<<(unsigned int N) {
185 return this->operator<<(static_cast<unsigned long>(N));
188 raw_ostream &operator<<(int N) {
189 return this->operator<<(static_cast<long>(N));
192 raw_ostream &operator<<(double N);
194 /// write_hex - Output \arg N in hexadecimal, without any prefix or padding.
195 raw_ostream &write_hex(unsigned long long N);
197 /// write_escaped - Output \arg Str, turning '\\', '\t', '\n', '"', and
198 /// anything that doesn't satisfy std::isprint into an escape sequence.
199 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
201 raw_ostream &write(unsigned char C);
202 raw_ostream &write(const char *Ptr, size_t Size);
204 // Formatted output, see the format() function in Support/Format.h.
205 raw_ostream &operator<<(const format_object_base &Fmt);
207 /// indent - Insert 'NumSpaces' spaces.
208 raw_ostream &indent(unsigned NumSpaces);
211 /// Changes the foreground color of text that will be output from this point
213 /// @param colors ANSI color to use, the special SAVEDCOLOR can be used to
214 /// change only the bold attribute, and keep colors untouched
215 /// @param bold bold/brighter text, default false
216 /// @param bg if true change the background, default: change foreground
217 /// @returns itself so it can be used within << invocations
218 virtual raw_ostream &changeColor(enum Colors, bool = false, bool = false) {
221 /// Resets the colors to terminal defaults. Call this when you are done
222 /// outputting colored text, or before program exit.
223 virtual raw_ostream &resetColor() { return *this; }
225 /// Reverses the forground and background colors.
226 virtual raw_ostream &reverseColor() { return *this; }
228 /// This function determines if this stream is connected to a "tty" or
229 /// "console" window. That is, the output would be displayed to the user
230 /// rather than being put on a pipe or stored in a file.
231 virtual bool is_displayed() const { return false; }
233 /// This function determines if this stream is displayed and supports colors.
234 virtual bool has_colors() const { return is_displayed(); }
236 //===--------------------------------------------------------------------===//
237 // Subclass Interface
238 //===--------------------------------------------------------------------===//
241 /// write_impl - The is the piece of the class that is implemented
242 /// by subclasses. This writes the \args Size bytes starting at
243 /// \arg Ptr to the underlying stream.
245 /// This function is guaranteed to only be called at a point at which it is
246 /// safe for the subclass to install a new buffer via SetBuffer.
248 /// \arg Ptr - The start of the data to be written. For buffered streams this
249 /// is guaranteed to be the start of the buffer.
250 /// \arg Size - The number of bytes to be written.
252 /// \invariant { Size > 0 }
253 virtual void write_impl(const char *Ptr, size_t Size) = 0;
255 // An out of line virtual method to provide a home for the class vtable.
256 virtual void handle();
258 /// current_pos - Return the current position within the stream, not
259 /// counting the bytes currently in the buffer.
260 virtual uint64_t current_pos() const = 0;
263 /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is
264 /// intended for use only by subclasses which can arrange for the output to go
265 /// directly into the desired output buffer, instead of being copied on each
267 void SetBuffer(char *BufferStart, size_t Size) {
268 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
271 /// preferred_buffer_size - Return an efficient buffer size for the
272 /// underlying output mechanism.
273 virtual size_t preferred_buffer_size() const;
275 /// getBufferStart - Return the beginning of the current stream buffer, or 0
276 /// if the stream is unbuffered.
277 const char *getBufferStart() const { return OutBufStart; }
279 //===--------------------------------------------------------------------===//
281 //===--------------------------------------------------------------------===//
283 /// SetBufferAndMode - Install the given buffer and mode.
284 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
286 /// flush_nonempty - Flush the current buffer, which is known to be
287 /// non-empty. This outputs the currently buffered data and resets
288 /// the buffer to empty.
289 void flush_nonempty();
291 /// copy_to_buffer - Copy data into the buffer. Size must not be
292 /// greater than the number of unused bytes in the buffer.
293 void copy_to_buffer(const char *Ptr, size_t Size);
296 //===----------------------------------------------------------------------===//
297 // File Output Streams
298 //===----------------------------------------------------------------------===//
300 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
302 class raw_fd_ostream : public raw_ostream {
306 /// Error This flag is true if an error of any kind has been detected.
310 /// Controls whether the stream should attempt to use atomic writes, when
312 bool UseAtomicWrites;
316 /// write_impl - See raw_ostream::write_impl.
317 virtual void write_impl(const char *Ptr, size_t Size);
319 /// current_pos - Return the current position within the stream, not
320 /// counting the bytes currently in the buffer.
321 virtual uint64_t current_pos() const { return pos; }
323 /// preferred_buffer_size - Determine an efficient buffer size.
324 virtual size_t preferred_buffer_size() const;
326 /// error_detected - Set the flag indicating that an output error has
327 /// been encountered.
328 void error_detected() { Error = true; }
333 /// F_Excl - When opening a file, this flag makes raw_fd_ostream
334 /// report an error if the file already exists.
337 /// F_Append - When opening a file, if it already exists append to the
338 /// existing file instead of returning an error. This may not be specified
342 /// F_Binary - The file should be opened in binary mode on platforms that
343 /// make this distinction.
347 /// raw_fd_ostream - Open the specified file for writing. If an error occurs,
348 /// information about the error is put into ErrorInfo, and the stream should
349 /// be immediately destroyed; the string will be empty if no error occurred.
350 /// This allows optional flags to control how the file will be opened.
352 /// As a special case, if Filename is "-", then the stream will use
353 /// STDOUT_FILENO instead of opening a file. Note that it will still consider
354 /// itself to own the file descriptor. In particular, it will close the
355 /// file descriptor when it is done (this is necessary to detect
357 raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
360 /// raw_fd_ostream ctor - FD is the file descriptor that this writes to. If
361 /// ShouldClose is true, this closes the file when the stream is destroyed.
362 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
366 /// close - Manually flush the stream and close the file.
367 /// Note that this does not call fsync.
370 /// seek - Flushes the stream and repositions the underlying file descriptor
371 /// position to the offset specified from the beginning of the file.
372 uint64_t seek(uint64_t off);
374 /// SetUseAtomicWrite - Set the stream to attempt to use atomic writes for
375 /// individual output routines where possible.
377 /// Note that because raw_ostream's are typically buffered, this flag is only
378 /// sensible when used on unbuffered streams which will flush their output
380 void SetUseAtomicWrites(bool Value) {
381 UseAtomicWrites = Value;
384 virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
386 virtual raw_ostream &resetColor();
388 virtual raw_ostream &reverseColor();
390 virtual bool is_displayed() const;
392 virtual bool has_colors() const;
394 /// has_error - Return the value of the flag in this raw_fd_ostream indicating
395 /// whether an output error has been encountered.
396 /// This doesn't implicitly flush any pending output. Also, it doesn't
397 /// guarantee to detect all errors unless the stream has been closed.
398 bool has_error() const {
402 /// clear_error - Set the flag read by has_error() to false. If the error
403 /// flag is set at the time when this raw_ostream's destructor is called,
404 /// report_fatal_error is called to report the error. Use clear_error()
405 /// after handling the error to avoid this behavior.
407 /// "Errors should never pass silently.
408 /// Unless explicitly silenced."
409 /// - from The Zen of Python, by Tim Peters
416 /// outs() - This returns a reference to a raw_ostream for standard output.
417 /// Use it like: outs() << "foo" << "bar";
420 /// errs() - This returns a reference to a raw_ostream for standard error.
421 /// Use it like: errs() << "foo" << "bar";
424 /// nulls() - This returns a reference to a raw_ostream which simply discards
426 raw_ostream &nulls();
428 //===----------------------------------------------------------------------===//
429 // Output Stream Adaptors
430 //===----------------------------------------------------------------------===//
432 /// raw_string_ostream - A raw_ostream that writes to an std::string. This is a
433 /// simple adaptor class. This class does not encounter output errors.
434 class raw_string_ostream : public raw_ostream {
437 /// write_impl - See raw_ostream::write_impl.
438 virtual void write_impl(const char *Ptr, size_t Size);
440 /// current_pos - Return the current position within the stream, not
441 /// counting the bytes currently in the buffer.
442 virtual uint64_t current_pos() const { return OS.size(); }
444 explicit raw_string_ostream(std::string &O) : OS(O) {}
445 ~raw_string_ostream();
447 /// str - Flushes the stream contents to the target string and returns
448 /// the string's reference.
455 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
456 /// SmallString. This is a simple adaptor class. This class does not
457 /// encounter output errors.
458 class raw_svector_ostream : public raw_ostream {
459 SmallVectorImpl<char> &OS;
461 /// write_impl - See raw_ostream::write_impl.
462 virtual void write_impl(const char *Ptr, size_t Size);
464 /// current_pos - Return the current position within the stream, not
465 /// counting the bytes currently in the buffer.
466 virtual uint64_t current_pos() const;
468 /// Construct a new raw_svector_ostream.
470 /// \arg O - The vector to write to; this should generally have at least 128
471 /// bytes free to avoid any extraneous memory overhead.
472 explicit raw_svector_ostream(SmallVectorImpl<char> &O);
473 ~raw_svector_ostream();
475 /// resync - This is called when the SmallVector we're appending to is changed
476 /// outside of the raw_svector_ostream's control. It is only safe to do this
477 /// if the raw_svector_ostream has previously been flushed.
480 /// str - Flushes the stream contents to the target vector and return a
481 /// StringRef for the vector contents.
485 /// raw_null_ostream - A raw_ostream that discards all output.
486 class raw_null_ostream : public raw_ostream {
487 /// write_impl - See raw_ostream::write_impl.
488 virtual void write_impl(const char *Ptr, size_t size);
490 /// current_pos - Return the current position within the stream, not
491 /// counting the bytes currently in the buffer.
492 virtual uint64_t current_pos() const;
495 explicit raw_null_ostream() {}
499 } // end llvm namespace