xref: /freebsd/contrib/llvm-project/llvm/include/llvm/Support/raw_ostream.h (revision 5def4c47d4bd90b209b9b4a4ba9faec15846d8fd)
1 //===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the raw_ostream class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_SUPPORT_RAW_OSTREAM_H
14 #define LLVM_SUPPORT_RAW_OSTREAM_H
15 
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Support/DataTypes.h"
19 #include <cassert>
20 #include <chrono>
21 #include <cstddef>
22 #include <cstdint>
23 #include <cstring>
24 #include <string>
25 #include <system_error>
26 #include <type_traits>
27 
28 namespace llvm {
29 
30 class formatv_object_base;
31 class format_object_base;
32 class FormattedString;
33 class FormattedNumber;
34 class FormattedBytes;
35 template <class T> class LLVM_NODISCARD Expected;
36 
37 namespace sys {
38 namespace fs {
39 enum FileAccess : unsigned;
40 enum OpenFlags : unsigned;
41 enum CreationDisposition : unsigned;
42 class FileLocker;
43 } // end namespace fs
44 } // end namespace sys
45 
46 /// This class implements an extremely fast bulk output stream that can *only*
47 /// output to a stream.  It does not support seeking, reopening, rewinding, line
48 /// buffered disciplines etc. It is a simple buffer that outputs
49 /// a chunk at a time.
50 class raw_ostream {
51 public:
52   // Class kinds to support LLVM-style RTTI.
53   enum class OStreamKind {
54     OK_OStream,
55     OK_FDStream,
56   };
57 
58 private:
59   OStreamKind Kind;
60 
61   /// The buffer is handled in such a way that the buffer is
62   /// uninitialized, unbuffered, or out of space when OutBufCur >=
63   /// OutBufEnd. Thus a single comparison suffices to determine if we
64   /// need to take the slow path to write a single character.
65   ///
66   /// The buffer is in one of three states:
67   ///  1. Unbuffered (BufferMode == Unbuffered)
68   ///  1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
69   ///  2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
70   ///               OutBufEnd - OutBufStart >= 1).
71   ///
72   /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
73   /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
74   /// managed by the subclass.
75   ///
76   /// If a subclass installs an external buffer using SetBuffer then it can wait
77   /// for a \see write_impl() call to handle the data which has been put into
78   /// this buffer.
79   char *OutBufStart, *OutBufEnd, *OutBufCur;
80   bool ColorEnabled = false;
81 
82   /// Optional stream this stream is tied to. If this stream is written to, the
83   /// tied-to stream will be flushed first.
84   raw_ostream *TiedStream = nullptr;
85 
86   enum class BufferKind {
87     Unbuffered = 0,
88     InternalBuffer,
89     ExternalBuffer
90   } BufferMode;
91 
92 public:
93   // color order matches ANSI escape sequence, don't change
94   enum class Colors {
95     BLACK = 0,
96     RED,
97     GREEN,
98     YELLOW,
99     BLUE,
100     MAGENTA,
101     CYAN,
102     WHITE,
103     SAVEDCOLOR,
104     RESET,
105   };
106 
107   static constexpr Colors BLACK = Colors::BLACK;
108   static constexpr Colors RED = Colors::RED;
109   static constexpr Colors GREEN = Colors::GREEN;
110   static constexpr Colors YELLOW = Colors::YELLOW;
111   static constexpr Colors BLUE = Colors::BLUE;
112   static constexpr Colors MAGENTA = Colors::MAGENTA;
113   static constexpr Colors CYAN = Colors::CYAN;
114   static constexpr Colors WHITE = Colors::WHITE;
115   static constexpr Colors SAVEDCOLOR = Colors::SAVEDCOLOR;
116   static constexpr Colors RESET = Colors::RESET;
117 
118   explicit raw_ostream(bool unbuffered = false,
119                        OStreamKind K = OStreamKind::OK_OStream)
120       : Kind(K), BufferMode(unbuffered ? BufferKind::Unbuffered
121                                        : BufferKind::InternalBuffer) {
122     // Start out ready to flush.
123     OutBufStart = OutBufEnd = OutBufCur = nullptr;
124   }
125 
126   raw_ostream(const raw_ostream &) = delete;
127   void operator=(const raw_ostream &) = delete;
128 
129   virtual ~raw_ostream();
130 
131   /// tell - Return the current offset with the file.
132   uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
133 
134   OStreamKind get_kind() const { return Kind; }
135 
136   //===--------------------------------------------------------------------===//
137   // Configuration Interface
138   //===--------------------------------------------------------------------===//
139 
140   /// Set the stream to be buffered, with an automatically determined buffer
141   /// size.
142   void SetBuffered();
143 
144   /// Set the stream to be buffered, using the specified buffer size.
145   void SetBufferSize(size_t Size) {
146     flush();
147     SetBufferAndMode(new char[Size], Size, BufferKind::InternalBuffer);
148   }
149 
150   size_t GetBufferSize() const {
151     // If we're supposed to be buffered but haven't actually gotten around
152     // to allocating the buffer yet, return the value that would be used.
153     if (BufferMode != BufferKind::Unbuffered && OutBufStart == nullptr)
154       return preferred_buffer_size();
155 
156     // Otherwise just return the size of the allocated buffer.
157     return OutBufEnd - OutBufStart;
158   }
159 
160   /// Set the stream to be unbuffered. When unbuffered, the stream will flush
161   /// after every write. This routine will also flush the buffer immediately
162   /// when the stream is being set to unbuffered.
163   void SetUnbuffered() {
164     flush();
165     SetBufferAndMode(nullptr, 0, BufferKind::Unbuffered);
166   }
167 
168   size_t GetNumBytesInBuffer() const {
169     return OutBufCur - OutBufStart;
170   }
171 
172   //===--------------------------------------------------------------------===//
173   // Data Output Interface
174   //===--------------------------------------------------------------------===//
175 
176   void flush() {
177     if (OutBufCur != OutBufStart)
178       flush_nonempty();
179   }
180 
181   raw_ostream &operator<<(char C) {
182     if (OutBufCur >= OutBufEnd)
183       return write(C);
184     *OutBufCur++ = C;
185     return *this;
186   }
187 
188   raw_ostream &operator<<(unsigned char C) {
189     if (OutBufCur >= OutBufEnd)
190       return write(C);
191     *OutBufCur++ = C;
192     return *this;
193   }
194 
195   raw_ostream &operator<<(signed char C) {
196     if (OutBufCur >= OutBufEnd)
197       return write(C);
198     *OutBufCur++ = C;
199     return *this;
200   }
201 
202   raw_ostream &operator<<(StringRef Str) {
203     // Inline fast path, particularly for strings with a known length.
204     size_t Size = Str.size();
205 
206     // Make sure we can use the fast path.
207     if (Size > (size_t)(OutBufEnd - OutBufCur))
208       return write(Str.data(), Size);
209 
210     if (Size) {
211       memcpy(OutBufCur, Str.data(), Size);
212       OutBufCur += Size;
213     }
214     return *this;
215   }
216 
217   raw_ostream &operator<<(const char *Str) {
218     // Inline fast path, particularly for constant strings where a sufficiently
219     // smart compiler will simplify strlen.
220 
221     return this->operator<<(StringRef(Str));
222   }
223 
224   raw_ostream &operator<<(const std::string &Str) {
225     // Avoid the fast path, it would only increase code size for a marginal win.
226     return write(Str.data(), Str.length());
227   }
228 
229   raw_ostream &operator<<(const SmallVectorImpl<char> &Str) {
230     return write(Str.data(), Str.size());
231   }
232 
233   raw_ostream &operator<<(unsigned long N);
234   raw_ostream &operator<<(long N);
235   raw_ostream &operator<<(unsigned long long N);
236   raw_ostream &operator<<(long long N);
237   raw_ostream &operator<<(const void *P);
238 
239   raw_ostream &operator<<(unsigned int N) {
240     return this->operator<<(static_cast<unsigned long>(N));
241   }
242 
243   raw_ostream &operator<<(int N) {
244     return this->operator<<(static_cast<long>(N));
245   }
246 
247   raw_ostream &operator<<(double N);
248 
249   /// Output \p N in hexadecimal, without any prefix or padding.
250   raw_ostream &write_hex(unsigned long long N);
251 
252   // Change the foreground color of text.
253   raw_ostream &operator<<(Colors C);
254 
255   /// Output a formatted UUID with dash separators.
256   using uuid_t = uint8_t[16];
257   raw_ostream &write_uuid(const uuid_t UUID);
258 
259   /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
260   /// satisfy llvm::isPrint into an escape sequence.
261   raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
262 
263   raw_ostream &write(unsigned char C);
264   raw_ostream &write(const char *Ptr, size_t Size);
265 
266   // Formatted output, see the format() function in Support/Format.h.
267   raw_ostream &operator<<(const format_object_base &Fmt);
268 
269   // Formatted output, see the leftJustify() function in Support/Format.h.
270   raw_ostream &operator<<(const FormattedString &);
271 
272   // Formatted output, see the formatHex() function in Support/Format.h.
273   raw_ostream &operator<<(const FormattedNumber &);
274 
275   // Formatted output, see the formatv() function in Support/FormatVariadic.h.
276   raw_ostream &operator<<(const formatv_object_base &);
277 
278   // Formatted output, see the format_bytes() function in Support/Format.h.
279   raw_ostream &operator<<(const FormattedBytes &);
280 
281   /// indent - Insert 'NumSpaces' spaces.
282   raw_ostream &indent(unsigned NumSpaces);
283 
284   /// write_zeros - Insert 'NumZeros' nulls.
285   raw_ostream &write_zeros(unsigned NumZeros);
286 
287   /// Changes the foreground color of text that will be output from this point
288   /// forward.
289   /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
290   /// change only the bold attribute, and keep colors untouched
291   /// @param Bold bold/brighter text, default false
292   /// @param BG if true change the background, default: change foreground
293   /// @returns itself so it can be used within << invocations
294   virtual raw_ostream &changeColor(enum Colors Color, bool Bold = false,
295                                    bool BG = false);
296 
297   /// Resets the colors to terminal defaults. Call this when you are done
298   /// outputting colored text, or before program exit.
299   virtual raw_ostream &resetColor();
300 
301   /// Reverses the foreground and background colors.
302   virtual raw_ostream &reverseColor();
303 
304   /// This function determines if this stream is connected to a "tty" or
305   /// "console" window. That is, the output would be displayed to the user
306   /// rather than being put on a pipe or stored in a file.
307   virtual bool is_displayed() const { return false; }
308 
309   /// This function determines if this stream is displayed and supports colors.
310   /// The result is unaffected by calls to enable_color().
311   virtual bool has_colors() const { return is_displayed(); }
312 
313   // Enable or disable colors. Once enable_colors(false) is called,
314   // changeColor() has no effect until enable_colors(true) is called.
315   virtual void enable_colors(bool enable) { ColorEnabled = enable; }
316 
317   /// Tie this stream to the specified stream. Replaces any existing tied-to
318   /// stream. Specifying a nullptr unties the stream.
319   void tie(raw_ostream *TieTo) { TiedStream = TieTo; }
320 
321   //===--------------------------------------------------------------------===//
322   // Subclass Interface
323   //===--------------------------------------------------------------------===//
324 
325 private:
326   /// The is the piece of the class that is implemented by subclasses.  This
327   /// writes the \p Size bytes starting at
328   /// \p Ptr to the underlying stream.
329   ///
330   /// This function is guaranteed to only be called at a point at which it is
331   /// safe for the subclass to install a new buffer via SetBuffer.
332   ///
333   /// \param Ptr The start of the data to be written. For buffered streams this
334   /// is guaranteed to be the start of the buffer.
335   ///
336   /// \param Size The number of bytes to be written.
337   ///
338   /// \invariant { Size > 0 }
339   virtual void write_impl(const char *Ptr, size_t Size) = 0;
340 
341   /// Return the current position within the stream, not counting the bytes
342   /// currently in the buffer.
343   virtual uint64_t current_pos() const = 0;
344 
345 protected:
346   /// Use the provided buffer as the raw_ostream buffer. This is intended for
347   /// use only by subclasses which can arrange for the output to go directly
348   /// into the desired output buffer, instead of being copied on each flush.
349   void SetBuffer(char *BufferStart, size_t Size) {
350     SetBufferAndMode(BufferStart, Size, BufferKind::ExternalBuffer);
351   }
352 
353   /// Return an efficient buffer size for the underlying output mechanism.
354   virtual size_t preferred_buffer_size() const;
355 
356   /// Return the beginning of the current stream buffer, or 0 if the stream is
357   /// unbuffered.
358   const char *getBufferStart() const { return OutBufStart; }
359 
360   //===--------------------------------------------------------------------===//
361   // Private Interface
362   //===--------------------------------------------------------------------===//
363 private:
364   /// Install the given buffer and mode.
365   void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
366 
367   /// Flush the current buffer, which is known to be non-empty. This outputs the
368   /// currently buffered data and resets the buffer to empty.
369   void flush_nonempty();
370 
371   /// Copy data into the buffer. Size must not be greater than the number of
372   /// unused bytes in the buffer.
373   void copy_to_buffer(const char *Ptr, size_t Size);
374 
375   /// Compute whether colors should be used and do the necessary work such as
376   /// flushing. The result is affected by calls to enable_color().
377   bool prepare_colors();
378 
379   /// Flush the tied-to stream (if present) and then write the required data.
380   void flush_tied_then_write(const char *Ptr, size_t Size);
381 
382   virtual void anchor();
383 };
384 
385 /// Call the appropriate insertion operator, given an rvalue reference to a
386 /// raw_ostream object and return a stream of the same type as the argument.
387 template <typename OStream, typename T>
388 std::enable_if_t<!std::is_reference<OStream>::value &&
389                      std::is_base_of<raw_ostream, OStream>::value,
390                  OStream &&>
391 operator<<(OStream &&OS, const T &Value) {
392   OS << Value;
393   return std::move(OS);
394 }
395 
396 /// An abstract base class for streams implementations that also support a
397 /// pwrite operation. This is useful for code that can mostly stream out data,
398 /// but needs to patch in a header that needs to know the output size.
399 class raw_pwrite_stream : public raw_ostream {
400   virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
401   void anchor() override;
402 
403 public:
404   explicit raw_pwrite_stream(bool Unbuffered = false,
405                              OStreamKind K = OStreamKind::OK_OStream)
406       : raw_ostream(Unbuffered, K) {}
407   void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
408 #ifndef NDEBUG
409     uint64_t Pos = tell();
410     // /dev/null always reports a pos of 0, so we cannot perform this check
411     // in that case.
412     if (Pos)
413       assert(Size + Offset <= Pos && "We don't support extending the stream");
414 #endif
415     pwrite_impl(Ptr, Size, Offset);
416   }
417 };
418 
419 //===----------------------------------------------------------------------===//
420 // File Output Streams
421 //===----------------------------------------------------------------------===//
422 
423 /// A raw_ostream that writes to a file descriptor.
424 ///
425 class raw_fd_ostream : public raw_pwrite_stream {
426   int FD;
427   bool ShouldClose;
428   bool SupportsSeeking = false;
429   mutable Optional<bool> HasColors;
430 
431 #ifdef _WIN32
432   /// True if this fd refers to a Windows console device. Mintty and other
433   /// terminal emulators are TTYs, but they are not consoles.
434   bool IsWindowsConsole = false;
435 #endif
436 
437   std::error_code EC;
438 
439   uint64_t pos = 0;
440 
441   /// See raw_ostream::write_impl.
442   void write_impl(const char *Ptr, size_t Size) override;
443 
444   void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
445 
446   /// Return the current position within the stream, not counting the bytes
447   /// currently in the buffer.
448   uint64_t current_pos() const override { return pos; }
449 
450   /// Determine an efficient buffer size.
451   size_t preferred_buffer_size() const override;
452 
453   void anchor() override;
454 
455 protected:
456   /// Set the flag indicating that an output error has been encountered.
457   void error_detected(std::error_code EC) { this->EC = EC; }
458 
459   /// Return the file descriptor.
460   int get_fd() const { return FD; }
461 
462   // Update the file position by increasing \p Delta.
463   void inc_pos(uint64_t Delta) { pos += Delta; }
464 
465 public:
466   /// Open the specified file for writing. If an error occurs, information
467   /// about the error is put into EC, and the stream should be immediately
468   /// destroyed;
469   /// \p Flags allows optional flags to control how the file will be opened.
470   ///
471   /// As a special case, if Filename is "-", then the stream will use
472   /// STDOUT_FILENO instead of opening a file. This will not close the stdout
473   /// descriptor.
474   raw_fd_ostream(StringRef Filename, std::error_code &EC);
475   raw_fd_ostream(StringRef Filename, std::error_code &EC,
476                  sys::fs::CreationDisposition Disp);
477   raw_fd_ostream(StringRef Filename, std::error_code &EC,
478                  sys::fs::FileAccess Access);
479   raw_fd_ostream(StringRef Filename, std::error_code &EC,
480                  sys::fs::OpenFlags Flags);
481   raw_fd_ostream(StringRef Filename, std::error_code &EC,
482                  sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access,
483                  sys::fs::OpenFlags Flags);
484 
485   /// FD is the file descriptor that this writes to.  If ShouldClose is true,
486   /// this closes the file when the stream is destroyed. If FD is for stdout or
487   /// stderr, it will not be closed.
488   raw_fd_ostream(int fd, bool shouldClose, bool unbuffered = false,
489                  OStreamKind K = OStreamKind::OK_OStream);
490 
491   ~raw_fd_ostream() override;
492 
493   /// Manually flush the stream and close the file. Note that this does not call
494   /// fsync.
495   void close();
496 
497   bool supportsSeeking() const { return SupportsSeeking; }
498 
499   /// Flushes the stream and repositions the underlying file descriptor position
500   /// to the offset specified from the beginning of the file.
501   uint64_t seek(uint64_t off);
502 
503   bool is_displayed() const override;
504 
505   bool has_colors() const override;
506 
507   std::error_code error() const { return EC; }
508 
509   /// Return the value of the flag in this raw_fd_ostream indicating whether an
510   /// output error has been encountered.
511   /// This doesn't implicitly flush any pending output.  Also, it doesn't
512   /// guarantee to detect all errors unless the stream has been closed.
513   bool has_error() const { return bool(EC); }
514 
515   /// Set the flag read by has_error() to false. If the error flag is set at the
516   /// time when this raw_ostream's destructor is called, report_fatal_error is
517   /// called to report the error. Use clear_error() after handling the error to
518   /// avoid this behavior.
519   ///
520   ///   "Errors should never pass silently.
521   ///    Unless explicitly silenced."
522   ///      - from The Zen of Python, by Tim Peters
523   ///
524   void clear_error() { EC = std::error_code(); }
525 
526   /// Locks the underlying file.
527   ///
528   /// @returns RAII object that releases the lock upon leaving the scope, if the
529   ///          locking was successful. Otherwise returns corresponding
530   ///          error code.
531   ///
532   /// The function blocks the current thread until the lock become available or
533   /// error occurs.
534   ///
535   /// Possible use of this function may be as follows:
536   ///
537   ///   @code{.cpp}
538   ///   if (auto L = stream.lock()) {
539   ///     // ... do action that require file to be locked.
540   ///   } else {
541   ///     handleAllErrors(std::move(L.takeError()), [&](ErrorInfoBase &EIB) {
542   ///       // ... handle lock error.
543   ///     });
544   ///   }
545   ///   @endcode
546   LLVM_NODISCARD Expected<sys::fs::FileLocker> lock();
547 
548   /// Tries to lock the underlying file within the specified period.
549   ///
550   /// @returns RAII object that releases the lock upon leaving the scope, if the
551   ///          locking was successful. Otherwise returns corresponding
552   ///          error code.
553   ///
554   /// It is used as @ref lock.
555   LLVM_NODISCARD
556   Expected<sys::fs::FileLocker> tryLockFor(std::chrono::milliseconds Timeout);
557 };
558 
559 /// This returns a reference to a raw_fd_ostream for standard output. Use it
560 /// like: outs() << "foo" << "bar";
561 raw_fd_ostream &outs();
562 
563 /// This returns a reference to a raw_ostream for standard error.
564 /// Use it like: errs() << "foo" << "bar";
565 /// By default, the stream is tied to stdout to ensure stdout is flushed before
566 /// stderr is written, to ensure the error messages are written in their
567 /// expected place.
568 raw_fd_ostream &errs();
569 
570 /// This returns a reference to a raw_ostream which simply discards output.
571 raw_ostream &nulls();
572 
573 //===----------------------------------------------------------------------===//
574 // File Streams
575 //===----------------------------------------------------------------------===//
576 
577 /// A raw_ostream of a file for reading/writing/seeking.
578 ///
579 class raw_fd_stream : public raw_fd_ostream {
580 public:
581   /// Open the specified file for reading/writing/seeking. If an error occurs,
582   /// information about the error is put into EC, and the stream should be
583   /// immediately destroyed.
584   raw_fd_stream(StringRef Filename, std::error_code &EC);
585 
586   /// This reads the \p Size bytes into a buffer pointed by \p Ptr.
587   ///
588   /// \param Ptr The start of the buffer to hold data to be read.
589   ///
590   /// \param Size The number of bytes to be read.
591   ///
592   /// On success, the number of bytes read is returned, and the file position is
593   /// advanced by this number. On error, -1 is returned, use error() to get the
594   /// error code.
595   ssize_t read(char *Ptr, size_t Size);
596 
597   /// Check if \p OS is a pointer of type raw_fd_stream*.
598   static bool classof(const raw_ostream *OS);
599 };
600 
601 //===----------------------------------------------------------------------===//
602 // Output Stream Adaptors
603 //===----------------------------------------------------------------------===//
604 
605 /// A raw_ostream that writes to an std::string.  This is a simple adaptor
606 /// class. This class does not encounter output errors.
607 class raw_string_ostream : public raw_ostream {
608   std::string &OS;
609 
610   /// See raw_ostream::write_impl.
611   void write_impl(const char *Ptr, size_t Size) override;
612 
613   /// Return the current position within the stream, not counting the bytes
614   /// currently in the buffer.
615   uint64_t current_pos() const override { return OS.size(); }
616 
617 public:
618   explicit raw_string_ostream(std::string &O) : OS(O) {
619     SetUnbuffered();
620   }
621   ~raw_string_ostream() override;
622 
623   /// Flushes the stream contents to the target string and returns  the string's
624   /// reference.
625   std::string& str() {
626     flush();
627     return OS;
628   }
629 };
630 
631 /// A raw_ostream that writes to an SmallVector or SmallString.  This is a
632 /// simple adaptor class. This class does not encounter output errors.
633 /// raw_svector_ostream operates without a buffer, delegating all memory
634 /// management to the SmallString. Thus the SmallString is always up-to-date,
635 /// may be used directly and there is no need to call flush().
636 class raw_svector_ostream : public raw_pwrite_stream {
637   SmallVectorImpl<char> &OS;
638 
639   /// See raw_ostream::write_impl.
640   void write_impl(const char *Ptr, size_t Size) override;
641 
642   void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
643 
644   /// Return the current position within the stream.
645   uint64_t current_pos() const override;
646 
647 public:
648   /// Construct a new raw_svector_ostream.
649   ///
650   /// \param O The vector to write to; this should generally have at least 128
651   /// bytes free to avoid any extraneous memory overhead.
652   explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
653     SetUnbuffered();
654   }
655 
656   ~raw_svector_ostream() override = default;
657 
658   void flush() = delete;
659 
660   /// Return a StringRef for the vector contents.
661   StringRef str() const { return StringRef(OS.data(), OS.size()); }
662 };
663 
664 /// A raw_ostream that discards all output.
665 class raw_null_ostream : public raw_pwrite_stream {
666   /// See raw_ostream::write_impl.
667   void write_impl(const char *Ptr, size_t size) override;
668   void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
669 
670   /// Return the current position within the stream, not counting the bytes
671   /// currently in the buffer.
672   uint64_t current_pos() const override;
673 
674 public:
675   explicit raw_null_ostream() = default;
676   ~raw_null_ostream() override;
677 };
678 
679 class buffer_ostream : public raw_svector_ostream {
680   raw_ostream &OS;
681   SmallVector<char, 0> Buffer;
682 
683   virtual void anchor() override;
684 
685 public:
686   buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {}
687   ~buffer_ostream() override { OS << str(); }
688 };
689 
690 class buffer_unique_ostream : public raw_svector_ostream {
691   std::unique_ptr<raw_ostream> OS;
692   SmallVector<char, 0> Buffer;
693 
694   virtual void anchor() override;
695 
696 public:
697   buffer_unique_ostream(std::unique_ptr<raw_ostream> OS)
698       : raw_svector_ostream(Buffer), OS(std::move(OS)) {}
699   ~buffer_unique_ostream() override { *OS << str(); }
700 };
701 
702 } // end namespace llvm
703 
704 #endif // LLVM_SUPPORT_RAW_OSTREAM_H
705