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/System/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;
61 /// Error This flag is true if an error of any kind has been detected.
66 // color order matches ANSI escape sequence, don't change
79 explicit raw_ostream(bool unbuffered=false)
80 : BufferMode(unbuffered ? Unbuffered : InternalBuffer), Error(false) {
81 // Start out ready to flush.
82 OutBufStart = OutBufEnd = OutBufCur = 0;
85 virtual ~raw_ostream();
87 /// tell - Return the current offset with the file.
88 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
90 /// has_error - Return the value of the flag in this raw_ostream indicating
91 /// whether an output error has been encountered.
92 bool has_error() const {
96 /// clear_error - Set the flag read by has_error() to false. If the error
97 /// flag is set at the time when this raw_ostream's destructor is called,
98 /// llvm_report_error is called to report the error. Use clear_error()
99 /// after handling the error to avoid this behavior.
104 //===--------------------------------------------------------------------===//
105 // Configuration Interface
106 //===--------------------------------------------------------------------===//
108 /// SetBuffered - Set the stream to be buffered, with an automatically
109 /// determined buffer size.
112 /// SetBufferSize - Set the stream to be buffered, using the
113 /// specified buffer size.
114 void SetBufferSize(size_t Size) {
116 SetBufferAndMode(new char[Size], Size, InternalBuffer);
119 size_t GetBufferSize() const {
120 // If we're supposed to be buffered but haven't actually gotten around
121 // to allocating the buffer yet, return the value that would be used.
122 if (BufferMode != Unbuffered && OutBufStart == 0)
123 return preferred_buffer_size();
125 // Otherwise just return the size of the allocated buffer.
126 return OutBufEnd - OutBufStart;
129 /// SetUnbuffered - Set the stream to be unbuffered. When
130 /// unbuffered, the stream will flush after every write. This routine
131 /// will also flush the buffer immediately when the stream is being
132 /// set to unbuffered.
133 void SetUnbuffered() {
135 SetBufferAndMode(0, 0, Unbuffered);
138 size_t GetNumBytesInBuffer() const {
139 return OutBufCur - OutBufStart;
142 //===--------------------------------------------------------------------===//
143 // Data Output Interface
144 //===--------------------------------------------------------------------===//
147 if (OutBufCur != OutBufStart)
151 raw_ostream &operator<<(char C) {
152 if (OutBufCur >= OutBufEnd)
158 raw_ostream &operator<<(unsigned char C) {
159 if (OutBufCur >= OutBufEnd)
165 raw_ostream &operator<<(signed char C) {
166 if (OutBufCur >= OutBufEnd)
172 raw_ostream &operator<<(StringRef Str) {
173 // Inline fast path, particularly for strings with a known length.
174 size_t Size = Str.size();
176 // Make sure we can use the fast path.
177 if (OutBufCur+Size > OutBufEnd)
178 return write(Str.data(), Size);
180 memcpy(OutBufCur, Str.data(), Size);
185 raw_ostream &operator<<(const char *Str) {
186 // Inline fast path, particulary for constant strings where a sufficiently
187 // smart compiler will simplify strlen.
189 return this->operator<<(StringRef(Str));
192 raw_ostream &operator<<(const std::string &Str) {
193 // Avoid the fast path, it would only increase code size for a marginal win.
194 return write(Str.data(), Str.length());
197 raw_ostream &operator<<(unsigned long N);
198 raw_ostream &operator<<(long N);
199 raw_ostream &operator<<(unsigned long long N);
200 raw_ostream &operator<<(long long N);
201 raw_ostream &operator<<(const void *P);
202 raw_ostream &operator<<(unsigned int N) {
203 return this->operator<<(static_cast<unsigned long>(N));
206 raw_ostream &operator<<(int N) {
207 return this->operator<<(static_cast<long>(N));
210 raw_ostream &operator<<(double N);
212 /// write_hex - Output \arg N in hexadecimal, without any prefix or padding.
213 raw_ostream &write_hex(unsigned long long N);
215 /// write_escaped - Output \arg Str, turning '\\', '\t', '\n', '"', and
216 /// anything that doesn't satisfy std::isprint into an escape sequence.
217 raw_ostream &write_escaped(StringRef Str);
219 raw_ostream &write(unsigned char C);
220 raw_ostream &write(const char *Ptr, size_t Size);
222 // Formatted output, see the format() function in Support/Format.h.
223 raw_ostream &operator<<(const format_object_base &Fmt);
225 /// indent - Insert 'NumSpaces' spaces.
226 raw_ostream &indent(unsigned NumSpaces);
229 /// Changes the foreground color of text that will be output from this point
231 /// @param colors ANSI color to use, the special SAVEDCOLOR can be used to
232 /// change only the bold attribute, and keep colors untouched
233 /// @param bold bold/brighter text, default false
234 /// @param bg if true change the background, default: change foreground
235 /// @returns itself so it can be used within << invocations
236 virtual raw_ostream &changeColor(enum Colors, bool = false,
237 bool = false) { return *this; }
239 /// Resets the colors to terminal defaults. Call this when you are done
240 /// outputting colored text, or before program exit.
241 virtual raw_ostream &resetColor() { return *this; }
243 /// This function determines if this stream is connected to a "tty" or
244 /// "console" window. That is, the output would be displayed to the user
245 /// rather than being put on a pipe or stored in a file.
246 virtual bool is_displayed() const { return false; }
248 //===--------------------------------------------------------------------===//
249 // Subclass Interface
250 //===--------------------------------------------------------------------===//
253 /// write_impl - The is the piece of the class that is implemented
254 /// by subclasses. This writes the \args Size bytes starting at
255 /// \arg Ptr to the underlying stream.
257 /// This function is guaranteed to only be called at a point at which it is
258 /// safe for the subclass to install a new buffer via SetBuffer.
260 /// \arg Ptr - The start of the data to be written. For buffered streams this
261 /// is guaranteed to be the start of the buffer.
262 /// \arg Size - The number of bytes to be written.
264 /// \invariant { Size > 0 }
265 virtual void write_impl(const char *Ptr, size_t Size) = 0;
267 // An out of line virtual method to provide a home for the class vtable.
268 virtual void handle();
270 /// current_pos - Return the current position within the stream, not
271 /// counting the bytes currently in the buffer.
272 virtual uint64_t current_pos() const = 0;
275 /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is
276 /// intended for use only by subclasses which can arrange for the output to go
277 /// directly into the desired output buffer, instead of being copied on each
279 void SetBuffer(char *BufferStart, size_t Size) {
280 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
283 /// preferred_buffer_size - Return an efficient buffer size for the
284 /// underlying output mechanism.
285 virtual size_t preferred_buffer_size() const;
287 /// error_detected - Set the flag indicating that an output error has
288 /// been encountered.
289 void error_detected() { Error = true; }
291 /// getBufferStart - Return the beginning of the current stream buffer, or 0
292 /// if the stream is unbuffered.
293 const char *getBufferStart() const { return OutBufStart; }
295 //===--------------------------------------------------------------------===//
297 //===--------------------------------------------------------------------===//
299 /// SetBufferAndMode - Install the given buffer and mode.
300 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
302 /// flush_nonempty - Flush the current buffer, which is known to be
303 /// non-empty. This outputs the currently buffered data and resets
304 /// the buffer to empty.
305 void flush_nonempty();
307 /// copy_to_buffer - Copy data into the buffer. Size must not be
308 /// greater than the number of unused bytes in the buffer.
309 void copy_to_buffer(const char *Ptr, size_t Size);
312 //===----------------------------------------------------------------------===//
313 // File Output Streams
314 //===----------------------------------------------------------------------===//
316 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
318 class raw_fd_ostream : public raw_ostream {
323 /// write_impl - See raw_ostream::write_impl.
324 virtual void write_impl(const char *Ptr, size_t Size);
326 /// current_pos - Return the current position within the stream, not
327 /// counting the bytes currently in the buffer.
328 virtual uint64_t current_pos() const { return pos; }
330 /// preferred_buffer_size - Determine an efficient buffer size.
331 virtual size_t preferred_buffer_size() const;
336 /// F_Excl - When opening a file, this flag makes raw_fd_ostream
337 /// report an error if the file already exists.
340 /// F_Append - When opening a file, if it already exists append to the
341 /// existing file instead of returning an error. This may not be specified
345 /// F_Binary - The file should be opened in binary mode on platforms that
346 /// make this distinction.
350 /// raw_fd_ostream - Open the specified file for writing. If an error occurs,
351 /// information about the error is put into ErrorInfo, and the stream should
352 /// be immediately destroyed; the string will be empty if no error occurred.
353 /// This allows optional flags to control how the file will be opened.
355 /// \param Filename - The file to open. If this is "-" then the
356 /// stream will use stdout instead.
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,
363 bool unbuffered=false) : raw_ostream(unbuffered), FD(fd),
364 ShouldClose(shouldClose) {}
368 /// close - Manually flush the stream and close the file.
371 /// seek - Flushes the stream and repositions the underlying file descriptor
372 /// positition to the offset specified from the beginning of the file.
373 uint64_t seek(uint64_t off);
375 virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
377 virtual raw_ostream &resetColor();
379 virtual bool is_displayed() const;
382 /// raw_stdout_ostream - This is a stream that always prints to stdout.
384 class raw_stdout_ostream : public raw_fd_ostream {
385 // An out of line virtual method to provide a home for the class vtable.
386 virtual void handle();
388 raw_stdout_ostream();
391 /// raw_stderr_ostream - This is a stream that always prints to stderr.
393 class raw_stderr_ostream : public raw_fd_ostream {
394 // An out of line virtual method to provide a home for the class vtable.
395 virtual void handle();
397 raw_stderr_ostream();
400 /// outs() - This returns a reference to a raw_ostream for standard output.
401 /// Use it like: outs() << "foo" << "bar";
404 /// errs() - This returns a reference to a raw_ostream for standard error.
405 /// Use it like: errs() << "foo" << "bar";
408 /// nulls() - This returns a reference to a raw_ostream which simply discards
410 raw_ostream &nulls();
412 //===----------------------------------------------------------------------===//
413 // Output Stream Adaptors
414 //===----------------------------------------------------------------------===//
416 /// raw_string_ostream - A raw_ostream that writes to an std::string. This is a
417 /// simple adaptor class. This class does not encounter output errors.
418 class raw_string_ostream : public raw_ostream {
421 /// write_impl - See raw_ostream::write_impl.
422 virtual void write_impl(const char *Ptr, size_t Size);
424 /// current_pos - Return the current position within the stream, not
425 /// counting the bytes currently in the buffer.
426 virtual uint64_t current_pos() const { return OS.size(); }
428 explicit raw_string_ostream(std::string &O) : OS(O) {}
429 ~raw_string_ostream();
431 /// str - Flushes the stream contents to the target string and returns
432 /// the string's reference.
439 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
440 /// SmallString. This is a simple adaptor class. This class does not
441 /// encounter output errors.
442 class raw_svector_ostream : public raw_ostream {
443 SmallVectorImpl<char> &OS;
445 /// write_impl - See raw_ostream::write_impl.
446 virtual void write_impl(const char *Ptr, size_t Size);
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;
452 /// Construct a new raw_svector_ostream.
454 /// \arg O - The vector to write to; this should generally have at least 128
455 /// bytes free to avoid any extraneous memory overhead.
456 explicit raw_svector_ostream(SmallVectorImpl<char> &O);
457 ~raw_svector_ostream();
459 /// str - Flushes the stream contents to the target vector and return a
460 /// StringRef for the vector contents.
464 /// raw_null_ostream - A raw_ostream that discards all output.
465 class raw_null_ostream : public raw_ostream {
466 /// write_impl - See raw_ostream::write_impl.
467 virtual void write_impl(const char *Ptr, size_t size);
469 /// current_pos - Return the current position within the stream, not
470 /// counting the bytes currently in the buffer.
471 virtual uint64_t current_pos() const;
474 explicit raw_null_ostream() {}
478 } // end llvm namespace