raw_ostream: Rework implementation of unbuffered streams so outputting
[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 public:
48   explicit raw_ostream(bool unbuffered=false) : Unbuffered(unbuffered) {
49     // Start out ready to flush.
50     OutBufStart = OutBufEnd = OutBufCur = 0;
51   }
52
53   virtual ~raw_ostream() {
54     delete [] OutBufStart;
55   }
56
57   //===--------------------------------------------------------------------===//
58   // Configuration Interface
59   //===--------------------------------------------------------------------===//
60
61   /// SetBufferSize - Set the internal buffer size to the specified amount
62   /// instead of the default.
63   void SetBufferSize(unsigned Size=4096) {
64     assert(Size >= 64 &&
65            "Buffer size must be somewhat large for invariants to hold");
66     flush();
67
68     delete [] OutBufStart;
69     OutBufStart = new char[Size];
70     OutBufEnd = OutBufStart+Size;
71     OutBufCur = OutBufStart;
72     Unbuffered = false;
73   }
74
75   /// SetUnbuffered - Set the streams buffering status. When
76   /// unbuffered the stream will flush after every write. This routine
77   /// will also flush the buffer immediately when the stream is being
78   /// set to unbuffered.
79   void SetUnbuffered() {
80     flush();
81     
82     delete [] OutBufStart;
83     OutBufStart = OutBufEnd = OutBufCur = 0;
84     Unbuffered = true;
85   }
86
87   unsigned GetNumBytesInBuffer() const {
88     return OutBufCur - OutBufStart;
89   }
90
91   //===--------------------------------------------------------------------===//
92   // Data Output Interface
93   //===--------------------------------------------------------------------===//
94
95   void flush() {
96     if (OutBufCur != OutBufStart)
97       flush_nonempty();
98   }
99
100   raw_ostream &operator<<(char C) {
101     if (OutBufCur >= OutBufEnd)
102       return write(C);
103     *OutBufCur++ = C;
104     return *this;
105   }
106
107   raw_ostream &operator<<(unsigned char C) {
108     if (OutBufCur >= OutBufEnd)
109       return write(C);
110     *OutBufCur++ = C;
111     return *this;
112   }
113
114   raw_ostream &operator<<(signed char C) {
115     if (OutBufCur >= OutBufEnd)
116       return write(C);
117     *OutBufCur++ = C;
118     return *this;
119   }
120
121   raw_ostream &operator<<(const char *Str) {
122     return write(Str, strlen(Str));
123   }
124
125   raw_ostream &operator<<(const std::string& Str) {
126     return write(Str.data(), Str.length());
127   }
128
129   raw_ostream &operator<<(unsigned long N);
130   raw_ostream &operator<<(long N);
131   raw_ostream &operator<<(unsigned long long N);
132   raw_ostream &operator<<(long long N);
133   raw_ostream &operator<<(const void *P);
134   raw_ostream &operator<<(unsigned int N) {
135     return this->operator<<(static_cast<unsigned long>(N));
136   }
137
138   raw_ostream &operator<<(int N) {
139     return this->operator<<(static_cast<long>(N));
140   }
141
142   raw_ostream &operator<<(double N) {
143     return this->operator<<(ftostr(N));
144   }
145
146   raw_ostream &write(unsigned char C);
147   raw_ostream &write(const char *Ptr, unsigned Size);
148
149   // Formatted output, see the format() function in Support/Format.h.
150   raw_ostream &operator<<(const format_object_base &Fmt);
151
152   //===--------------------------------------------------------------------===//
153   // Subclass Interface
154   //===--------------------------------------------------------------------===//
155
156 private:
157   /// write_impl - The is the piece of the class that is implemented
158   /// by subclasses.  This writes the \args Size bytes starting at
159   /// \arg Ptr to the underlying stream.
160   /// 
161   /// \invariant { Size > 0 }
162   virtual void write_impl(const char *Ptr, unsigned Size) = 0;
163
164   // An out of line virtual method to provide a home for the class vtable.
165   virtual void handle();
166
167   //===--------------------------------------------------------------------===//
168   // Private Interface
169   //===--------------------------------------------------------------------===//
170 private:
171   /// flush_nonempty - Flush the current buffer, which is known to be
172   /// non-empty. This outputs the currently buffered data and resets
173   /// the buffer to empty.
174   void flush_nonempty();
175 };
176
177 //===----------------------------------------------------------------------===//
178 // File Output Streams
179 //===----------------------------------------------------------------------===//
180
181 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
182 ///
183 class raw_fd_ostream : public raw_ostream {
184   int FD;
185   bool ShouldClose;
186   uint64_t pos;
187
188   /// write_impl - See raw_ostream::write_impl.
189   virtual void write_impl(const char *Ptr, unsigned Size);
190 public:
191   /// raw_fd_ostream - Open the specified file for writing. If an
192   /// error occurs, information about the error is put into ErrorInfo,
193   /// and the stream should be immediately destroyed; the string will
194   /// be empty if no error occurred.
195   ///
196   /// \param Filename - The file to open. If this is "-" then the
197   /// stream will use stdout instead.
198   /// \param Binary - The file should be opened in binary mode on
199   /// platforms that support this distinction.
200   raw_fd_ostream(const char *Filename, bool Binary, std::string &ErrorInfo);
201
202   /// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
203   /// ShouldClose is true, this closes the file when the stream is destroyed.
204   raw_fd_ostream(int fd, bool shouldClose, 
205                  bool unbuffered=false) : raw_ostream(unbuffered), FD(fd), 
206                                           ShouldClose(shouldClose) {}
207   
208   ~raw_fd_ostream();
209
210   /// close - Manually flush the stream and close the file.
211   void close();
212
213   /// tell - Return the current offset with the file.
214   uint64_t tell() { return pos + GetNumBytesInBuffer(); }
215
216   /// seek - Flushes the stream and repositions the underlying file descriptor
217   ///  positition to the offset specified from the beginning of the file.
218   uint64_t seek(uint64_t off);
219 };
220
221 /// raw_stdout_ostream - This is a stream that always prints to stdout.
222 ///
223 class raw_stdout_ostream : public raw_fd_ostream {
224   // An out of line virtual method to provide a home for the class vtable.
225   virtual void handle();
226 public:
227   raw_stdout_ostream();
228 };
229
230 /// raw_stderr_ostream - This is a stream that always prints to stderr.
231 ///
232 class raw_stderr_ostream : public raw_fd_ostream {
233   // An out of line virtual method to provide a home for the class vtable.
234   virtual void handle();
235 public:
236   raw_stderr_ostream();
237 };
238
239 /// outs() - This returns a reference to a raw_ostream for standard output.
240 /// Use it like: outs() << "foo" << "bar";
241 raw_ostream &outs();
242
243 /// errs() - This returns a reference to a raw_ostream for standard error.
244 /// Use it like: errs() << "foo" << "bar";
245 raw_ostream &errs();
246
247
248 //===----------------------------------------------------------------------===//
249 // Output Stream Adaptors
250 //===----------------------------------------------------------------------===//
251
252 /// raw_os_ostream - A raw_ostream that writes to an std::ostream.  This is a
253 /// simple adaptor class.
254 class raw_os_ostream : public raw_ostream {
255   std::ostream &OS;
256
257   /// write_impl - See raw_ostream::write_impl.
258   virtual void write_impl(const char *Ptr, unsigned Size);
259 public:
260   raw_os_ostream(std::ostream &O) : OS(O) {}
261   ~raw_os_ostream();
262 };
263
264 /// raw_string_ostream - A raw_ostream that writes to an std::string.  This is a
265 /// simple adaptor class.
266 class raw_string_ostream : public raw_ostream {
267   std::string &OS;
268
269   /// write_impl - See raw_ostream::write_impl.
270   virtual void write_impl(const char *Ptr, unsigned Size);
271 public:
272   raw_string_ostream(std::string &O) : OS(O) {}
273   ~raw_string_ostream();
274
275   /// str - Flushes the stream contents to the target string and returns
276   ///  the string's reference.
277   std::string& str() {
278     flush();
279     return OS;
280   }
281 };
282
283 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
284 /// SmallString.  This is a simple adaptor class.
285 class raw_svector_ostream : public raw_ostream {
286   SmallVectorImpl<char> &OS;
287
288   /// write_impl - See raw_ostream::write_impl.
289   virtual void write_impl(const char *Ptr, unsigned Size);
290 public:
291   raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {}
292   ~raw_svector_ostream();
293 };
294
295 } // end llvm namespace
296
297 #endif