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/StringExtras.h"
18 #include "llvm/ADT/StringRef.h"
25 class format_object_base;
27 class SmallVectorImpl;
29 /// raw_ostream - This class implements an extremely fast bulk output stream
30 /// that can *only* output to a stream. It does not support seeking, reopening,
31 /// rewinding, line buffered disciplines etc. It is a simple buffer that outputs
32 /// a chunk at a time.
35 // Do not implement. raw_ostream is noncopyable.
36 void operator=(const raw_ostream &);
37 raw_ostream(const raw_ostream &);
39 /// The buffer is handled in such a way that the buffer is
40 /// uninitialized, unbuffered, or out of space when OutBufCur >=
41 /// OutBufEnd. Thus a single comparison suffices to determine if we
42 /// need to take the slow path to write a single character.
44 /// The buffer is in one of three states:
45 /// 1. Unbuffered (BufferMode == Unbuffered)
46 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
47 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
48 /// OutBufEnd - OutBufStart >= 64).
50 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
51 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
52 /// managed by the subclass.
54 /// If a subclass installs an external buffer using SetBuffer then it can wait
55 /// for a \see write_impl() call to handle the data which has been put into
57 char *OutBufStart, *OutBufEnd, *OutBufCur;
65 /// Error This flag is true if an error of any kind has been detected.
70 // color order matches ANSI escape sequence, don't change
83 explicit raw_ostream(bool unbuffered=false)
84 : BufferMode(unbuffered ? Unbuffered : InternalBuffer), Error(false) {
85 // Start out ready to flush.
86 OutBufStart = OutBufEnd = OutBufCur = 0;
89 virtual ~raw_ostream();
91 /// tell - Return the current offset with the file.
92 uint64_t tell() { return current_pos() + GetNumBytesInBuffer(); }
94 /// has_error - Return the value of the flag in this raw_ostream indicating
95 /// whether an output error has been encountered.
96 bool has_error() const {
100 /// clear_error - Set the flag read by has_error() to false. If the error
101 /// flag is set at the time when this raw_ostream's destructor is called,
102 /// llvm_report_error is called to report the error. Use clear_error()
103 /// after handling the error to avoid this behavior.
108 //===--------------------------------------------------------------------===//
109 // Configuration Interface
110 //===--------------------------------------------------------------------===//
112 /// SetBuffered - Set the stream to be buffered, with an automatically
113 /// determined buffer size.
116 /// SetBufferSize - Set the stream to be buffered, using the
117 /// specified buffer size.
118 void SetBufferSize(size_t Size) {
120 SetBufferAndMode(new char[Size], Size, InternalBuffer);
123 size_t GetBufferSize() {
124 // If we're supposed to be buffered but haven't actually gotten around
125 // to allocating the buffer yet, return the value that would be used.
126 if (BufferMode != Unbuffered && OutBufStart == 0)
127 return preferred_buffer_size();
129 // Otherwise just return the size of the allocated buffer.
130 return OutBufEnd - OutBufStart;
133 /// SetUnbuffered - Set the stream to be unbuffered. When
134 /// unbuffered, the stream will flush after every write. This routine
135 /// will also flush the buffer immediately when the stream is being
136 /// set to unbuffered.
137 void SetUnbuffered() {
139 SetBufferAndMode(0, 0, Unbuffered);
142 size_t GetNumBytesInBuffer() const {
143 return OutBufCur - OutBufStart;
146 //===--------------------------------------------------------------------===//
147 // Data Output Interface
148 //===--------------------------------------------------------------------===//
151 if (OutBufCur != OutBufStart)
155 raw_ostream &operator<<(char C) {
156 if (OutBufCur >= OutBufEnd)
162 raw_ostream &operator<<(unsigned char C) {
163 if (OutBufCur >= OutBufEnd)
169 raw_ostream &operator<<(signed char C) {
170 if (OutBufCur >= OutBufEnd)
176 raw_ostream &operator<<(const StringRef &Str) {
177 // Inline fast path, particularly for strings with a known length.
178 size_t Size = Str.size();
180 // Make sure we can use the fast path.
181 if (OutBufCur+Size > OutBufEnd)
182 return write(Str.data(), Size);
184 memcpy(OutBufCur, Str.data(), Size);
189 raw_ostream &operator<<(const char *Str) {
190 // Inline fast path, particulary for constant strings where a sufficiently
191 // smart compiler will simplify strlen.
193 this->operator<<(StringRef(Str));
197 raw_ostream &operator<<(const std::string &Str) {
198 // Avoid the fast path, it would only increase code size for a marginal win.
200 write(Str.data(), Str.length());
204 raw_ostream &operator<<(unsigned long N);
205 raw_ostream &operator<<(long N);
206 raw_ostream &operator<<(unsigned long long N);
207 raw_ostream &operator<<(long long N);
208 raw_ostream &operator<<(const void *P);
209 raw_ostream &operator<<(unsigned int N) {
210 this->operator<<(static_cast<unsigned long>(N));
214 raw_ostream &operator<<(int N) {
215 this->operator<<(static_cast<long>(N));
219 raw_ostream &operator<<(double N) {
220 this->operator<<(ftostr(N));
224 /// write_hex - Output \arg N in hexadecimal, without any prefix or padding.
225 raw_ostream &write_hex(unsigned long long N);
227 raw_ostream &write(unsigned char C);
228 raw_ostream &write(const char *Ptr, size_t Size);
230 // Formatted output, see the format() function in Support/Format.h.
231 raw_ostream &operator<<(const format_object_base &Fmt);
233 /// indent - Insert 'NumSpaces' spaces.
234 raw_ostream &indent(unsigned NumSpaces);
237 /// Changes the foreground color of text that will be output from this point
239 /// @param colors ANSI color to use, the special SAVEDCOLOR can be used to
240 /// change only the bold attribute, and keep colors untouched
241 /// @param bold bold/brighter text, default false
242 /// @param bg if true change the background, default: change foreground
243 /// @returns itself so it can be used within << invocations
244 virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
245 bool bg=false) { return *this; }
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 //===--------------------------------------------------------------------===//
252 // Subclass Interface
253 //===--------------------------------------------------------------------===//
256 /// write_impl - The is the piece of the class that is implemented
257 /// by subclasses. This writes the \args Size bytes starting at
258 /// \arg Ptr to the underlying stream.
260 /// This function is guaranteed to only be called at a point at which it is
261 /// safe for the subclass to install a new buffer via SetBuffer.
263 /// \arg Ptr - The start of the data to be written. For buffered streams this
264 /// is guaranteed to be the start of the buffer.
265 /// \arg Size - The number of bytes to be written.
267 /// \invariant { Size > 0 }
268 virtual void write_impl(const char *Ptr, size_t Size) = 0;
270 // An out of line virtual method to provide a home for the class vtable.
271 virtual void handle();
273 /// current_pos - Return the current position within the stream, not
274 /// counting the bytes currently in the buffer.
275 virtual uint64_t current_pos() = 0;
278 /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is
279 /// intended for use only by subclasses which can arrange for the output to go
280 /// directly into the desired output buffer, instead of being copied on each
282 void SetBuffer(char *BufferStart, size_t Size) {
283 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
286 /// preferred_buffer_size - Return an efficient buffer size for the
287 /// underlying output mechanism.
288 virtual size_t preferred_buffer_size();
290 /// error_detected - Set the flag indicating that an output error has
291 /// been encountered.
292 void error_detected() { Error = true; }
294 /// getBufferStart - Return the beginning of the current stream buffer, or 0
295 /// if the stream is unbuffered.
296 const char *getBufferStart() const { return OutBufStart; }
298 //===--------------------------------------------------------------------===//
300 //===--------------------------------------------------------------------===//
302 /// SetBufferAndMode - Install the given buffer and mode.
303 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
305 /// flush_nonempty - Flush the current buffer, which is known to be
306 /// non-empty. This outputs the currently buffered data and resets
307 /// the buffer to empty.
308 void flush_nonempty();
310 /// copy_to_buffer - Copy data into the buffer. Size must not be
311 /// greater than the number of unused bytes in the buffer.
312 void copy_to_buffer(const char *Ptr, size_t Size);
315 //===----------------------------------------------------------------------===//
316 // File Output Streams
317 //===----------------------------------------------------------------------===//
319 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
321 class raw_fd_ostream : public raw_ostream {
326 /// write_impl - See raw_ostream::write_impl.
327 virtual void write_impl(const char *Ptr, size_t Size);
329 /// current_pos - Return the current position within the stream, not
330 /// counting the bytes currently in the buffer.
331 virtual uint64_t current_pos() { return pos; }
333 /// preferred_buffer_size - Determine an efficient buffer size.
334 virtual size_t preferred_buffer_size();
339 /// F_Force - When opening a file, this flag makes raw_fd_ostream overwrite
340 /// a file if it already exists instead of emitting an error. This may not
341 /// be specified with F_Append.
344 /// F_Append - When opening a file, if it already exists append to the
345 /// existing file instead of returning an error. This may not be specified
349 /// F_Binary - The file should be opened in binary mode on platforms that
350 /// support this distinction.
354 /// raw_fd_ostream - Open the specified file for writing. If an error occurs,
355 /// information about the error is put into ErrorInfo, and the stream should
356 /// be immediately destroyed; the string will be empty if no error occurred.
357 /// This allows optional flags to control how the file will be opened.
359 /// \param Filename - The file to open. If this is "-" then the
360 /// stream will use stdout instead.
361 raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
364 /// raw_fd_ostream ctor - FD is the file descriptor that this writes to. If
365 /// ShouldClose is true, this closes the file when the stream is destroyed.
366 raw_fd_ostream(int fd, bool shouldClose,
367 bool unbuffered=false) : raw_ostream(unbuffered), FD(fd),
368 ShouldClose(shouldClose) {}
372 /// close - Manually flush the stream and close the file.
375 /// seek - Flushes the stream and repositions the underlying file descriptor
376 /// positition to the offset specified from the beginning of the file.
377 uint64_t seek(uint64_t off);
379 virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
381 virtual raw_ostream &resetColor();
384 /// raw_stdout_ostream - This is a stream that always prints to stdout.
386 class raw_stdout_ostream : public raw_fd_ostream {
387 // An out of line virtual method to provide a home for the class vtable.
388 virtual void handle();
390 raw_stdout_ostream();
393 /// raw_stderr_ostream - This is a stream that always prints to stderr.
395 class raw_stderr_ostream : public raw_fd_ostream {
396 // An out of line virtual method to provide a home for the class vtable.
397 virtual void handle();
399 raw_stderr_ostream();
402 /// outs() - This returns a reference to a raw_ostream for standard output.
403 /// Use it like: outs() << "foo" << "bar";
406 /// errs() - This returns a reference to a raw_ostream for standard error.
407 /// Use it like: errs() << "foo" << "bar";
410 /// nulls() - This returns a reference to a raw_ostream which simply discards
412 raw_ostream &nulls();
414 //===----------------------------------------------------------------------===//
415 // Output Stream Adaptors
416 //===----------------------------------------------------------------------===//
418 /// raw_os_ostream - A raw_ostream that writes to an std::ostream. This is a
419 /// simple adaptor class. It does not check for output errors; clients should
420 /// use the underlying stream to detect errors.
421 class raw_os_ostream : public raw_ostream {
424 /// write_impl - See raw_ostream::write_impl.
425 virtual void write_impl(const char *Ptr, size_t Size);
427 /// current_pos - Return the current position within the stream, not
428 /// counting the bytes currently in the buffer.
429 virtual uint64_t current_pos();
432 raw_os_ostream(std::ostream &O) : OS(O) {}
436 /// raw_string_ostream - A raw_ostream that writes to an std::string. This is a
437 /// simple adaptor class. This class does not encounter output errors.
438 class raw_string_ostream : public raw_ostream {
441 /// write_impl - See raw_ostream::write_impl.
442 virtual void write_impl(const char *Ptr, size_t Size);
444 /// current_pos - Return the current position within the stream, not
445 /// counting the bytes currently in the buffer.
446 virtual uint64_t current_pos() { return OS.size(); }
448 explicit raw_string_ostream(std::string &O) : OS(O) {}
449 ~raw_string_ostream();
451 /// str - Flushes the stream contents to the target string and returns
452 /// the string's reference.
459 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
460 /// SmallString. This is a simple adaptor class. This class does not
461 /// encounter output errors.
462 class raw_svector_ostream : public raw_ostream {
463 SmallVectorImpl<char> &OS;
465 /// write_impl - See raw_ostream::write_impl.
466 virtual void write_impl(const char *Ptr, size_t Size);
468 /// current_pos - Return the current position within the stream, not
469 /// counting the bytes currently in the buffer.
470 virtual uint64_t current_pos();
472 /// Construct a new raw_svector_ostream.
474 /// \arg O - The vector to write to; this should generally have at least 128
475 /// bytes free to avoid any extraneous memory overhead.
476 explicit raw_svector_ostream(SmallVectorImpl<char> &O);
477 ~raw_svector_ostream();
479 /// str - Flushes the stream contents to the target vector and return a
480 /// StringRef for the vector contents.
484 /// raw_null_ostream - A raw_ostream that discards all output.
485 class raw_null_ostream : public raw_ostream {
486 /// write_impl - See raw_ostream::write_impl.
487 virtual void write_impl(const char *Ptr, size_t size);
489 /// current_pos - Return the current position within the stream, not
490 /// counting the bytes currently in the buffer.
491 virtual uint64_t current_pos();
494 explicit raw_null_ostream() {}
498 } // end llvm namespace