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"
21 #include "llvm/Support/ErrorHandling.h"
24 #if defined(HAVE_UNISTD_H)
27 #if defined(HAVE_FCNTL_H)
35 # define STDIN_FILENO 0
38 # define STDOUT_FILENO 1
41 # define STDERR_FILENO 2
48 // An out of line virtual method to provide a home for the class vtable.
49 void raw_ostream::handle() {}
51 raw_ostream &raw_ostream::operator<<(unsigned long N) {
52 // Zero is a special case.
56 char NumberBuffer[20];
57 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
58 char *CurPtr = EndPtr;
61 *--CurPtr = '0' + char(N % 10);
64 return write(CurPtr, EndPtr-CurPtr);
67 raw_ostream &raw_ostream::operator<<(long N) {
73 return this->operator<<(static_cast<unsigned long>(N));
76 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
77 // Zero is a special case.
81 char NumberBuffer[20];
82 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
83 char *CurPtr = EndPtr;
86 *--CurPtr = '0' + char(N % 10);
89 return write(CurPtr, EndPtr-CurPtr);
92 raw_ostream &raw_ostream::operator<<(long long N) {
98 return this->operator<<(static_cast<unsigned long long>(N));
101 raw_ostream &raw_ostream::operator<<(const void *P) {
102 uintptr_t N = (uintptr_t) P;
105 // Zero is a special case.
109 char NumberBuffer[20];
110 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
111 char *CurPtr = EndPtr;
115 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
119 return write(CurPtr, EndPtr-CurPtr);
122 void raw_ostream::flush_nonempty() {
123 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
124 write_impl(OutBufStart, OutBufCur - OutBufStart);
125 OutBufCur = OutBufStart;
128 raw_ostream &raw_ostream::write(unsigned char C) {
129 // Group exceptional cases into a single branch.
130 if (OutBufCur >= OutBufEnd) {
132 write_impl(reinterpret_cast<char*>(&C), 1);
146 raw_ostream &raw_ostream::write(const char *Ptr, unsigned Size) {
147 // Group exceptional cases into a single branch.
148 if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
150 write_impl(Ptr, Size);
160 // Handle short strings specially, memcpy isn't very good at very short
163 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
164 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
165 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
166 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
169 // Normally the string to emit is shorter than the buffer.
170 if (Size <= unsigned(OutBufEnd-OutBufCur)) {
171 memcpy(OutBufCur, Ptr, Size);
175 // Otherwise we are emitting a string larger than our buffer. We
176 // know we already flushed, so just write it out directly.
177 write_impl(Ptr, Size);
187 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
188 // If we have more than a few bytes left in our output buffer, try
189 // formatting directly onto its end.
191 // FIXME: This test is a bit silly, since if we don't have enough
192 // space in the buffer we will have to flush the formatted output
193 // anyway. We should just flush upfront in such cases, and use the
194 // whole buffer as our scratch pad. Note, however, that this case is
195 // also necessary for correctness on unbuffered streams.
196 unsigned NextBufferSize = 127;
197 if (OutBufEnd-OutBufCur > 3) {
198 unsigned BufferBytesLeft = OutBufEnd-OutBufCur;
199 unsigned BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
201 // Common case is that we have plenty of space.
202 if (BytesUsed < BufferBytesLeft) {
203 OutBufCur += BytesUsed;
207 // Otherwise, we overflowed and the return value tells us the size to try
209 NextBufferSize = BytesUsed;
212 // If we got here, we didn't have enough space in the output buffer for the
213 // string. Try printing into a SmallVector that is resized to have enough
214 // space. Iterate until we win.
215 SmallVector<char, 128> V;
218 V.resize(NextBufferSize);
220 // Try formatting into the SmallVector.
221 unsigned BytesUsed = Fmt.print(&V[0], NextBufferSize);
223 // If BytesUsed fit into the vector, we win.
224 if (BytesUsed <= NextBufferSize)
225 return write(&V[0], BytesUsed);
227 // Otherwise, try again with a new size.
228 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
229 NextBufferSize = BytesUsed;
233 //===----------------------------------------------------------------------===//
235 //===----------------------------------------------------------------------===//
237 // Out of line virtual method.
238 void format_object_base::home() {
241 //===----------------------------------------------------------------------===//
243 //===----------------------------------------------------------------------===//
245 /// raw_fd_ostream - Open the specified file for writing. If an error
246 /// occurs, information about the error is put into ErrorInfo, and the
247 /// stream should be immediately destroyed; the string will be empty
248 /// if no error occurred.
249 raw_fd_ostream::raw_fd_ostream(const char *Filename, bool Binary, bool Force,
250 std::string &ErrorInfo) : pos(0) {
253 // Handle "-" as stdout.
254 if (Filename[0] == '-' && Filename[1] == 0) {
256 // If user requested binary then put stdout into binary mode if
259 sys::Program::ChangeStdoutToBinary();
264 int Flags = O_WRONLY|O_CREAT|O_TRUNC;
271 FD = open(Filename, Flags, 0664);
273 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
280 raw_fd_ostream::~raw_fd_ostream() {
284 if (::close(FD) != 0)
285 llvm_report_error("IO failure closing output stream.");
289 void raw_fd_ostream::write_impl(const char *Ptr, unsigned Size) {
290 assert (FD >= 0 && "File already closed.");
292 if (::write(FD, Ptr, Size) != (ssize_t) Size)
293 llvm_report_error("IO failure writing to output stream.");
296 void raw_fd_ostream::close() {
297 assert (ShouldClose);
300 if (::close(FD) != 0)
301 llvm_report_error("IO failure closing output stream.");
305 uint64_t raw_fd_ostream::seek(uint64_t off) {
307 pos = ::lseek(FD, off, SEEK_SET);
309 llvm_report_error("IO failure seeking on output stream.");
313 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
315 if (sys::Process::ColorNeedsFlush())
317 const char *colorcode =
318 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
319 : sys::Process::OutputColor(colors, bold, bg);
321 unsigned len = strlen(colorcode);
322 write(colorcode, len);
323 // don't account colors towards output characters
329 raw_ostream &raw_fd_ostream::resetColor() {
330 if (sys::Process::ColorNeedsFlush())
332 const char *colorcode = sys::Process::ResetColor();
334 unsigned len = strlen(colorcode);
335 write(colorcode, len);
336 // don't account colors towards output characters
342 //===----------------------------------------------------------------------===//
343 // raw_stdout/err_ostream
344 //===----------------------------------------------------------------------===//
346 raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
347 raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
350 // An out of line virtual method to provide a home for the class vtable.
351 void raw_stdout_ostream::handle() {}
352 void raw_stderr_ostream::handle() {}
354 /// outs() - This returns a reference to a raw_ostream for standard output.
355 /// Use it like: outs() << "foo" << "bar";
356 raw_ostream &llvm::outs() {
357 static raw_stdout_ostream S;
361 /// errs() - This returns a reference to a raw_ostream for standard error.
362 /// Use it like: errs() << "foo" << "bar";
363 raw_ostream &llvm::errs() {
364 static raw_stderr_ostream S;
368 //===----------------------------------------------------------------------===//
370 //===----------------------------------------------------------------------===//
372 raw_os_ostream::~raw_os_ostream() {
376 void raw_os_ostream::write_impl(const char *Ptr, unsigned Size) {
380 uint64_t raw_os_ostream::current_pos() { return OS.tellp(); }
382 uint64_t raw_os_ostream::tell() {
383 return (uint64_t)OS.tellp() + GetNumBytesInBuffer();
386 //===----------------------------------------------------------------------===//
387 // raw_string_ostream
388 //===----------------------------------------------------------------------===//
390 raw_string_ostream::~raw_string_ostream() {
394 void raw_string_ostream::write_impl(const char *Ptr, unsigned Size) {
395 OS.append(Ptr, Size);
398 //===----------------------------------------------------------------------===//
399 // raw_svector_ostream
400 //===----------------------------------------------------------------------===//
402 raw_svector_ostream::~raw_svector_ostream() {
406 void raw_svector_ostream::write_impl(const char *Ptr, unsigned Size) {
407 OS.append(Ptr, Ptr + Size);
410 uint64_t raw_svector_ostream::current_pos() { return OS.size(); }
412 uint64_t raw_svector_ostream::tell() {
413 return OS.size() + GetNumBytesInBuffer();