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