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