1 //===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===//
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 file defines the raw_ostream class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_SUPPORT_RAW_OSTREAM_H
15 #define LLVM_SUPPORT_RAW_OSTREAM_H
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
24 #include <system_error>
28 class formatv_object_base;
29 class format_object_base;
30 class FormattedString;
31 class FormattedNumber;
36 enum FileAccess : unsigned;
37 enum OpenFlags : unsigned;
38 enum CreationDisposition : unsigned;
40 } // end namespace sys
42 /// This class implements an extremely fast bulk output stream that can *only*
43 /// output to a stream. It does not support seeking, reopening, rewinding, line
44 /// buffered disciplines etc. It is a simple buffer that outputs
45 /// a chunk at a time.
48 /// The buffer is handled in such a way that the buffer is
49 /// uninitialized, unbuffered, or out of space when OutBufCur >=
50 /// OutBufEnd. Thus a single comparison suffices to determine if we
51 /// need to take the slow path to write a single character.
53 /// The buffer is in one of three states:
54 /// 1. Unbuffered (BufferMode == Unbuffered)
55 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
56 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
57 /// OutBufEnd - OutBufStart >= 1).
59 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
60 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
61 /// managed by the subclass.
63 /// If a subclass installs an external buffer using SetBuffer then it can wait
64 /// for a \see write_impl() call to handle the data which has been put into
66 char *OutBufStart, *OutBufEnd, *OutBufCur;
75 // color order matches ANSI escape sequence, don't change
88 explicit raw_ostream(bool unbuffered = false)
89 : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
90 // Start out ready to flush.
91 OutBufStart = OutBufEnd = OutBufCur = nullptr;
94 raw_ostream(const raw_ostream &) = delete;
95 void operator=(const raw_ostream &) = delete;
97 virtual ~raw_ostream();
99 /// tell - Return the current offset with the file.
100 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
102 //===--------------------------------------------------------------------===//
103 // Configuration Interface
104 //===--------------------------------------------------------------------===//
106 /// Set the stream to be buffered, with an automatically determined buffer
110 /// Set the stream to be buffered, using the specified buffer size.
111 void SetBufferSize(size_t Size) {
113 SetBufferAndMode(new char[Size], Size, InternalBuffer);
116 size_t GetBufferSize() const {
117 // If we're supposed to be buffered but haven't actually gotten around
118 // to allocating the buffer yet, return the value that would be used.
119 if (BufferMode != Unbuffered && OutBufStart == nullptr)
120 return preferred_buffer_size();
122 // Otherwise just return the size of the allocated buffer.
123 return OutBufEnd - OutBufStart;
126 /// Set the stream to be unbuffered. When unbuffered, the stream will flush
127 /// after every write. This routine will also flush the buffer immediately
128 /// when the stream is being set to unbuffered.
129 void SetUnbuffered() {
131 SetBufferAndMode(nullptr, 0, Unbuffered);
134 size_t GetNumBytesInBuffer() const {
135 return OutBufCur - OutBufStart;
138 //===--------------------------------------------------------------------===//
139 // Data Output Interface
140 //===--------------------------------------------------------------------===//
143 if (OutBufCur != OutBufStart)
147 raw_ostream &operator<<(char C) {
148 if (OutBufCur >= OutBufEnd)
154 raw_ostream &operator<<(unsigned char C) {
155 if (OutBufCur >= OutBufEnd)
161 raw_ostream &operator<<(signed char C) {
162 if (OutBufCur >= OutBufEnd)
168 raw_ostream &operator<<(StringRef Str) {
169 // Inline fast path, particularly for strings with a known length.
170 size_t Size = Str.size();
172 // Make sure we can use the fast path.
173 if (Size > (size_t)(OutBufEnd - OutBufCur))
174 return write(Str.data(), Size);
177 memcpy(OutBufCur, Str.data(), Size);
183 raw_ostream &operator<<(const char *Str) {
184 // Inline fast path, particularly for constant strings where a sufficiently
185 // smart compiler will simplify strlen.
187 return this->operator<<(StringRef(Str));
190 raw_ostream &operator<<(const std::string &Str) {
191 // Avoid the fast path, it would only increase code size for a marginal win.
192 return write(Str.data(), Str.length());
195 raw_ostream &operator<<(const SmallVectorImpl<char> &Str) {
196 return write(Str.data(), Str.size());
199 raw_ostream &operator<<(unsigned long N);
200 raw_ostream &operator<<(long N);
201 raw_ostream &operator<<(unsigned long long N);
202 raw_ostream &operator<<(long long N);
203 raw_ostream &operator<<(const void *P);
205 raw_ostream &operator<<(unsigned int N) {
206 return this->operator<<(static_cast<unsigned long>(N));
209 raw_ostream &operator<<(int N) {
210 return this->operator<<(static_cast<long>(N));
213 raw_ostream &operator<<(double N);
215 /// Output \p N in hexadecimal, without any prefix or padding.
216 raw_ostream &write_hex(unsigned long long N);
218 /// Output a formatted UUID with dash separators.
219 using uuid_t = uint8_t[16];
220 raw_ostream &write_uuid(const uuid_t UUID);
222 /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't
223 /// satisfy std::isprint into an escape sequence.
224 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
226 raw_ostream &write(unsigned char C);
227 raw_ostream &write(const char *Ptr, size_t Size);
229 // Formatted output, see the format() function in Support/Format.h.
230 raw_ostream &operator<<(const format_object_base &Fmt);
232 // Formatted output, see the leftJustify() function in Support/Format.h.
233 raw_ostream &operator<<(const FormattedString &);
235 // Formatted output, see the formatHex() function in Support/Format.h.
236 raw_ostream &operator<<(const FormattedNumber &);
238 // Formatted output, see the formatv() function in Support/FormatVariadic.h.
239 raw_ostream &operator<<(const formatv_object_base &);
241 // Formatted output, see the format_bytes() function in Support/Format.h.
242 raw_ostream &operator<<(const FormattedBytes &);
244 /// indent - Insert 'NumSpaces' spaces.
245 raw_ostream &indent(unsigned NumSpaces);
247 /// write_zeros - Insert 'NumZeros' nulls.
248 raw_ostream &write_zeros(unsigned NumZeros);
250 /// Changes the foreground color of text that will be output from this point
252 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
253 /// change only the bold attribute, and keep colors untouched
254 /// @param Bold bold/brighter text, default false
255 /// @param BG if true change the background, default: change foreground
256 /// @returns itself so it can be used within << invocations
257 virtual raw_ostream &changeColor(enum Colors Color,
266 /// Resets the colors to terminal defaults. Call this when you are done
267 /// outputting colored text, or before program exit.
268 virtual raw_ostream &resetColor() { return *this; }
270 /// Reverses the foreground and background colors.
271 virtual raw_ostream &reverseColor() { return *this; }
273 /// This function determines if this stream is connected to a "tty" or
274 /// "console" window. That is, the output would be displayed to the user
275 /// rather than being put on a pipe or stored in a file.
276 virtual bool is_displayed() const { return false; }
278 /// This function determines if this stream is displayed and supports colors.
279 virtual bool has_colors() const { return is_displayed(); }
281 //===--------------------------------------------------------------------===//
282 // Subclass Interface
283 //===--------------------------------------------------------------------===//
286 /// The is the piece of the class that is implemented by subclasses. This
287 /// writes the \p Size bytes starting at
288 /// \p Ptr to the underlying stream.
290 /// This function is guaranteed to only be called at a point at which it is
291 /// safe for the subclass to install a new buffer via SetBuffer.
293 /// \param Ptr The start of the data to be written. For buffered streams this
294 /// is guaranteed to be the start of the buffer.
296 /// \param Size The number of bytes to be written.
298 /// \invariant { Size > 0 }
299 virtual void write_impl(const char *Ptr, size_t Size) = 0;
301 /// Return the current position within the stream, not counting the bytes
302 /// currently in the buffer.
303 virtual uint64_t current_pos() const = 0;
306 /// Use the provided buffer as the raw_ostream buffer. This is intended for
307 /// use only by subclasses which can arrange for the output to go directly
308 /// into the desired output buffer, instead of being copied on each flush.
309 void SetBuffer(char *BufferStart, size_t Size) {
310 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
313 /// Return an efficient buffer size for the underlying output mechanism.
314 virtual size_t preferred_buffer_size() const;
316 /// Return the beginning of the current stream buffer, or 0 if the stream is
318 const char *getBufferStart() const { return OutBufStart; }
320 //===--------------------------------------------------------------------===//
322 //===--------------------------------------------------------------------===//
324 /// Install the given buffer and mode.
325 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
327 /// Flush the current buffer, which is known to be non-empty. This outputs the
328 /// currently buffered data and resets the buffer to empty.
329 void flush_nonempty();
331 /// Copy data into the buffer. Size must not be greater than the number of
332 /// unused bytes in the buffer.
333 void copy_to_buffer(const char *Ptr, size_t Size);
335 virtual void anchor();
338 /// An abstract base class for streams implementations that also support a
339 /// pwrite operation. This is useful for code that can mostly stream out data,
340 /// but needs to patch in a header that needs to know the output size.
341 class raw_pwrite_stream : public raw_ostream {
342 virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0;
343 void anchor() override;
346 explicit raw_pwrite_stream(bool Unbuffered = false)
347 : raw_ostream(Unbuffered) {}
348 void pwrite(const char *Ptr, size_t Size, uint64_t Offset) {
350 uint64_t Pos = tell();
351 // /dev/null always reports a pos of 0, so we cannot perform this check
354 assert(Size + Offset <= Pos && "We don't support extending the stream");
356 pwrite_impl(Ptr, Size, Offset);
360 //===----------------------------------------------------------------------===//
361 // File Output Streams
362 //===----------------------------------------------------------------------===//
364 /// A raw_ostream that writes to a file descriptor.
366 class raw_fd_ostream : public raw_pwrite_stream {
374 bool SupportsSeeking;
376 /// See raw_ostream::write_impl.
377 void write_impl(const char *Ptr, size_t Size) override;
379 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
381 /// Return the current position within the stream, not counting the bytes
382 /// currently in the buffer.
383 uint64_t current_pos() const override { return pos; }
385 /// Determine an efficient buffer size.
386 size_t preferred_buffer_size() const override;
388 /// Set the flag indicating that an output error has been encountered.
389 void error_detected(std::error_code EC) { this->EC = EC; }
391 void anchor() override;
394 /// Open the specified file for writing. If an error occurs, information
395 /// about the error is put into EC, and the stream should be immediately
397 /// \p Flags allows optional flags to control how the file will be opened.
399 /// As a special case, if Filename is "-", then the stream will use
400 /// STDOUT_FILENO instead of opening a file. This will not close the stdout
402 raw_fd_ostream(StringRef Filename, std::error_code &EC);
403 raw_fd_ostream(StringRef Filename, std::error_code &EC,
404 sys::fs::CreationDisposition Disp);
405 raw_fd_ostream(StringRef Filename, std::error_code &EC,
406 sys::fs::FileAccess Access);
407 raw_fd_ostream(StringRef Filename, std::error_code &EC,
408 sys::fs::OpenFlags Flags);
409 raw_fd_ostream(StringRef Filename, std::error_code &EC,
410 sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access,
411 sys::fs::OpenFlags Flags);
413 /// FD is the file descriptor that this writes to. If ShouldClose is true,
414 /// this closes the file when the stream is destroyed. If FD is for stdout or
415 /// stderr, it will not be closed.
416 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
418 ~raw_fd_ostream() override;
420 /// Manually flush the stream and close the file. Note that this does not call
424 bool supportsSeeking() { return SupportsSeeking; }
426 /// Flushes the stream and repositions the underlying file descriptor position
427 /// to the offset specified from the beginning of the file.
428 uint64_t seek(uint64_t off);
430 raw_ostream &changeColor(enum Colors colors, bool bold=false,
431 bool bg=false) override;
432 raw_ostream &resetColor() override;
434 raw_ostream &reverseColor() override;
436 bool is_displayed() const override;
438 bool has_colors() const override;
440 std::error_code error() const { return EC; }
442 /// Return the value of the flag in this raw_fd_ostream indicating whether an
443 /// output error has been encountered.
444 /// This doesn't implicitly flush any pending output. Also, it doesn't
445 /// guarantee to detect all errors unless the stream has been closed.
446 bool has_error() const { return bool(EC); }
448 /// Set the flag read by has_error() to false. If the error flag is set at the
449 /// time when this raw_ostream's destructor is called, report_fatal_error is
450 /// called to report the error. Use clear_error() after handling the error to
451 /// avoid this behavior.
453 /// "Errors should never pass silently.
454 /// Unless explicitly silenced."
455 /// - from The Zen of Python, by Tim Peters
457 void clear_error() { EC = std::error_code(); }
460 /// This returns a reference to a raw_ostream for standard output. Use it like:
461 /// outs() << "foo" << "bar";
464 /// This returns a reference to a raw_ostream for standard error. Use it like:
465 /// errs() << "foo" << "bar";
468 /// This returns a reference to a raw_ostream which simply discards output.
469 raw_ostream &nulls();
471 //===----------------------------------------------------------------------===//
472 // Output Stream Adaptors
473 //===----------------------------------------------------------------------===//
475 /// A raw_ostream that writes to an std::string. This is a simple adaptor
476 /// class. This class does not encounter output errors.
477 class raw_string_ostream : public raw_ostream {
480 /// See raw_ostream::write_impl.
481 void write_impl(const char *Ptr, size_t Size) override;
483 /// Return the current position within the stream, not counting the bytes
484 /// currently in the buffer.
485 uint64_t current_pos() const override { return OS.size(); }
488 explicit raw_string_ostream(std::string &O) : OS(O) {}
489 ~raw_string_ostream() override;
491 /// Flushes the stream contents to the target string and returns the string's
499 /// A raw_ostream that writes to an SmallVector or SmallString. This is a
500 /// simple adaptor class. This class does not encounter output errors.
501 /// raw_svector_ostream operates without a buffer, delegating all memory
502 /// management to the SmallString. Thus the SmallString is always up-to-date,
503 /// may be used directly and there is no need to call flush().
504 class raw_svector_ostream : public raw_pwrite_stream {
505 SmallVectorImpl<char> &OS;
507 /// See raw_ostream::write_impl.
508 void write_impl(const char *Ptr, size_t Size) override;
510 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
512 /// Return the current position within the stream.
513 uint64_t current_pos() const override;
516 /// Construct a new raw_svector_ostream.
518 /// \param O The vector to write to; this should generally have at least 128
519 /// bytes free to avoid any extraneous memory overhead.
520 explicit raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
524 ~raw_svector_ostream() override = default;
526 void flush() = delete;
528 /// Return a StringRef for the vector contents.
529 StringRef str() { return StringRef(OS.data(), OS.size()); }
532 /// A raw_ostream that discards all output.
533 class raw_null_ostream : public raw_pwrite_stream {
534 /// See raw_ostream::write_impl.
535 void write_impl(const char *Ptr, size_t size) override;
536 void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override;
538 /// Return the current position within the stream, not counting the bytes
539 /// currently in the buffer.
540 uint64_t current_pos() const override;
543 explicit raw_null_ostream() = default;
544 ~raw_null_ostream() override;
547 class buffer_ostream : public raw_svector_ostream {
549 SmallVector<char, 0> Buffer;
552 buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {}
553 ~buffer_ostream() override { OS << str(); }
556 } // end namespace llvm
558 #endif // LLVM_SUPPORT_RAW_OSTREAM_H