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"
22 class format_object_base;
24 class SmallVectorImpl;
26 /// raw_ostream - This class implements an extremely fast bulk output stream
27 /// that can *only* output to a stream. It does not support seeking, reopening,
28 /// rewinding, line buffered disciplines etc. It is a simple buffer that outputs
29 /// a chunk at a time.
32 // Do not implement. raw_ostream is noncopyable.
33 void operator=(const raw_ostream &) LLVM_DELETED_FUNCTION;
34 raw_ostream(const raw_ostream &) LLVM_DELETED_FUNCTION;
36 /// The buffer is handled in such a way that the buffer is
37 /// uninitialized, unbuffered, or out of space when OutBufCur >=
38 /// OutBufEnd. Thus a single comparison suffices to determine if we
39 /// need to take the slow path to write a single character.
41 /// The buffer is in one of three states:
42 /// 1. Unbuffered (BufferMode == Unbuffered)
43 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
44 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
45 /// OutBufEnd - OutBufStart >= 1).
47 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
48 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
49 /// managed by the subclass.
51 /// If a subclass installs an external buffer using SetBuffer then it can wait
52 /// for a \see write_impl() call to handle the data which has been put into
54 char *OutBufStart, *OutBufEnd, *OutBufCur;
63 // color order matches ANSI escape sequence, don't change
76 explicit raw_ostream(bool unbuffered=false)
77 : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
78 // Start out ready to flush.
79 OutBufStart = OutBufEnd = OutBufCur = 0;
82 virtual ~raw_ostream();
84 /// tell - Return the current offset with the file.
85 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
87 //===--------------------------------------------------------------------===//
88 // Configuration Interface
89 //===--------------------------------------------------------------------===//
91 /// SetBuffered - Set the stream to be buffered, with an automatically
92 /// determined buffer size.
95 /// SetBufferSize - Set the stream to be buffered, using the
96 /// specified buffer size.
97 void SetBufferSize(size_t Size) {
99 SetBufferAndMode(new char[Size], Size, InternalBuffer);
102 size_t GetBufferSize() const {
103 // If we're supposed to be buffered but haven't actually gotten around
104 // to allocating the buffer yet, return the value that would be used.
105 if (BufferMode != Unbuffered && OutBufStart == 0)
106 return preferred_buffer_size();
108 // Otherwise just return the size of the allocated buffer.
109 return OutBufEnd - OutBufStart;
112 /// SetUnbuffered - Set the stream to be unbuffered. When
113 /// unbuffered, the stream will flush after every write. This routine
114 /// will also flush the buffer immediately when the stream is being
115 /// set to unbuffered.
116 void SetUnbuffered() {
118 SetBufferAndMode(0, 0, Unbuffered);
121 size_t GetNumBytesInBuffer() const {
122 return OutBufCur - OutBufStart;
125 //===--------------------------------------------------------------------===//
126 // Data Output Interface
127 //===--------------------------------------------------------------------===//
130 if (OutBufCur != OutBufStart)
134 raw_ostream &operator<<(char C) {
135 if (OutBufCur >= OutBufEnd)
141 raw_ostream &operator<<(unsigned char C) {
142 if (OutBufCur >= OutBufEnd)
148 raw_ostream &operator<<(signed char C) {
149 if (OutBufCur >= OutBufEnd)
155 raw_ostream &operator<<(StringRef Str) {
156 // Inline fast path, particularly for strings with a known length.
157 size_t Size = Str.size();
159 // Make sure we can use the fast path.
160 if (OutBufCur+Size > OutBufEnd)
161 return write(Str.data(), Size);
163 memcpy(OutBufCur, Str.data(), Size);
168 raw_ostream &operator<<(const char *Str) {
169 // Inline fast path, particularly for constant strings where a sufficiently
170 // smart compiler will simplify strlen.
172 return this->operator<<(StringRef(Str));
175 raw_ostream &operator<<(const std::string &Str) {
176 // Avoid the fast path, it would only increase code size for a marginal win.
177 return write(Str.data(), Str.length());
180 raw_ostream &operator<<(unsigned long N);
181 raw_ostream &operator<<(long N);
182 raw_ostream &operator<<(unsigned long long N);
183 raw_ostream &operator<<(long long N);
184 raw_ostream &operator<<(const void *P);
185 raw_ostream &operator<<(unsigned int N) {
186 return this->operator<<(static_cast<unsigned long>(N));
189 raw_ostream &operator<<(int N) {
190 return this->operator<<(static_cast<long>(N));
193 raw_ostream &operator<<(double N);
195 /// write_hex - Output \p N in hexadecimal, without any prefix or padding.
196 raw_ostream &write_hex(unsigned long long N);
198 /// write_escaped - Output \p Str, turning '\\', '\t', '\n', '"', and
199 /// anything that doesn't satisfy std::isprint into an escape sequence.
200 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
202 raw_ostream &write(unsigned char C);
203 raw_ostream &write(const char *Ptr, size_t Size);
205 // Formatted output, see the format() function in Support/Format.h.
206 raw_ostream &operator<<(const format_object_base &Fmt);
208 /// indent - Insert 'NumSpaces' spaces.
209 raw_ostream &indent(unsigned NumSpaces);
212 /// Changes the foreground color of text that will be output from this point
214 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
215 /// change only the bold attribute, and keep colors untouched
216 /// @param Bold bold/brighter text, default false
217 /// @param BG if true change the background, default: change foreground
218 /// @returns itself so it can be used within << invocations
219 virtual raw_ostream &changeColor(enum Colors Color,
228 /// Resets the colors to terminal defaults. Call this when you are done
229 /// outputting colored text, or before program exit.
230 virtual raw_ostream &resetColor() { return *this; }
232 /// Reverses the forground and background colors.
233 virtual raw_ostream &reverseColor() { return *this; }
235 /// This function determines if this stream is connected to a "tty" or
236 /// "console" window. That is, the output would be displayed to the user
237 /// rather than being put on a pipe or stored in a file.
238 virtual bool is_displayed() const { return false; }
240 /// This function determines if this stream is displayed and supports colors.
241 virtual bool has_colors() const { return is_displayed(); }
243 //===--------------------------------------------------------------------===//
244 // Subclass Interface
245 //===--------------------------------------------------------------------===//
248 /// write_impl - The is the piece of the class that is implemented
249 /// by subclasses. This writes the \p Size bytes starting at
250 /// \p Ptr to the underlying stream.
252 /// This function is guaranteed to only be called at a point at which it is
253 /// safe for the subclass to install a new buffer via SetBuffer.
255 /// \param Ptr The start of the data to be written. For buffered streams this
256 /// is guaranteed to be the start of the buffer.
258 /// \param Size The number of bytes to be written.
260 /// \invariant { Size > 0 }
261 virtual void write_impl(const char *Ptr, size_t Size) = 0;
263 // An out of line virtual method to provide a home for the class vtable.
264 virtual void handle();
266 /// current_pos - Return the current position within the stream, not
267 /// counting the bytes currently in the buffer.
268 virtual uint64_t current_pos() const = 0;
271 /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is
272 /// intended for use only by subclasses which can arrange for the output to go
273 /// directly into the desired output buffer, instead of being copied on each
275 void SetBuffer(char *BufferStart, size_t Size) {
276 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
279 /// preferred_buffer_size - Return an efficient buffer size for the
280 /// underlying output mechanism.
281 virtual size_t preferred_buffer_size() const;
283 /// getBufferStart - Return the beginning of the current stream buffer, or 0
284 /// if the stream is unbuffered.
285 const char *getBufferStart() const { return OutBufStart; }
287 //===--------------------------------------------------------------------===//
289 //===--------------------------------------------------------------------===//
291 /// SetBufferAndMode - Install the given buffer and mode.
292 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
294 /// flush_nonempty - Flush the current buffer, which is known to be
295 /// non-empty. This outputs the currently buffered data and resets
296 /// the buffer to empty.
297 void flush_nonempty();
299 /// copy_to_buffer - Copy data into the buffer. Size must not be
300 /// greater than the number of unused bytes in the buffer.
301 void copy_to_buffer(const char *Ptr, size_t Size);
304 //===----------------------------------------------------------------------===//
305 // File Output Streams
306 //===----------------------------------------------------------------------===//
308 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
310 class raw_fd_ostream : public raw_ostream {
314 /// Error This flag is true if an error of any kind has been detected.
318 /// Controls whether the stream should attempt to use atomic writes, when
320 bool UseAtomicWrites;
324 /// write_impl - See raw_ostream::write_impl.
325 virtual void write_impl(const char *Ptr, size_t Size) LLVM_OVERRIDE;
327 /// current_pos - Return the current position within the stream, not
328 /// counting the bytes currently in the buffer.
329 virtual uint64_t current_pos() const LLVM_OVERRIDE { return pos; }
331 /// preferred_buffer_size - Determine an efficient buffer size.
332 virtual size_t preferred_buffer_size() const LLVM_OVERRIDE;
334 /// error_detected - Set the flag indicating that an output error has
335 /// been encountered.
336 void error_detected() { Error = true; }
341 /// F_Excl - When opening a file, this flag makes raw_fd_ostream
342 /// report an error if the file already exists.
345 /// F_Append - When opening a file, if it already exists append to the
346 /// existing file instead of returning an error. This may not be specified
350 /// F_Binary - The file should be opened in binary mode on platforms that
351 /// make this distinction.
355 /// raw_fd_ostream - Open the specified file for writing. If an error occurs,
356 /// information about the error is put into ErrorInfo, and the stream should
357 /// be immediately destroyed; the string will be empty if no error occurred.
358 /// This allows optional flags to control how the file will be opened.
360 /// As a special case, if Filename is "-", then the stream will use
361 /// STDOUT_FILENO instead of opening a file. Note that it will still consider
362 /// itself to own the file descriptor. In particular, it will close the
363 /// file descriptor when it is done (this is necessary to detect
365 raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
368 /// raw_fd_ostream ctor - FD is the file descriptor that this writes to. If
369 /// ShouldClose is true, this closes the file when the stream is destroyed.
370 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
374 /// close - Manually flush the stream and close the file.
375 /// Note that this does not call fsync.
378 /// seek - Flushes the stream and repositions the underlying file descriptor
379 /// position to the offset specified from the beginning of the file.
380 uint64_t seek(uint64_t off);
382 /// SetUseAtomicWrite - Set the stream to attempt to use atomic writes for
383 /// individual output routines where possible.
385 /// Note that because raw_ostream's are typically buffered, this flag is only
386 /// sensible when used on unbuffered streams which will flush their output
388 void SetUseAtomicWrites(bool Value) {
389 UseAtomicWrites = Value;
392 virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
393 bool bg=false) LLVM_OVERRIDE;
394 virtual raw_ostream &resetColor() LLVM_OVERRIDE;
396 virtual raw_ostream &reverseColor() LLVM_OVERRIDE;
398 virtual bool is_displayed() const LLVM_OVERRIDE;
400 virtual bool has_colors() const LLVM_OVERRIDE;
402 /// has_error - Return the value of the flag in this raw_fd_ostream indicating
403 /// whether an output error has been encountered.
404 /// This doesn't implicitly flush any pending output. Also, it doesn't
405 /// guarantee to detect all errors unless the stream has been closed.
406 bool has_error() const {
410 /// clear_error - Set the flag read by has_error() to false. If the error
411 /// flag is set at the time when this raw_ostream's destructor is called,
412 /// report_fatal_error is called to report the error. Use clear_error()
413 /// after handling the error to avoid this behavior.
415 /// "Errors should never pass silently.
416 /// Unless explicitly silenced."
417 /// - from The Zen of Python, by Tim Peters
424 /// outs() - This returns a reference to a raw_ostream for standard output.
425 /// Use it like: outs() << "foo" << "bar";
428 /// errs() - This returns a reference to a raw_ostream for standard error.
429 /// Use it like: errs() << "foo" << "bar";
432 /// nulls() - This returns a reference to a raw_ostream which simply discards
434 raw_ostream &nulls();
436 //===----------------------------------------------------------------------===//
437 // Output Stream Adaptors
438 //===----------------------------------------------------------------------===//
440 /// raw_string_ostream - A raw_ostream that writes to an std::string. This is a
441 /// simple adaptor class. This class does not encounter output errors.
442 class raw_string_ostream : public raw_ostream {
445 /// write_impl - See raw_ostream::write_impl.
446 virtual void write_impl(const char *Ptr, size_t Size) LLVM_OVERRIDE;
448 /// current_pos - Return the current position within the stream, not
449 /// counting the bytes currently in the buffer.
450 virtual uint64_t current_pos() const LLVM_OVERRIDE { return OS.size(); }
452 explicit raw_string_ostream(std::string &O) : OS(O) {}
453 ~raw_string_ostream();
455 /// str - Flushes the stream contents to the target string and returns
456 /// the string's reference.
463 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
464 /// SmallString. This is a simple adaptor class. This class does not
465 /// encounter output errors.
466 class raw_svector_ostream : public raw_ostream {
467 SmallVectorImpl<char> &OS;
469 /// write_impl - See raw_ostream::write_impl.
470 virtual void write_impl(const char *Ptr, size_t Size) LLVM_OVERRIDE;
472 /// current_pos - Return the current position within the stream, not
473 /// counting the bytes currently in the buffer.
474 virtual uint64_t current_pos() const LLVM_OVERRIDE;
476 /// Construct a new raw_svector_ostream.
478 /// \param O The vector to write to; this should generally have at least 128
479 /// bytes free to avoid any extraneous memory overhead.
480 explicit raw_svector_ostream(SmallVectorImpl<char> &O);
481 ~raw_svector_ostream();
483 /// resync - This is called when the SmallVector we're appending to is changed
484 /// outside of the raw_svector_ostream's control. It is only safe to do this
485 /// if the raw_svector_ostream has previously been flushed.
488 /// str - Flushes the stream contents to the target vector and return a
489 /// StringRef for the vector contents.
493 /// raw_null_ostream - A raw_ostream that discards all output.
494 class raw_null_ostream : public raw_ostream {
495 /// write_impl - See raw_ostream::write_impl.
496 virtual void write_impl(const char *Ptr, size_t size) LLVM_OVERRIDE;
498 /// current_pos - Return the current position within the stream, not
499 /// counting the bytes currently in the buffer.
500 virtual uint64_t current_pos() const LLVM_OVERRIDE;
503 explicit raw_null_ostream() {}
507 } // end llvm namespace