1 //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements support for bulk buffered stream output.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/System/Program.h"
17 #include "llvm/System/Process.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/Support/Compiler.h"
23 #if defined(HAVE_UNISTD_H)
26 #if defined(HAVE_FCNTL_H)
34 # define STDIN_FILENO 0
37 # define STDOUT_FILENO 1
40 # define STDERR_FILENO 2
47 // An out of line virtual method to provide a home for the class vtable.
48 void raw_ostream::handle() {}
50 raw_ostream &raw_ostream::operator<<(unsigned long N) {
51 // Zero is a special case.
55 char NumberBuffer[20];
56 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
57 char *CurPtr = EndPtr;
60 *--CurPtr = '0' + char(N % 10);
63 return write(CurPtr, EndPtr-CurPtr);
66 raw_ostream &raw_ostream::operator<<(long N) {
72 return this->operator<<(static_cast<unsigned long>(N));
75 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
76 // Zero is a special case.
80 char NumberBuffer[20];
81 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
82 char *CurPtr = EndPtr;
85 *--CurPtr = '0' + char(N % 10);
88 return write(CurPtr, EndPtr-CurPtr);
91 raw_ostream &raw_ostream::operator<<(long long N) {
97 return this->operator<<(static_cast<unsigned long long>(N));
100 raw_ostream &raw_ostream::operator<<(const void *P) {
101 uintptr_t N = (uintptr_t) P;
104 // Zero is a special case.
108 char NumberBuffer[20];
109 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
110 char *CurPtr = EndPtr;
114 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
118 return write(CurPtr, EndPtr-CurPtr);
121 void raw_ostream::flush_nonempty() {
122 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
123 write_impl(OutBufStart, OutBufCur - OutBufStart);
124 OutBufCur = OutBufStart;
127 raw_ostream &raw_ostream::write(unsigned char C) {
128 // Group exceptional cases into a single branch.
129 if (OutBufCur >= OutBufEnd) {
131 write_impl(reinterpret_cast<char*>(&C), 1);
145 raw_ostream &raw_ostream::write(const char *Ptr, unsigned Size) {
146 // Group exceptional cases into a single branch.
147 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
149 write_impl(Ptr, Size);
159 // Handle short strings specially, memcpy isn't very good at very short
162 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
163 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
164 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
165 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
168 // Normally the string to emit is shorter than the buffer.
169 if (Size <= unsigned(OutBufEnd-OutBufStart)) {
170 memcpy(OutBufCur, Ptr, Size);
174 // Otherwise we are emitting a string larger than our buffer. We
175 // know we already flushed, so just write it out directly.
176 write_impl(Ptr, Size);
186 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
187 // If we have more than a few bytes left in our output buffer, try
188 // formatting directly onto its end.
190 // FIXME: This test is a bit silly, since if we don't have enough
191 // space in the buffer we will have to flush the formatted output
192 // anyway. We should just flush upfront in such cases, and use the
193 // whole buffer as our scratch pad. Note, however, that this case is
194 // also necessary for correctness on unbuffered streams.
195 unsigned NextBufferSize = 127;
196 if (OutBufEnd-OutBufCur > 3) {
197 unsigned BufferBytesLeft = OutBufEnd-OutBufCur;
198 unsigned BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
200 // Common case is that we have plenty of space.
201 if (BytesUsed < BufferBytesLeft) {
202 OutBufCur += BytesUsed;
206 // Otherwise, we overflowed and the return value tells us the size to try
208 NextBufferSize = BytesUsed;
211 // If we got here, we didn't have enough space in the output buffer for the
212 // string. Try printing into a SmallVector that is resized to have enough
213 // space. Iterate until we win.
214 SmallVector<char, 128> V;
217 V.resize(NextBufferSize);
219 // Try formatting into the SmallVector.
220 unsigned BytesUsed = Fmt.print(&V[0], NextBufferSize);
222 // If BytesUsed fit into the vector, we win.
223 if (BytesUsed <= NextBufferSize)
224 return write(&V[0], BytesUsed);
226 // Otherwise, try again with a new size.
227 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
228 NextBufferSize = BytesUsed;
232 //===----------------------------------------------------------------------===//
234 //===----------------------------------------------------------------------===//
236 // Out of line virtual method.
237 void format_object_base::home() {
240 //===----------------------------------------------------------------------===//
242 //===----------------------------------------------------------------------===//
244 /// raw_fd_ostream - Open the specified file for writing. If an error
245 /// occurs, information about the error is put into ErrorInfo, and the
246 /// stream should be immediately destroyed; the string will be empty
247 /// if no error occurred.
248 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary,
249 std::string &ErrorInfo) : pos(0) {
252 // Handle "-" as stdout.
253 if (Filename[0] == '-' && Filename[1] == 0) {
255 // If user requested binary then put stdout into binary mode if
258 sys::Program::ChangeStdoutToBinary();
263 int Flags = O_WRONLY|O_CREAT|O_TRUNC;
268 FD = open(Filename, Flags, 0644);
270 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
277 raw_fd_ostream::~raw_fd_ostream() {
285 void raw_fd_ostream::write_impl(const char *Ptr, unsigned Size) {
286 assert (FD >= 0 && "File already closed.");
288 ::write(FD, Ptr, Size);
291 void raw_fd_ostream::close() {
292 assert (ShouldClose);
299 uint64_t raw_fd_ostream::seek(uint64_t off) {
301 pos = lseek(FD, off, SEEK_SET);
305 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
307 if (sys::Process::ColorNeedsFlush())
309 const char *colorcode =
310 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
311 : sys::Process::OutputColor(colors, bold, bg);
313 unsigned len = strlen(colorcode);
314 write(colorcode, len);
315 // don't account colors towards output characters
321 raw_ostream &raw_fd_ostream::resetColor() {
322 if (sys::Process::ColorNeedsFlush())
324 const char *colorcode = sys::Process::ResetColor();
326 unsigned len = strlen(colorcode);
327 write(colorcode, len);
328 // don't account colors towards output characters
334 //===----------------------------------------------------------------------===//
335 // raw_stdout/err_ostream
336 //===----------------------------------------------------------------------===//
338 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
339 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
342 // An out of line virtual method to provide a home for the class vtable.
343 void raw_stdout_ostream::handle() {}
344 void raw_stderr_ostream::handle() {}
346 /// outs() - This returns a reference to a raw_ostream for standard output.
347 /// Use it like: outs() << "foo" << "bar";
348 raw_ostream &llvm::outs() {
349 static raw_stdout_ostream S;
353 /// errs() - This returns a reference to a raw_ostream for standard error.
354 /// Use it like: errs() << "foo" << "bar";
355 raw_ostream &llvm::errs() {
356 static raw_stderr_ostream S;
360 //===----------------------------------------------------------------------===//
362 //===----------------------------------------------------------------------===//
364 raw_os_ostream::~raw_os_ostream() {
368 void raw_os_ostream::write_impl(const char *Ptr, unsigned Size) {
372 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
374 uint64_t raw_os_ostream::tell() {
375 return (uint64_t)OS.tellp() + GetNumBytesInBuffer();
378 //===----------------------------------------------------------------------===//
379 // raw_string_ostream
380 //===----------------------------------------------------------------------===//
382 raw_string_ostream::~raw_string_ostream() {
386 void raw_string_ostream::write_impl(const char *Ptr, unsigned Size) {
387 OS.append(Ptr, Size);
390 //===----------------------------------------------------------------------===//
391 // raw_svector_ostream
392 //===----------------------------------------------------------------------===//
394 raw_svector_ostream::~raw_svector_ostream() {
398 void raw_svector_ostream::write_impl(const char *Ptr, unsigned Size) {
399 OS.append(Ptr, Ptr + Size);
402 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
404 uint64_t raw_svector_ostream::tell() {
405 return OS.size() + GetNumBytesInBuffer();