raw_ostream.h revision 753e6258b88d2053d21d0c95bd67e0d1ae801d0e
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 <cassert>
19#include <cstring>
20#include <string>
21#include <iosfwd>
22
23namespace llvm {
24  class format_object_base;
25  template <typename T>
26  class SmallVectorImpl;
27
28/// raw_ostream - This class implements an extremely fast bulk output stream
29/// that can *only* output to a stream.  It does not support seeking, reopening,
30/// rewinding, line buffered disciplines etc. It is a simple buffer that outputs
31/// a chunk at a time.
32class raw_ostream {
33private:
34  /// The buffer is handled in such a way that the buffer is
35  /// uninitialized, unbuffered, or out of space when OutBufCur >=
36  /// OutBufEnd. Thus a single comparison suffices to determine if we
37  /// need to take the slow path to write a single character.
38  ///
39  /// The buffer is in one of three states:
40  ///  1. Unbuffered (Unbuffered == true)
41  ///  1. Uninitialized (Unbuffered == false && OutBufStart == 0).
42  ///  2. Buffered (Unbuffered == false && OutBufStart != 0 &&
43  ///               OutBufEnd - OutBufStart >= 64).
44  char *OutBufStart, *OutBufEnd, *OutBufCur;
45  bool Unbuffered;
46
47public:
48  // color order matches ANSI escape sequence, don't change
49  enum Colors {
50    BLACK=0,
51    RED,
52    GREEN,
53    YELLOW,
54    BLUE,
55    MAGENTA,
56    CYAN,
57    WHITE,
58    SAVEDCOLOR
59  };
60
61  explicit raw_ostream(bool unbuffered=false) : Unbuffered(unbuffered) {
62    // Start out ready to flush.
63    OutBufStart = OutBufEnd = OutBufCur = 0;
64  }
65
66  virtual ~raw_ostream() {
67    delete [] OutBufStart;
68  }
69
70  /// tell - Return the current offset with the file.
71  uint64_t tell() { return current_pos() + GetNumBytesInBuffer(); }
72
73  //===--------------------------------------------------------------------===//
74  // Configuration Interface
75  //===--------------------------------------------------------------------===//
76
77  /// SetBufferSize - Set the internal buffer size to the specified amount
78  /// instead of the default.
79  void SetBufferSize(unsigned Size=4096) {
80    assert(Size >= 64 &&
81           "Buffer size must be somewhat large for invariants to hold");
82    flush();
83
84    delete [] OutBufStart;
85    OutBufStart = new char[Size];
86    OutBufEnd = OutBufStart+Size;
87    OutBufCur = OutBufStart;
88    Unbuffered = false;
89  }
90
91  /// SetUnbuffered - Set the streams buffering status. When
92  /// unbuffered the stream will flush after every write. This routine
93  /// will also flush the buffer immediately when the stream is being
94  /// set to unbuffered.
95  void SetUnbuffered() {
96    flush();
97
98    delete [] OutBufStart;
99    OutBufStart = OutBufEnd = OutBufCur = 0;
100    Unbuffered = true;
101  }
102
103  unsigned GetNumBytesInBuffer() const {
104    return OutBufCur - OutBufStart;
105  }
106
107  //===--------------------------------------------------------------------===//
108  // Data Output Interface
109  //===--------------------------------------------------------------------===//
110
111  void flush() {
112    if (OutBufCur != OutBufStart)
113      flush_nonempty();
114  }
115
116  raw_ostream &operator<<(char C) {
117    if (OutBufCur >= OutBufEnd)
118      return write(C);
119    *OutBufCur++ = C;
120    return *this;
121  }
122
123  raw_ostream &operator<<(unsigned char C) {
124    if (OutBufCur >= OutBufEnd)
125      return write(C);
126    *OutBufCur++ = C;
127    return *this;
128  }
129
130  raw_ostream &operator<<(signed char C) {
131    if (OutBufCur >= OutBufEnd)
132      return write(C);
133    *OutBufCur++ = C;
134    return *this;
135  }
136
137  raw_ostream &operator<<(const char *Str) {
138    // Inline fast path, particulary for constant strings where a
139    // sufficiently smart compiler will simplify strlen.
140
141    unsigned Size = strlen(Str);
142
143    // Make sure we can use the fast path.
144    if (OutBufCur+Size > OutBufEnd)
145      return write(Str, Size);
146
147    memcpy(OutBufCur, Str, Size);
148    OutBufCur += Size;
149    return *this;
150  }
151
152  raw_ostream &operator<<(const std::string& Str) {
153    write(Str.data(), Str.length());
154    return *this;
155  }
156
157  raw_ostream &operator<<(unsigned long N);
158  raw_ostream &operator<<(long N);
159  raw_ostream &operator<<(unsigned long long N);
160  raw_ostream &operator<<(long long N);
161  raw_ostream &operator<<(const void *P);
162  raw_ostream &operator<<(unsigned int N) {
163    this->operator<<(static_cast<unsigned long>(N));
164    return *this;
165  }
166
167  raw_ostream &operator<<(int N) {
168    this->operator<<(static_cast<long>(N));
169    return *this;
170  }
171
172  raw_ostream &operator<<(double N) {
173    this->operator<<(ftostr(N));
174    return *this;
175  }
176
177  raw_ostream &write(unsigned char C);
178  raw_ostream &write(const char *Ptr, unsigned Size);
179
180  // Formatted output, see the format() function in Support/Format.h.
181  raw_ostream &operator<<(const format_object_base &Fmt);
182
183  /// Changes the foreground color of text that will be output from this point
184  /// forward.
185  /// @param colors ANSI color to use, the special SAVEDCOLOR can be used to
186  /// change only the bold attribute, and keep colors untouched
187  /// @param bold bold/brighter text, default false
188  /// @param bg if true change the background, default: change foreground
189  /// @returns itself so it can be used within << invocations
190  virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
191                                   bool  bg=false) { return *this; }
192
193  /// Resets the colors to terminal defaults. Call this when you are done
194  /// outputting colored text, or before program exit.
195  virtual raw_ostream &resetColor() { return *this; }
196
197  //===--------------------------------------------------------------------===//
198  // Subclass Interface
199  //===--------------------------------------------------------------------===//
200
201private:
202  /// write_impl - The is the piece of the class that is implemented
203  /// by subclasses.  This writes the \args Size bytes starting at
204  /// \arg Ptr to the underlying stream.
205  ///
206  /// \invariant { Size > 0 }
207  virtual void write_impl(const char *Ptr, unsigned Size) = 0;
208
209  // An out of line virtual method to provide a home for the class vtable.
210  virtual void handle();
211
212  /// current_pos - Return the current position within the stream, not
213  /// counting the bytes currently in the buffer.
214  virtual uint64_t current_pos() = 0;
215
216  //===--------------------------------------------------------------------===//
217  // Private Interface
218  //===--------------------------------------------------------------------===//
219private:
220  /// flush_nonempty - Flush the current buffer, which is known to be
221  /// non-empty. This outputs the currently buffered data and resets
222  /// the buffer to empty.
223  void flush_nonempty();
224};
225
226//===----------------------------------------------------------------------===//
227// File Output Streams
228//===----------------------------------------------------------------------===//
229
230/// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
231///
232class raw_fd_ostream : public raw_ostream {
233  int FD;
234  bool ShouldClose;
235  uint64_t pos;
236
237  /// write_impl - See raw_ostream::write_impl.
238  virtual void write_impl(const char *Ptr, unsigned Size);
239
240  /// current_pos - Return the current position within the stream, not
241  /// counting the bytes currently in the buffer.
242  virtual uint64_t current_pos() { return pos; }
243
244public:
245  /// raw_fd_ostream - Open the specified file for writing. If an
246  /// error occurs, information about the error is put into ErrorInfo,
247  /// and the stream should be immediately destroyed; the string will
248  /// be empty if no error occurred.
249  ///
250  /// \param Filename - The file to open. If this is "-" then the
251  /// stream will use stdout instead.
252  /// \param Binary - The file should be opened in binary mode on
253  /// platforms that support this distinction.
254  raw_fd_ostream(const char *Filename, bool Binary, std::string &ErrorInfo);
255
256  /// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
257  /// ShouldClose is true, this closes the file when the stream is destroyed.
258  raw_fd_ostream(int fd, bool shouldClose,
259                 bool unbuffered=false) : raw_ostream(unbuffered), FD(fd),
260                                          ShouldClose(shouldClose) {}
261
262  ~raw_fd_ostream();
263
264  /// close - Manually flush the stream and close the file.
265  void close();
266
267  /// tell - Return the current offset with the file.
268  uint64_t tell() { return pos + GetNumBytesInBuffer(); }
269
270  /// seek - Flushes the stream and repositions the underlying file descriptor
271  ///  positition to the offset specified from the beginning of the file.
272  uint64_t seek(uint64_t off);
273
274  virtual raw_ostream &changeColor(enum Colors colors, bool bold=false,
275                                   bool bg=false);
276  virtual raw_ostream &resetColor();
277};
278
279/// raw_stdout_ostream - This is a stream that always prints to stdout.
280///
281class raw_stdout_ostream : public raw_fd_ostream {
282  // An out of line virtual method to provide a home for the class vtable.
283  virtual void handle();
284public:
285  raw_stdout_ostream();
286};
287
288/// raw_stderr_ostream - This is a stream that always prints to stderr.
289///
290class raw_stderr_ostream : public raw_fd_ostream {
291  // An out of line virtual method to provide a home for the class vtable.
292  virtual void handle();
293public:
294  raw_stderr_ostream();
295};
296
297/// outs() - This returns a reference to a raw_ostream for standard output.
298/// Use it like: outs() << "foo" << "bar";
299raw_ostream &outs();
300
301/// errs() - This returns a reference to a raw_ostream for standard error.
302/// Use it like: errs() << "foo" << "bar";
303raw_ostream &errs();
304
305
306//===----------------------------------------------------------------------===//
307// Output Stream Adaptors
308//===----------------------------------------------------------------------===//
309
310/// raw_os_ostream - A raw_ostream that writes to an std::ostream.  This is a
311/// simple adaptor class.  It does check for I/O errors; clients should use
312/// the underlying stream to detect errors.
313class raw_os_ostream : public raw_ostream {
314  std::ostream &OS;
315
316  /// write_impl - See raw_ostream::write_impl.
317  virtual void write_impl(const char *Ptr, unsigned Size);
318
319  /// current_pos - Return the current position within the stream, not
320  /// counting the bytes currently in the buffer.
321  virtual uint64_t current_pos();
322
323public:
324  raw_os_ostream(std::ostream &O) : OS(O) {}
325  ~raw_os_ostream();
326
327  /// tell - Return the current offset with the stream.
328  uint64_t tell();
329};
330
331/// raw_string_ostream - A raw_ostream that writes to an std::string.  This is a
332/// simple adaptor class.
333class raw_string_ostream : public raw_ostream {
334  std::string &OS;
335
336  /// write_impl - See raw_ostream::write_impl.
337  virtual void write_impl(const char *Ptr, unsigned Size);
338
339  /// current_pos - Return the current position within the stream, not
340  /// counting the bytes currently in the buffer.
341  virtual uint64_t current_pos() { return OS.size(); }
342public:
343  raw_string_ostream(std::string &O) : OS(O) {}
344  ~raw_string_ostream();
345
346  /// tell - Return the current offset with the stream.
347  uint64_t tell() { return OS.size() + GetNumBytesInBuffer(); }
348
349  /// str - Flushes the stream contents to the target string and returns
350  ///  the string's reference.
351  std::string& str() {
352    flush();
353    return OS;
354  }
355};
356
357/// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
358/// SmallString.  This is a simple adaptor class.
359class raw_svector_ostream : public raw_ostream {
360  SmallVectorImpl<char> &OS;
361
362  /// write_impl - See raw_ostream::write_impl.
363  virtual void write_impl(const char *Ptr, unsigned Size);
364
365  /// current_pos - Return the current position within the stream, not
366  /// counting the bytes currently in the buffer.
367  virtual uint64_t current_pos();
368public:
369  raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {}
370  ~raw_svector_ostream();
371
372  /// tell - Return the current offset with the stream.
373  uint64_t tell();
374};
375
376} // end llvm namespace
377
378#endif
379