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