raw_ostream.h revision 56c9286edcc59fb381452c7d88f8faf80ab1b525
1//===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the raw_ostream class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_RAW_OSTREAM_H
15#define LLVM_SUPPORT_RAW_OSTREAM_H
16
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/ADT/StringRef.h"
19#include <cassert>
20#include <cstring>
21#include <string>
22#include <iosfwd>
23
24namespace llvm {
25  class format_object_base;
26  template <typename T>
27  class SmallVectorImpl;
28
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.
33class raw_ostream {
34private:
35  // Do not implement. raw_ostream is noncopyable.
36  void operator=(const raw_ostream &);
37  raw_ostream(const raw_ostream &);
38
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.
43  ///
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).
49  ///
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.
53  ///
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
56  /// this buffer.
57  char *OutBufStart, *OutBufEnd, *OutBufCur;
58
59  enum BufferKind {
60    Unbuffered = 0,
61    InternalBuffer,
62    ExternalBuffer
63  } BufferMode;
64
65  /// Error This flag is true if an error of any kind has been detected.
66  ///
67  bool Error;
68
69public:
70  // color order matches ANSI escape sequence, don't change
71  enum Colors {
72    BLACK=0,
73    RED,
74    GREEN,
75    YELLOW,
76    BLUE,
77    MAGENTA,
78    CYAN,
79    WHITE,
80    SAVEDCOLOR
81  };
82
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;
87  }
88
89  virtual ~raw_ostream();
90
91  /// tell - Return the current offset with the file.
92  uint64_t tell() { return current_pos() + GetNumBytesInBuffer(); }
93
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 {
97    return Error;
98  }
99
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.
104  void clear_error() {
105    Error = false;
106  }
107
108  //===--------------------------------------------------------------------===//
109  // Configuration Interface
110  //===--------------------------------------------------------------------===//
111
112  /// SetBuffered - Set the stream to be buffered, with an automatically
113  /// determined buffer size.
114  void SetBuffered();
115
116  /// SetBufferSize - Set the stream to be buffered, using the
117  /// specified buffer size.
118  void SetBufferSize(size_t Size) {
119    flush();
120    SetBufferAndMode(new char[Size], Size, InternalBuffer);
121  }
122
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();
128
129    // Otherwise just return the size of the allocated buffer.
130    return OutBufEnd - OutBufStart;
131  }
132
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() {
138    flush();
139    SetBufferAndMode(0, 0, Unbuffered);
140  }
141
142  size_t GetNumBytesInBuffer() const {
143    return OutBufCur - OutBufStart;
144  }
145
146  //===--------------------------------------------------------------------===//
147  // Data Output Interface
148  //===--------------------------------------------------------------------===//
149
150  void flush() {
151    if (OutBufCur != OutBufStart)
152      flush_nonempty();
153  }
154
155  raw_ostream &operator<<(char C) {
156    if (OutBufCur >= OutBufEnd)
157      return write(C);
158    *OutBufCur++ = C;
159    return *this;
160  }
161
162  raw_ostream &operator<<(unsigned char C) {
163    if (OutBufCur >= OutBufEnd)
164      return write(C);
165    *OutBufCur++ = C;
166    return *this;
167  }
168
169  raw_ostream &operator<<(signed char C) {
170    if (OutBufCur >= OutBufEnd)
171      return write(C);
172    *OutBufCur++ = C;
173    return *this;
174  }
175
176  raw_ostream &operator<<(const StringRef &Str) {
177    // Inline fast path, particularly for strings with a known length.
178    size_t Size = Str.size();
179
180    // Make sure we can use the fast path.
181    if (OutBufCur+Size > OutBufEnd)
182      return write(Str.data(), Size);
183
184    memcpy(OutBufCur, Str.data(), Size);
185    OutBufCur += Size;
186    return *this;
187  }
188
189  raw_ostream &operator<<(const char *Str) {
190    // Inline fast path, particulary for constant strings where a sufficiently
191    // smart compiler will simplify strlen.
192
193    this->operator<<(StringRef(Str));
194    return *this;
195  }
196
197  raw_ostream &operator<<(const std::string &Str) {
198    // Avoid the fast path, it would only increase code size for a marginal win.
199
200    write(Str.data(), Str.length());
201    return *this;
202  }
203
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));
211    return *this;
212  }
213
214  raw_ostream &operator<<(int N) {
215    this->operator<<(static_cast<long>(N));
216    return *this;
217  }
218
219  raw_ostream &operator<<(double N) {
220    this->operator<<(ftostr(N));
221    return *this;
222  }
223
224  /// write_hex - Output \arg N in hexadecimal, without any prefix or padding.
225  raw_ostream &write_hex(unsigned long long N);
226
227  raw_ostream &write(unsigned char C);
228  raw_ostream &write(const char *Ptr, size_t Size);
229
230  // Formatted output, see the format() function in Support/Format.h.
231  raw_ostream &operator<<(const format_object_base &Fmt);
232
233  /// Changes the foreground color of text that will be output from this point
234  /// forward.
235  /// @param colors ANSI color to use, the special SAVEDCOLOR can be used to
236  /// change only the bold attribute, and keep colors untouched
237  /// @param bold bold/brighter text, default false
238  /// @param bg if true change the background, default: change foreground
239  /// @returns itself so it can be used within << invocations
240  virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
241                                   bool  bg=false) { return *this; }
242
243  /// Resets the colors to terminal defaults. Call this when you are done
244  /// outputting colored text, or before program exit.
245  virtual raw_ostream &resetColor() { return *this; }
246
247  //===--------------------------------------------------------------------===//
248  // Subclass Interface
249  //===--------------------------------------------------------------------===//
250
251private:
252  /// write_impl - The is the piece of the class that is implemented
253  /// by subclasses.  This writes the \args Size bytes starting at
254  /// \arg Ptr to the underlying stream.
255  ///
256  /// This function is guaranteed to only be called at a point at which it is
257  /// safe for the subclass to install a new buffer via SetBuffer.
258  ///
259  /// \arg Ptr - The start of the data to be written. For buffered streams this
260  /// is guaranteed to be the start of the buffer.
261  /// \arg Size - The number of bytes to be written.
262  ///
263  /// \invariant { Size > 0 }
264  virtual void write_impl(const char *Ptr, size_t Size) = 0;
265
266  // An out of line virtual method to provide a home for the class vtable.
267  virtual void handle();
268
269  /// current_pos - Return the current position within the stream, not
270  /// counting the bytes currently in the buffer.
271  virtual uint64_t current_pos() = 0;
272
273protected:
274  /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is
275  /// intended for use only by subclasses which can arrange for the output to go
276  /// directly into the desired output buffer, instead of being copied on each
277  /// flush.
278  void SetBuffer(char *BufferStart, size_t Size) {
279    SetBufferAndMode(BufferStart, Size, ExternalBuffer);
280  }
281
282  /// preferred_buffer_size - Return an efficient buffer size for the
283  /// underlying output mechanism.
284  virtual size_t preferred_buffer_size();
285
286  /// error_detected - Set the flag indicating that an output error has
287  /// been encountered.
288  void error_detected() { Error = true; }
289
290  /// getBufferStart - Return the beginning of the current stream buffer, or 0
291  /// if the stream is unbuffered.
292  const char *getBufferStart() const { return OutBufStart; }
293
294  //===--------------------------------------------------------------------===//
295  // Private Interface
296  //===--------------------------------------------------------------------===//
297private:
298  /// SetBufferAndMode - Install the given buffer and mode.
299  void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
300
301  /// flush_nonempty - Flush the current buffer, which is known to be
302  /// non-empty. This outputs the currently buffered data and resets
303  /// the buffer to empty.
304  void flush_nonempty();
305
306  /// copy_to_buffer - Copy data into the buffer. Size must not be
307  /// greater than the number of unused bytes in the buffer.
308  void copy_to_buffer(const char *Ptr, size_t Size);
309};
310
311//===----------------------------------------------------------------------===//
312// File Output Streams
313//===----------------------------------------------------------------------===//
314
315/// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
316///
317class raw_fd_ostream : public raw_ostream {
318  int FD;
319  bool ShouldClose;
320  uint64_t pos;
321
322  /// write_impl - See raw_ostream::write_impl.
323  virtual void write_impl(const char *Ptr, size_t Size);
324
325  /// current_pos - Return the current position within the stream, not
326  /// counting the bytes currently in the buffer.
327  virtual uint64_t current_pos() { return pos; }
328
329  /// preferred_buffer_size - Determine an efficient buffer size.
330  virtual size_t preferred_buffer_size();
331
332public:
333  /// raw_fd_ostream - Open the specified file for writing. If an
334  /// error occurs, information about the error is put into ErrorInfo,
335  /// and the stream should be immediately destroyed; the string will
336  /// be empty if no error occurred.
337  ///
338  /// \param Filename - The file to open. If this is "-" then the
339  /// stream will use stdout instead.
340  /// \param Binary - The file should be opened in binary mode on
341  /// platforms that support this distinction.
342  /// \param Force - Don't consider the case where the file already
343  /// exists to be an error.
344  raw_fd_ostream(const char *Filename, bool Binary, bool Force,
345                 std::string &ErrorInfo);
346
347  /// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
348  /// ShouldClose is true, this closes the file when the stream is destroyed.
349  raw_fd_ostream(int fd, bool shouldClose,
350                 bool unbuffered=false) : raw_ostream(unbuffered), FD(fd),
351                                          ShouldClose(shouldClose) {}
352
353  ~raw_fd_ostream();
354
355  /// close - Manually flush the stream and close the file.
356  void close();
357
358  /// seek - Flushes the stream and repositions the underlying file descriptor
359  ///  positition to the offset specified from the beginning of the file.
360  uint64_t seek(uint64_t off);
361
362  virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
363                                   bool bg=false);
364  virtual raw_ostream &resetColor();
365};
366
367/// raw_stdout_ostream - This is a stream that always prints to stdout.
368///
369class raw_stdout_ostream : public raw_fd_ostream {
370  // An out of line virtual method to provide a home for the class vtable.
371  virtual void handle();
372public:
373  raw_stdout_ostream();
374};
375
376/// raw_stderr_ostream - This is a stream that always prints to stderr.
377///
378class raw_stderr_ostream : public raw_fd_ostream {
379  // An out of line virtual method to provide a home for the class vtable.
380  virtual void handle();
381public:
382  raw_stderr_ostream();
383};
384
385/// outs() - This returns a reference to a raw_ostream for standard output.
386/// Use it like: outs() << "foo" << "bar";
387raw_ostream &outs();
388
389/// errs() - This returns a reference to a raw_ostream for standard error.
390/// Use it like: errs() << "foo" << "bar";
391raw_ostream &errs();
392
393/// nulls() - This returns a reference to a raw_ostream which simply discards
394/// output.
395raw_ostream &nulls();
396
397//===----------------------------------------------------------------------===//
398// Output Stream Adaptors
399//===----------------------------------------------------------------------===//
400
401/// raw_os_ostream - A raw_ostream that writes to an std::ostream.  This is a
402/// simple adaptor class.  It does not check for output errors; clients should
403/// use the underlying stream to detect errors.
404class raw_os_ostream : public raw_ostream {
405  std::ostream &OS;
406
407  /// write_impl - See raw_ostream::write_impl.
408  virtual void write_impl(const char *Ptr, size_t Size);
409
410  /// current_pos - Return the current position within the stream, not
411  /// counting the bytes currently in the buffer.
412  virtual uint64_t current_pos();
413
414public:
415  raw_os_ostream(std::ostream &O) : OS(O) {}
416  ~raw_os_ostream();
417};
418
419/// raw_string_ostream - A raw_ostream that writes to an std::string.  This is a
420/// simple adaptor class. This class does not encounter output errors.
421class raw_string_ostream : public raw_ostream {
422  std::string &OS;
423
424  /// write_impl - See raw_ostream::write_impl.
425  virtual void write_impl(const char *Ptr, size_t Size);
426
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() { return OS.size(); }
430public:
431  explicit raw_string_ostream(std::string &O) : OS(O) {}
432  ~raw_string_ostream();
433
434  /// str - Flushes the stream contents to the target string and returns
435  ///  the string's reference.
436  std::string& str() {
437    flush();
438    return OS;
439  }
440};
441
442/// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
443/// SmallString.  This is a simple adaptor class. This class does not
444/// encounter output errors.
445class raw_svector_ostream : public raw_ostream {
446  SmallVectorImpl<char> &OS;
447
448  /// write_impl - See raw_ostream::write_impl.
449  virtual void write_impl(const char *Ptr, size_t Size);
450
451  /// current_pos - Return the current position within the stream, not
452  /// counting the bytes currently in the buffer.
453  virtual uint64_t current_pos();
454public:
455  /// Construct a new raw_svector_ostream.
456  ///
457  /// \arg O - The vector to write to; this should generally have at least 128
458  /// bytes free to avoid any extraneous memory overhead.
459  explicit raw_svector_ostream(SmallVectorImpl<char> &O);
460  ~raw_svector_ostream();
461
462  /// str - Flushes the stream contents to the target vector and return a
463  /// StringRef for the vector contents.
464  StringRef str();
465};
466
467/// raw_null_ostream - A raw_ostream that discards all output.
468class raw_null_ostream : public raw_ostream {
469  /// write_impl - See raw_ostream::write_impl.
470  virtual void write_impl(const char *Ptr, size_t size);
471
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();
475
476public:
477  explicit raw_null_ostream() {}
478  ~raw_null_ostream();
479};
480
481} // end llvm namespace
482
483#endif
484