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