Add static cast to unsigned char whenever a character classification function is...
[oota-llvm.git] / lib / Support / raw_ostream.cpp
1 //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
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 implements support for bulk buffered stream output.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Config/config.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/Process.h"
23 #include "llvm/Support/Program.h"
24 #include "llvm/Support/system_error.h"
25 #include <cctype>
26 #include <cerrno>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29
30 #if defined(HAVE_UNISTD_H)
31 # include <unistd.h>
32 #endif
33 #if defined(HAVE_FCNTL_H)
34 # include <fcntl.h>
35 #endif
36 #if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
37 #  include <sys/uio.h>
38 #endif
39
40 #if defined(__CYGWIN__)
41 #include <io.h>
42 #endif
43
44 #if defined(_MSC_VER)
45 #include <io.h>
46 #include <fcntl.h>
47 #ifndef STDIN_FILENO
48 # define STDIN_FILENO 0
49 #endif
50 #ifndef STDOUT_FILENO
51 # define STDOUT_FILENO 1
52 #endif
53 #ifndef STDERR_FILENO
54 # define STDERR_FILENO 2
55 #endif
56 #endif
57
58 using namespace llvm;
59
60 raw_ostream::~raw_ostream() {
61   // raw_ostream's subclasses should take care to flush the buffer
62   // in their destructors.
63   assert(OutBufCur == OutBufStart &&
64          "raw_ostream destructor called with non-empty buffer!");
65
66   if (BufferMode == InternalBuffer)
67     delete [] OutBufStart;
68 }
69
70 // An out of line virtual method to provide a home for the class vtable.
71 void raw_ostream::handle() {}
72
73 size_t raw_ostream::preferred_buffer_size() const {
74   // BUFSIZ is intended to be a reasonable default.
75   return BUFSIZ;
76 }
77
78 void raw_ostream::SetBuffered() {
79   // Ask the subclass to determine an appropriate buffer size.
80   if (size_t Size = preferred_buffer_size())
81     SetBufferSize(Size);
82   else
83     // It may return 0, meaning this stream should be unbuffered.
84     SetUnbuffered();
85 }
86
87 void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
88                                    BufferKind Mode) {
89   assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) ||
90           (Mode != Unbuffered && BufferStart && Size)) &&
91          "stream must be unbuffered or have at least one byte");
92   // Make sure the current buffer is free of content (we can't flush here; the
93   // child buffer management logic will be in write_impl).
94   assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
95
96   if (BufferMode == InternalBuffer)
97     delete [] OutBufStart;
98   OutBufStart = BufferStart;
99   OutBufEnd = OutBufStart+Size;
100   OutBufCur = OutBufStart;
101   BufferMode = Mode;
102
103   assert(OutBufStart <= OutBufEnd && "Invalid size!");
104 }
105
106 raw_ostream &raw_ostream::operator<<(unsigned long N) {
107   // Zero is a special case.
108   if (N == 0)
109     return *this << '0';
110
111   char NumberBuffer[20];
112   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
113   char *CurPtr = EndPtr;
114
115   while (N) {
116     *--CurPtr = '0' + char(N % 10);
117     N /= 10;
118   }
119   return write(CurPtr, EndPtr-CurPtr);
120 }
121
122 raw_ostream &raw_ostream::operator<<(long N) {
123   if (N <  0) {
124     *this << '-';
125     // Avoid undefined behavior on LONG_MIN with a cast.
126     N = -(unsigned long)N;
127   }
128
129   return this->operator<<(static_cast<unsigned long>(N));
130 }
131
132 raw_ostream &raw_ostream::operator<<(unsigned long long N) {
133   // Output using 32-bit div/mod when possible.
134   if (N == static_cast<unsigned long>(N))
135     return this->operator<<(static_cast<unsigned long>(N));
136
137   char NumberBuffer[20];
138   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
139   char *CurPtr = EndPtr;
140
141   while (N) {
142     *--CurPtr = '0' + char(N % 10);
143     N /= 10;
144   }
145   return write(CurPtr, EndPtr-CurPtr);
146 }
147
148 raw_ostream &raw_ostream::operator<<(long long N) {
149   if (N < 0) {
150     *this << '-';
151     // Avoid undefined behavior on INT64_MIN with a cast.
152     N = -(unsigned long long)N;
153   }
154
155   return this->operator<<(static_cast<unsigned long long>(N));
156 }
157
158 raw_ostream &raw_ostream::write_hex(unsigned long long N) {
159   // Zero is a special case.
160   if (N == 0)
161     return *this << '0';
162
163   char NumberBuffer[20];
164   char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
165   char *CurPtr = EndPtr;
166
167   while (N) {
168     uintptr_t x = N % 16;
169     *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
170     N /= 16;
171   }
172
173   return write(CurPtr, EndPtr-CurPtr);
174 }
175
176 raw_ostream &raw_ostream::write_escaped(StringRef Str,
177                                         bool UseHexEscapes) {
178   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
179     unsigned char c = Str[i];
180
181     switch (c) {
182     case '\\':
183       *this << '\\' << '\\';
184       break;
185     case '\t':
186       *this << '\\' << 't';
187       break;
188     case '\n':
189       *this << '\\' << 'n';
190       break;
191     case '"':
192       *this << '\\' << '"';
193       break;
194     default:
195       if (std::isprint(c)) {
196         *this << c;
197         break;
198       }
199
200       // Write out the escaped representation.
201       if (UseHexEscapes) {
202         *this << '\\' << 'x';
203         *this << hexdigit((c >> 4 & 0xF));
204         *this << hexdigit((c >> 0) & 0xF);
205       } else {
206         // Always use a full 3-character octal escape.
207         *this << '\\';
208         *this << char('0' + ((c >> 6) & 7));
209         *this << char('0' + ((c >> 3) & 7));
210         *this << char('0' + ((c >> 0) & 7));
211       }
212     }
213   }
214
215   return *this;
216 }
217
218 raw_ostream &raw_ostream::operator<<(const void *P) {
219   *this << '0' << 'x';
220
221   return write_hex((uintptr_t) P);
222 }
223
224 raw_ostream &raw_ostream::operator<<(double N) {
225 #ifdef _WIN32
226   // On MSVCRT and compatible, output of %e is incompatible to Posix
227   // by default. Number of exponent digits should be at least 2. "%+03d"
228   // FIXME: Implement our formatter to here or Support/Format.h!
229   int fpcl = _fpclass(N);
230
231   // negative zero
232   if (fpcl == _FPCLASS_NZ)
233     return *this << "-0.000000e+00";
234
235   char buf[16];
236   unsigned len;
237   len = snprintf(buf, sizeof(buf), "%e", N);
238   if (len <= sizeof(buf) - 2) {
239     if (len >= 5 && buf[len - 5] == 'e' && buf[len - 3] == '0') {
240       int cs = buf[len - 4];
241       if (cs == '+' || cs == '-') {
242         int c1 = buf[len - 2];
243         int c0 = buf[len - 1];
244         if (isdigit(static_cast<unsigned char>(c1)) &&
245             isdigit(static_cast<unsigned char>(c0))) {
246           // Trim leading '0': "...e+012" -> "...e+12\0"
247           buf[len - 3] = c1;
248           buf[len - 2] = c0;
249           buf[--len] = 0;
250         }
251       }
252     }
253     return this->operator<<(buf);
254   }
255 #endif
256   return this->operator<<(format("%e", N));
257 }
258
259
260
261 void raw_ostream::flush_nonempty() {
262   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
263   size_t Length = OutBufCur - OutBufStart;
264   OutBufCur = OutBufStart;
265   write_impl(OutBufStart, Length);
266 }
267
268 raw_ostream &raw_ostream::write(unsigned char C) {
269   // Group exceptional cases into a single branch.
270   if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
271     if (LLVM_UNLIKELY(!OutBufStart)) {
272       if (BufferMode == Unbuffered) {
273         write_impl(reinterpret_cast<char*>(&C), 1);
274         return *this;
275       }
276       // Set up a buffer and start over.
277       SetBuffered();
278       return write(C);
279     }
280
281     flush_nonempty();
282   }
283
284   *OutBufCur++ = C;
285   return *this;
286 }
287
288 raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
289   // Group exceptional cases into a single branch.
290   if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
291     if (LLVM_UNLIKELY(!OutBufStart)) {
292       if (BufferMode == Unbuffered) {
293         write_impl(Ptr, Size);
294         return *this;
295       }
296       // Set up a buffer and start over.
297       SetBuffered();
298       return write(Ptr, Size);
299     }
300
301     size_t NumBytes = OutBufEnd - OutBufCur;
302
303     // If the buffer is empty at this point we have a string that is larger
304     // than the buffer. Directly write the chunk that is a multiple of the
305     // preferred buffer size and put the remainder in the buffer.
306     if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
307       size_t BytesToWrite = Size - (Size % NumBytes);
308       write_impl(Ptr, BytesToWrite);
309       copy_to_buffer(Ptr + BytesToWrite, Size - BytesToWrite);
310       return *this;
311     }
312
313     // We don't have enough space in the buffer to fit the string in. Insert as
314     // much as possible, flush and start over with the remainder.
315     copy_to_buffer(Ptr, NumBytes);
316     flush_nonempty();
317     return write(Ptr + NumBytes, Size - NumBytes);
318   }
319
320   copy_to_buffer(Ptr, Size);
321
322   return *this;
323 }
324
325 void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
326   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
327
328   // Handle short strings specially, memcpy isn't very good at very short
329   // strings.
330   switch (Size) {
331   case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
332   case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
333   case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
334   case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
335   case 0: break;
336   default:
337     memcpy(OutBufCur, Ptr, Size);
338     break;
339   }
340
341   OutBufCur += Size;
342 }
343
344 // Formatted output.
345 raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
346   // If we have more than a few bytes left in our output buffer, try
347   // formatting directly onto its end.
348   size_t NextBufferSize = 127;
349   size_t BufferBytesLeft = OutBufEnd - OutBufCur;
350   if (BufferBytesLeft > 3) {
351     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
352
353     // Common case is that we have plenty of space.
354     if (BytesUsed <= BufferBytesLeft) {
355       OutBufCur += BytesUsed;
356       return *this;
357     }
358
359     // Otherwise, we overflowed and the return value tells us the size to try
360     // again with.
361     NextBufferSize = BytesUsed;
362   }
363
364   // If we got here, we didn't have enough space in the output buffer for the
365   // string.  Try printing into a SmallVector that is resized to have enough
366   // space.  Iterate until we win.
367   SmallVector<char, 128> V;
368
369   while (1) {
370     V.resize(NextBufferSize);
371
372     // Try formatting into the SmallVector.
373     size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
374
375     // If BytesUsed fit into the vector, we win.
376     if (BytesUsed <= NextBufferSize)
377       return write(V.data(), BytesUsed);
378
379     // Otherwise, try again with a new size.
380     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
381     NextBufferSize = BytesUsed;
382   }
383 }
384
385 /// indent - Insert 'NumSpaces' spaces.
386 raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
387   static const char Spaces[] = "                                "
388                                "                                "
389                                "                ";
390
391   // Usually the indentation is small, handle it with a fastpath.
392   if (NumSpaces < array_lengthof(Spaces))
393     return write(Spaces, NumSpaces);
394
395   while (NumSpaces) {
396     unsigned NumToWrite = std::min(NumSpaces,
397                                    (unsigned)array_lengthof(Spaces)-1);
398     write(Spaces, NumToWrite);
399     NumSpaces -= NumToWrite;
400   }
401   return *this;
402 }
403
404
405 //===----------------------------------------------------------------------===//
406 //  Formatted Output
407 //===----------------------------------------------------------------------===//
408
409 // Out of line virtual method.
410 void format_object_base::home() {
411 }
412
413 //===----------------------------------------------------------------------===//
414 //  raw_fd_ostream
415 //===----------------------------------------------------------------------===//
416
417 /// raw_fd_ostream - Open the specified file for writing. If an error
418 /// occurs, information about the error is put into ErrorInfo, and the
419 /// stream should be immediately destroyed; the string will be empty
420 /// if no error occurred.
421 raw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
422                                unsigned Flags)
423   : Error(false), UseAtomicWrites(false), pos(0)
424 {
425   assert(Filename != 0 && "Filename is null");
426   // Verify that we don't have both "append" and "excl".
427   assert((!(Flags & F_Excl) || !(Flags & F_Append)) &&
428          "Cannot specify both 'excl' and 'append' file creation flags!");
429
430   ErrorInfo.clear();
431
432   // Handle "-" as stdout. Note that when we do this, we consider ourself
433   // the owner of stdout. This means that we can do things like close the
434   // file descriptor when we're done and set the "binary" flag globally.
435   if (Filename[0] == '-' && Filename[1] == 0) {
436     FD = STDOUT_FILENO;
437     // If user requested binary then put stdout into binary mode if
438     // possible.
439     if (Flags & F_Binary)
440       sys::Program::ChangeStdoutToBinary();
441     // Close stdout when we're done, to detect any output errors.
442     ShouldClose = true;
443     return;
444   }
445
446   int OpenFlags = O_WRONLY|O_CREAT;
447 #ifdef O_BINARY
448   if (Flags & F_Binary)
449     OpenFlags |= O_BINARY;
450 #endif
451
452   if (Flags & F_Append)
453     OpenFlags |= O_APPEND;
454   else
455     OpenFlags |= O_TRUNC;
456   if (Flags & F_Excl)
457     OpenFlags |= O_EXCL;
458
459   while ((FD = open(Filename, OpenFlags, 0664)) < 0) {
460     if (errno != EINTR) {
461       ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
462       ShouldClose = false;
463       return;
464     }
465   }
466
467   // Ok, we successfully opened the file, so it'll need to be closed.
468   ShouldClose = true;
469 }
470
471 /// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
472 /// ShouldClose is true, this closes the file when the stream is destroyed.
473 raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
474   : raw_ostream(unbuffered), FD(fd),
475     ShouldClose(shouldClose), Error(false), UseAtomicWrites(false) {
476 #ifdef O_BINARY
477   // Setting STDOUT and STDERR to binary mode is necessary in Win32
478   // to avoid undesirable linefeed conversion.
479   if (fd == STDOUT_FILENO || fd == STDERR_FILENO)
480     setmode(fd, O_BINARY);
481 #endif
482
483   // Get the starting position.
484   off_t loc = ::lseek(FD, 0, SEEK_CUR);
485   if (loc == (off_t)-1)
486     pos = 0;
487   else
488     pos = static_cast<uint64_t>(loc);
489 }
490
491 raw_fd_ostream::~raw_fd_ostream() {
492   if (FD >= 0) {
493     flush();
494     if (ShouldClose)
495       while (::close(FD) != 0)
496         if (errno != EINTR) {
497           error_detected();
498           break;
499         }
500   }
501
502 #ifdef __MINGW32__
503   // On mingw, global dtors should not call exit().
504   // report_fatal_error() invokes exit(). We know report_fatal_error()
505   // might not write messages to stderr when any errors were detected
506   // on FD == 2.
507   if (FD == 2) return;
508 #endif
509
510   // If there are any pending errors, report them now. Clients wishing
511   // to avoid report_fatal_error calls should check for errors with
512   // has_error() and clear the error flag with clear_error() before
513   // destructing raw_ostream objects which may have errors.
514   if (has_error())
515     report_fatal_error("IO failure on output stream.");
516 }
517
518
519 void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
520   assert(FD >= 0 && "File already closed.");
521   pos += Size;
522
523   do {
524     ssize_t ret;
525
526     // Check whether we should attempt to use atomic writes.
527     if (LLVM_LIKELY(!UseAtomicWrites)) {
528       ret = ::write(FD, Ptr, Size);
529     } else {
530       // Use ::writev() where available.
531 #if defined(HAVE_WRITEV)
532       const void *Addr = static_cast<const void *>(Ptr);
533       struct iovec IOV = {const_cast<void *>(Addr), Size };
534       ret = ::writev(FD, &IOV, 1);
535 #else
536       ret = ::write(FD, Ptr, Size);
537 #endif
538     }
539
540     if (ret < 0) {
541       // If it's a recoverable error, swallow it and retry the write.
542       //
543       // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
544       // raw_ostream isn't designed to do non-blocking I/O. However, some
545       // programs, such as old versions of bjam, have mistakenly used
546       // O_NONBLOCK. For compatibility, emulate blocking semantics by
547       // spinning until the write succeeds. If you don't want spinning,
548       // don't use O_NONBLOCK file descriptors with raw_ostream.
549       if (errno == EINTR || errno == EAGAIN
550 #ifdef EWOULDBLOCK
551           || errno == EWOULDBLOCK
552 #endif
553           )
554         continue;
555
556       // Otherwise it's a non-recoverable error. Note it and quit.
557       error_detected();
558       break;
559     }
560
561     // The write may have written some or all of the data. Update the
562     // size and buffer pointer to reflect the remainder that needs
563     // to be written. If there are no bytes left, we're done.
564     Ptr += ret;
565     Size -= ret;
566   } while (Size > 0);
567 }
568
569 void raw_fd_ostream::close() {
570   assert(ShouldClose);
571   ShouldClose = false;
572   flush();
573   while (::close(FD) != 0)
574     if (errno != EINTR) {
575       error_detected();
576       break;
577     }
578   FD = -1;
579 }
580
581 uint64_t raw_fd_ostream::seek(uint64_t off) {
582   flush();
583   pos = ::lseek(FD, off, SEEK_SET);
584   if (pos != off)
585     error_detected();
586   return pos;
587 }
588
589 size_t raw_fd_ostream::preferred_buffer_size() const {
590 #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
591   // Windows and Minix have no st_blksize.
592   assert(FD >= 0 && "File not yet open!");
593   struct stat statbuf;
594   if (fstat(FD, &statbuf) != 0)
595     return 0;
596
597   // If this is a terminal, don't use buffering. Line buffering
598   // would be a more traditional thing to do, but it's not worth
599   // the complexity.
600   if (S_ISCHR(statbuf.st_mode) && isatty(FD))
601     return 0;
602   // Return the preferred block size.
603   return statbuf.st_blksize;
604 #else
605   return raw_ostream::preferred_buffer_size();
606 #endif
607 }
608
609 raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
610                                          bool bg) {
611   if (sys::Process::ColorNeedsFlush())
612     flush();
613   const char *colorcode =
614     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
615     : sys::Process::OutputColor(colors, bold, bg);
616   if (colorcode) {
617     size_t len = strlen(colorcode);
618     write(colorcode, len);
619     // don't account colors towards output characters
620     pos -= len;
621   }
622   return *this;
623 }
624
625 raw_ostream &raw_fd_ostream::resetColor() {
626   if (sys::Process::ColorNeedsFlush())
627     flush();
628   const char *colorcode = sys::Process::ResetColor();
629   if (colorcode) {
630     size_t len = strlen(colorcode);
631     write(colorcode, len);
632     // don't account colors towards output characters
633     pos -= len;
634   }
635   return *this;
636 }
637
638 raw_ostream &raw_fd_ostream::reverseColor() {
639   if (sys::Process::ColorNeedsFlush())
640     flush();
641   const char *colorcode = sys::Process::OutputReverse();
642   if (colorcode) {
643     size_t len = strlen(colorcode);
644     write(colorcode, len);
645     // don't account colors towards output characters
646     pos -= len;
647   }
648   return *this;
649 }
650
651 bool raw_fd_ostream::is_displayed() const {
652   return sys::Process::FileDescriptorIsDisplayed(FD);
653 }
654
655 bool raw_fd_ostream::has_colors() const {
656   return sys::Process::FileDescriptorHasColors(FD);
657 }
658
659 //===----------------------------------------------------------------------===//
660 //  outs(), errs(), nulls()
661 //===----------------------------------------------------------------------===//
662
663 /// outs() - This returns a reference to a raw_ostream for standard output.
664 /// Use it like: outs() << "foo" << "bar";
665 raw_ostream &llvm::outs() {
666   // Set buffer settings to model stdout behavior.
667   // Delete the file descriptor when the program exists, forcing error
668   // detection. If you don't want this behavior, don't use outs().
669   static raw_fd_ostream S(STDOUT_FILENO, true);
670   return S;
671 }
672
673 /// errs() - This returns a reference to a raw_ostream for standard error.
674 /// Use it like: errs() << "foo" << "bar";
675 raw_ostream &llvm::errs() {
676   // Set standard error to be unbuffered by default.
677   static raw_fd_ostream S(STDERR_FILENO, false, true);
678   return S;
679 }
680
681 /// nulls() - This returns a reference to a raw_ostream which discards output.
682 raw_ostream &llvm::nulls() {
683   static raw_null_ostream S;
684   return S;
685 }
686
687
688 //===----------------------------------------------------------------------===//
689 //  raw_string_ostream
690 //===----------------------------------------------------------------------===//
691
692 raw_string_ostream::~raw_string_ostream() {
693   flush();
694 }
695
696 void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
697   OS.append(Ptr, Size);
698 }
699
700 //===----------------------------------------------------------------------===//
701 //  raw_svector_ostream
702 //===----------------------------------------------------------------------===//
703
704 // The raw_svector_ostream implementation uses the SmallVector itself as the
705 // buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
706 // always pointing past the end of the vector, but within the vector
707 // capacity. This allows raw_ostream to write directly into the correct place,
708 // and we only need to set the vector size when the data is flushed.
709
710 raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
711   // Set up the initial external buffer. We make sure that the buffer has at
712   // least 128 bytes free; raw_ostream itself only requires 64, but we want to
713   // make sure that we don't grow the buffer unnecessarily on destruction (when
714   // the data is flushed). See the FIXME below.
715   OS.reserve(OS.size() + 128);
716   SetBuffer(OS.end(), OS.capacity() - OS.size());
717 }
718
719 raw_svector_ostream::~raw_svector_ostream() {
720   // FIXME: Prevent resizing during this flush().
721   flush();
722 }
723
724 /// resync - This is called when the SmallVector we're appending to is changed
725 /// outside of the raw_svector_ostream's control.  It is only safe to do this
726 /// if the raw_svector_ostream has previously been flushed.
727 void raw_svector_ostream::resync() {
728   assert(GetNumBytesInBuffer() == 0 && "Didn't flush before mutating vector");
729
730   if (OS.capacity() - OS.size() < 64)
731     OS.reserve(OS.capacity() * 2);
732   SetBuffer(OS.end(), OS.capacity() - OS.size());
733 }
734
735 void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
736   // If we're writing bytes from the end of the buffer into the smallvector, we
737   // don't need to copy the bytes, just commit the bytes because they are
738   // already in the right place.
739   if (Ptr == OS.end()) {
740     assert(OS.size() + Size <= OS.capacity() && "Invalid write_impl() call!");
741     OS.set_size(OS.size() + Size);
742   } else {
743     assert(GetNumBytesInBuffer() == 0 &&
744            "Should be writing from buffer if some bytes in it");
745     // Otherwise, do copy the bytes.
746     OS.append(Ptr, Ptr+Size);
747   }
748
749   // Grow the vector if necessary.
750   if (OS.capacity() - OS.size() < 64)
751     OS.reserve(OS.capacity() * 2);
752
753   // Update the buffer position.
754   SetBuffer(OS.end(), OS.capacity() - OS.size());
755 }
756
757 uint64_t raw_svector_ostream::current_pos() const {
758    return OS.size();
759 }
760
761 StringRef raw_svector_ostream::str() {
762   flush();
763   return StringRef(OS.begin(), OS.size());
764 }
765
766 //===----------------------------------------------------------------------===//
767 //  raw_null_ostream
768 //===----------------------------------------------------------------------===//
769
770 raw_null_ostream::~raw_null_ostream() {
771 #ifndef NDEBUG
772   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
773   // with raw_null_ostream, but it's better to have raw_null_ostream follow
774   // the rules than to change the rules just for raw_null_ostream.
775   flush();
776 #endif
777 }
778
779 void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
780 }
781
782 uint64_t raw_null_ostream::current_pos() const {
783   return 0;
784 }