raw_ostream.h revision ab810275448c34c072c47be1f16ae1d679bfd20c
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 (Unbuffered == true)
46  ///  1. Uninitialized (Unbuffered == false && OutBufStart == 0).
47  ///  2. Buffered (Unbuffered == false && OutBufStart != 0 &&
48  ///               OutBufEnd - OutBufStart >= 64).
49  char *OutBufStart, *OutBufEnd, *OutBufCur;
50  bool Unbuffered;
51
52  /// Error This flag is true if an error of any kind has been detected.
53  ///
54  bool Error;
55
56public:
57  // color order matches ANSI escape sequence, don't change
58  enum Colors {
59    BLACK=0,
60    RED,
61    GREEN,
62    YELLOW,
63    BLUE,
64    MAGENTA,
65    CYAN,
66    WHITE,
67    SAVEDCOLOR
68  };
69
70  explicit raw_ostream(bool unbuffered=false)
71    : Unbuffered(unbuffered), Error(false) {
72    // Start out ready to flush.
73    OutBufStart = OutBufEnd = OutBufCur = 0;
74  }
75
76  virtual ~raw_ostream();
77
78  /// tell - Return the current offset with the file.
79  uint64_t tell() { return current_pos() + GetNumBytesInBuffer(); }
80
81  /// has_error - Return the value of the flag in this raw_ostream indicating
82  /// whether an output error has been encountered.
83  bool has_error() const {
84    return Error;
85  }
86
87  /// clear_error - Set the flag read by has_error() to false. If the error
88  /// flag is set at the time when this raw_ostream's destructor is called,
89  /// llvm_report_error is called to report the error. Use clear_error()
90  /// after handling the error to avoid this behavior.
91  void clear_error() {
92    Error = false;
93  }
94
95  //===--------------------------------------------------------------------===//
96  // Configuration Interface
97  //===--------------------------------------------------------------------===//
98
99  /// SetBuffered - Set the stream to be buffered, with an automatically
100  /// determined buffer size.
101  void SetBuffered();
102
103  /// SetBufferrSize - Set the stream to be buffered, using the
104  /// specified buffer size.
105  void SetBufferSize(size_t Size);
106
107  size_t GetBufferSize() {
108    // If we're supposed to be buffered but haven't actually gotten around
109    // to allocating the buffer yet, return the value that would be used.
110    if (!Unbuffered && !OutBufStart)
111      return preferred_buffer_size();
112
113    // Otherwise just return the size of the allocated buffer.
114    return OutBufEnd - OutBufStart;
115  }
116
117  /// SetUnbuffered - Set the stream to be unbuffered. When
118  /// unbuffered, the stream will flush after every write. This routine
119  /// will also flush the buffer immediately when the stream is being
120  /// set to unbuffered.
121  void SetUnbuffered();
122
123  size_t GetNumBytesInBuffer() const {
124    return OutBufCur - OutBufStart;
125  }
126
127  //===--------------------------------------------------------------------===//
128  // Data Output Interface
129  //===--------------------------------------------------------------------===//
130
131  void flush() {
132    if (OutBufCur != OutBufStart)
133      flush_nonempty();
134  }
135
136  raw_ostream &operator<<(char C) {
137    if (OutBufCur >= OutBufEnd)
138      return write(C);
139    *OutBufCur++ = C;
140    return *this;
141  }
142
143  raw_ostream &operator<<(unsigned char C) {
144    if (OutBufCur >= OutBufEnd)
145      return write(C);
146    *OutBufCur++ = C;
147    return *this;
148  }
149
150  raw_ostream &operator<<(signed char C) {
151    if (OutBufCur >= OutBufEnd)
152      return write(C);
153    *OutBufCur++ = C;
154    return *this;
155  }
156
157  raw_ostream &operator<<(const StringRef &Str) {
158    // Inline fast path, particularly for strings with a known length.
159    size_t Size = Str.size();
160
161    // Make sure we can use the fast path.
162    if (OutBufCur+Size > OutBufEnd)
163      return write(Str.data(), Size);
164
165    memcpy(OutBufCur, Str.data(), Size);
166    OutBufCur += Size;
167    return *this;
168  }
169
170  raw_ostream &operator<<(const char *Str) {
171    // Inline fast path, particulary for constant strings where a sufficiently
172    // smart compiler will simplify strlen.
173
174    this->operator<<(StringRef(Str));
175    return *this;
176  }
177
178  raw_ostream &operator<<(const std::string& Str) {
179    write(Str.data(), Str.length());
180    return *this;
181  }
182
183  raw_ostream &operator<<(unsigned long N);
184  raw_ostream &operator<<(long N);
185  raw_ostream &operator<<(unsigned long long N);
186  raw_ostream &operator<<(long long N);
187  raw_ostream &operator<<(const void *P);
188  raw_ostream &operator<<(unsigned int N) {
189    this->operator<<(static_cast<unsigned long>(N));
190    return *this;
191  }
192
193  raw_ostream &operator<<(int N) {
194    this->operator<<(static_cast<long>(N));
195    return *this;
196  }
197
198  raw_ostream &operator<<(double N) {
199    this->operator<<(ftostr(N));
200    return *this;
201  }
202
203  /// write_hex - Output \arg N in hexadecimal, without any prefix or padding.
204  raw_ostream &write_hex(unsigned long long N);
205
206  raw_ostream &write(unsigned char C);
207  raw_ostream &write(const char *Ptr, size_t Size);
208
209  // Formatted output, see the format() function in Support/Format.h.
210  raw_ostream &operator<<(const format_object_base &Fmt);
211
212  /// Changes the foreground color of text that will be output from this point
213  /// forward.
214  /// @param colors 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 colors, bool bold=false,
220                                   bool  bg=false) { return *this; }
221
222  /// Resets the colors to terminal defaults. Call this when you are done
223  /// outputting colored text, or before program exit.
224  virtual raw_ostream &resetColor() { return *this; }
225
226  //===--------------------------------------------------------------------===//
227  // Subclass Interface
228  //===--------------------------------------------------------------------===//
229
230private:
231  /// write_impl - The is the piece of the class that is implemented
232  /// by subclasses.  This writes the \args Size bytes starting at
233  /// \arg Ptr to the underlying stream.
234  ///
235  /// \invariant { Size > 0 }
236  virtual void write_impl(const char *Ptr, size_t Size) = 0;
237
238  // An out of line virtual method to provide a home for the class vtable.
239  virtual void handle();
240
241  /// current_pos - Return the current position within the stream, not
242  /// counting the bytes currently in the buffer.
243  virtual uint64_t current_pos() = 0;
244
245protected:
246  /// preferred_buffer_size - Return an efficient buffer size for the
247  /// underlying output mechanism.
248  virtual size_t preferred_buffer_size();
249
250  /// error_detected - Set the flag indicating that an output error has
251  /// been encountered.
252  void error_detected() { Error = true; }
253
254  /// getBufferStart - Return the beginning of the current stream buffer, or 0
255  /// if the stream is unbuffered.
256  const char *getBufferStart() const { return OutBufStart; }
257
258  //===--------------------------------------------------------------------===//
259  // Private Interface
260  //===--------------------------------------------------------------------===//
261private:
262  /// flush_nonempty - Flush the current buffer, which is known to be
263  /// non-empty. This outputs the currently buffered data and resets
264  /// the buffer to empty.
265  void flush_nonempty();
266
267  /// copy_to_buffer - Copy data into the buffer. Size must not be
268  /// greater than the number of unused bytes in the buffer.
269  void copy_to_buffer(const char *Ptr, size_t Size);
270};
271
272//===----------------------------------------------------------------------===//
273// File Output Streams
274//===----------------------------------------------------------------------===//
275
276/// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
277///
278class raw_fd_ostream : public raw_ostream {
279  int FD;
280  bool ShouldClose;
281  uint64_t pos;
282
283  /// write_impl - See raw_ostream::write_impl.
284  virtual void write_impl(const char *Ptr, size_t Size);
285
286  /// current_pos - Return the current position within the stream, not
287  /// counting the bytes currently in the buffer.
288  virtual uint64_t current_pos() { return pos; }
289
290  /// preferred_buffer_size - Determine an efficient buffer size.
291  virtual size_t preferred_buffer_size();
292
293public:
294  /// raw_fd_ostream - Open the specified file for writing. If an
295  /// error occurs, information about the error is put into ErrorInfo,
296  /// and the stream should be immediately destroyed; the string will
297  /// be empty if no error occurred.
298  ///
299  /// \param Filename - The file to open. If this is "-" then the
300  /// stream will use stdout instead.
301  /// \param Binary - The file should be opened in binary mode on
302  /// platforms that support this distinction.
303  /// \param Force - Don't consider the case where the file already
304  /// exists to be an error.
305  raw_fd_ostream(const char *Filename, bool Binary, bool Force,
306                 std::string &ErrorInfo);
307
308  /// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
309  /// ShouldClose is true, this closes the file when the stream is destroyed.
310  raw_fd_ostream(int fd, bool shouldClose,
311                 bool unbuffered=false) : raw_ostream(unbuffered), FD(fd),
312                                          ShouldClose(shouldClose) {}
313
314  ~raw_fd_ostream();
315
316  /// close - Manually flush the stream and close the file.
317  void close();
318
319  /// tell - Return the current offset with the file.
320  uint64_t tell() { return pos + GetNumBytesInBuffer(); }
321
322  /// seek - Flushes the stream and repositions the underlying file descriptor
323  ///  positition to the offset specified from the beginning of the file.
324  uint64_t seek(uint64_t off);
325
326  virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
327                                   bool bg=false);
328  virtual raw_ostream &resetColor();
329};
330
331/// raw_stdout_ostream - This is a stream that always prints to stdout.
332///
333class raw_stdout_ostream : public raw_fd_ostream {
334  // An out of line virtual method to provide a home for the class vtable.
335  virtual void handle();
336public:
337  raw_stdout_ostream();
338};
339
340/// raw_stderr_ostream - This is a stream that always prints to stderr.
341///
342class raw_stderr_ostream : public raw_fd_ostream {
343  // An out of line virtual method to provide a home for the class vtable.
344  virtual void handle();
345public:
346  raw_stderr_ostream();
347};
348
349/// outs() - This returns a reference to a raw_ostream for standard output.
350/// Use it like: outs() << "foo" << "bar";
351raw_ostream &outs();
352
353/// errs() - This returns a reference to a raw_ostream for standard error.
354/// Use it like: errs() << "foo" << "bar";
355raw_ostream &errs();
356
357/// nulls() - This returns a reference to a raw_ostream which simply discards
358/// output.
359raw_ostream &nulls();
360
361//===----------------------------------------------------------------------===//
362// Output Stream Adaptors
363//===----------------------------------------------------------------------===//
364
365/// raw_os_ostream - A raw_ostream that writes to an std::ostream.  This is a
366/// simple adaptor class.  It does not check for output errors; clients should
367/// use the underlying stream to detect errors.
368class raw_os_ostream : public raw_ostream {
369  std::ostream &OS;
370
371  /// write_impl - See raw_ostream::write_impl.
372  virtual void write_impl(const char *Ptr, size_t Size);
373
374  /// current_pos - Return the current position within the stream, not
375  /// counting the bytes currently in the buffer.
376  virtual uint64_t current_pos();
377
378public:
379  raw_os_ostream(std::ostream &O) : OS(O) {}
380  ~raw_os_ostream();
381
382  /// tell - Return the current offset with the stream.
383  uint64_t tell();
384};
385
386/// raw_string_ostream - A raw_ostream that writes to an std::string.  This is a
387/// simple adaptor class. This class does not encounter output errors.
388class raw_string_ostream : public raw_ostream {
389  std::string &OS;
390
391  /// write_impl - See raw_ostream::write_impl.
392  virtual void write_impl(const char *Ptr, size_t Size);
393
394  /// current_pos - Return the current position within the stream, not
395  /// counting the bytes currently in the buffer.
396  virtual uint64_t current_pos() { return OS.size(); }
397public:
398  explicit raw_string_ostream(std::string &O) : OS(O) {}
399  ~raw_string_ostream();
400
401  /// tell - Return the current offset with the stream.
402  uint64_t tell() { return OS.size() + GetNumBytesInBuffer(); }
403
404  /// str - Flushes the stream contents to the target string and returns
405  ///  the string's reference.
406  std::string& str() {
407    flush();
408    return OS;
409  }
410};
411
412/// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
413/// SmallString.  This is a simple adaptor class. This class does not
414/// encounter output errors.
415class raw_svector_ostream : public raw_ostream {
416  SmallVectorImpl<char> &OS;
417
418  /// write_impl - See raw_ostream::write_impl.
419  virtual void write_impl(const char *Ptr, size_t Size);
420
421  /// current_pos - Return the current position within the stream, not
422  /// counting the bytes currently in the buffer.
423  virtual uint64_t current_pos();
424public:
425  explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {}
426  ~raw_svector_ostream();
427
428  /// tell - Return the current offset with the stream.
429  uint64_t tell();
430};
431
432/// raw_null_ostream - A raw_ostream that discards all output.
433class raw_null_ostream : public raw_ostream {
434  /// write_impl - See raw_ostream::write_impl.
435  virtual void write_impl(const char *Ptr, size_t size);
436
437  /// current_pos - Return the current position within the stream, not
438  /// counting the bytes currently in the buffer.
439  virtual uint64_t current_pos();
440
441public:
442  explicit raw_null_ostream() {}
443  ~raw_null_ostream();
444};
445
446} // end llvm namespace
447
448#endif
449