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