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