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/StringRef.h"
18 #include "llvm/Support/Compiler.h"
19 #include "llvm/Support/DataTypes.h"
22 class format_object_base;
24 class SmallVectorImpl;
28 enum OpenFlags : unsigned;
32 /// raw_ostream - This class implements an extremely fast bulk output stream
33 /// that can *only* output to a stream. It does not support seeking, reopening,
34 /// rewinding, line buffered disciplines etc. It is a simple buffer that outputs
35 /// a chunk at a time.
38 void operator=(const raw_ostream &) LLVM_DELETED_FUNCTION;
39 raw_ostream(const raw_ostream &) LLVM_DELETED_FUNCTION;
41 /// The buffer is handled in such a way that the buffer is
42 /// uninitialized, unbuffered, or out of space when OutBufCur >=
43 /// OutBufEnd. Thus a single comparison suffices to determine if we
44 /// need to take the slow path to write a single character.
46 /// The buffer is in one of three states:
47 /// 1. Unbuffered (BufferMode == Unbuffered)
48 /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0).
49 /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 &&
50 /// OutBufEnd - OutBufStart >= 1).
52 /// If buffered, then the raw_ostream owns the buffer if (BufferMode ==
53 /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is
54 /// managed by the subclass.
56 /// If a subclass installs an external buffer using SetBuffer then it can wait
57 /// for a \see write_impl() call to handle the data which has been put into
59 char *OutBufStart, *OutBufEnd, *OutBufCur;
68 // color order matches ANSI escape sequence, don't change
81 explicit raw_ostream(bool unbuffered=false)
82 : BufferMode(unbuffered ? Unbuffered : InternalBuffer) {
83 // Start out ready to flush.
84 OutBufStart = OutBufEnd = OutBufCur = nullptr;
87 virtual ~raw_ostream();
89 /// tell - Return the current offset with the file.
90 uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); }
92 //===--------------------------------------------------------------------===//
93 // Configuration Interface
94 //===--------------------------------------------------------------------===//
96 /// SetBuffered - Set the stream to be buffered, with an automatically
97 /// determined buffer size.
100 /// SetBufferSize - Set the stream to be buffered, using the
101 /// specified buffer size.
102 void SetBufferSize(size_t Size) {
104 SetBufferAndMode(new char[Size], Size, InternalBuffer);
107 size_t GetBufferSize() const {
108 // If we're supposed to be buffered but haven't actually gotten around
109 // to allocating the buffer yet, return the value that would be used.
110 if (BufferMode != Unbuffered && OutBufStart == nullptr)
111 return preferred_buffer_size();
113 // Otherwise just return the size of the allocated buffer.
114 return OutBufEnd - OutBufStart;
117 /// SetUnbuffered - Set the stream to be unbuffered. When
118 /// unbuffered, the stream will flush after every write. This routine
119 /// will also flush the buffer immediately when the stream is being
120 /// set to unbuffered.
121 void SetUnbuffered() {
123 SetBufferAndMode(nullptr, 0, Unbuffered);
126 size_t GetNumBytesInBuffer() const {
127 return OutBufCur - OutBufStart;
130 //===--------------------------------------------------------------------===//
131 // Data Output Interface
132 //===--------------------------------------------------------------------===//
135 if (OutBufCur != OutBufStart)
139 raw_ostream &operator<<(char C) {
140 if (OutBufCur >= OutBufEnd)
146 raw_ostream &operator<<(unsigned char C) {
147 if (OutBufCur >= OutBufEnd)
153 raw_ostream &operator<<(signed char C) {
154 if (OutBufCur >= OutBufEnd)
160 raw_ostream &operator<<(StringRef Str) {
161 // Inline fast path, particularly for strings with a known length.
162 size_t Size = Str.size();
164 // Make sure we can use the fast path.
165 if (Size > (size_t)(OutBufEnd - OutBufCur))
166 return write(Str.data(), Size);
168 memcpy(OutBufCur, Str.data(), Size);
173 raw_ostream &operator<<(const char *Str) {
174 // Inline fast path, particularly for constant strings where a sufficiently
175 // smart compiler will simplify strlen.
177 return this->operator<<(StringRef(Str));
180 raw_ostream &operator<<(const std::string &Str) {
181 // Avoid the fast path, it would only increase code size for a marginal win.
182 return write(Str.data(), Str.length());
185 raw_ostream &operator<<(unsigned long N);
186 raw_ostream &operator<<(long N);
187 raw_ostream &operator<<(unsigned long long N);
188 raw_ostream &operator<<(long long N);
189 raw_ostream &operator<<(const void *P);
190 raw_ostream &operator<<(unsigned int N) {
191 return this->operator<<(static_cast<unsigned long>(N));
194 raw_ostream &operator<<(int N) {
195 return this->operator<<(static_cast<long>(N));
198 raw_ostream &operator<<(double N);
200 /// write_hex - Output \p N in hexadecimal, without any prefix or padding.
201 raw_ostream &write_hex(unsigned long long N);
203 /// write_escaped - Output \p Str, turning '\\', '\t', '\n', '"', and
204 /// anything that doesn't satisfy std::isprint into an escape sequence.
205 raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false);
207 raw_ostream &write(unsigned char C);
208 raw_ostream &write(const char *Ptr, size_t Size);
210 // Formatted output, see the format() function in Support/Format.h.
211 raw_ostream &operator<<(const format_object_base &Fmt);
213 /// indent - Insert 'NumSpaces' spaces.
214 raw_ostream &indent(unsigned NumSpaces);
217 /// Changes the foreground color of text that will be output from this point
219 /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to
220 /// change only the bold attribute, and keep colors untouched
221 /// @param Bold bold/brighter text, default false
222 /// @param BG if true change the background, default: change foreground
223 /// @returns itself so it can be used within << invocations
224 virtual raw_ostream &changeColor(enum Colors Color,
233 /// Resets the colors to terminal defaults. Call this when you are done
234 /// outputting colored text, or before program exit.
235 virtual raw_ostream &resetColor() { return *this; }
237 /// Reverses the forground and background colors.
238 virtual raw_ostream &reverseColor() { return *this; }
240 /// This function determines if this stream is connected to a "tty" or
241 /// "console" window. That is, the output would be displayed to the user
242 /// rather than being put on a pipe or stored in a file.
243 virtual bool is_displayed() const { return false; }
245 /// This function determines if this stream is displayed and supports colors.
246 virtual bool has_colors() const { return is_displayed(); }
248 //===--------------------------------------------------------------------===//
249 // Subclass Interface
250 //===--------------------------------------------------------------------===//
253 /// write_impl - The is the piece of the class that is implemented
254 /// by subclasses. This writes the \p Size bytes starting at
255 /// \p Ptr to the underlying stream.
257 /// This function is guaranteed to only be called at a point at which it is
258 /// safe for the subclass to install a new buffer via SetBuffer.
260 /// \param Ptr The start of the data to be written. For buffered streams this
261 /// is guaranteed to be the start of the buffer.
263 /// \param Size The number of bytes to be written.
265 /// \invariant { Size > 0 }
266 virtual void write_impl(const char *Ptr, size_t Size) = 0;
268 // An out of line virtual method to provide a home for the class vtable.
269 virtual void handle();
271 /// current_pos - Return the current position within the stream, not
272 /// counting the bytes currently in the buffer.
273 virtual uint64_t current_pos() const = 0;
276 /// SetBuffer - Use the provided buffer as the raw_ostream buffer. This is
277 /// intended for use only by subclasses which can arrange for the output to go
278 /// directly into the desired output buffer, instead of being copied on each
280 void SetBuffer(char *BufferStart, size_t Size) {
281 SetBufferAndMode(BufferStart, Size, ExternalBuffer);
284 /// preferred_buffer_size - Return an efficient buffer size for the
285 /// underlying output mechanism.
286 virtual size_t preferred_buffer_size() const;
288 /// getBufferStart - Return the beginning of the current stream buffer, or 0
289 /// if the stream is unbuffered.
290 const char *getBufferStart() const { return OutBufStart; }
292 //===--------------------------------------------------------------------===//
294 //===--------------------------------------------------------------------===//
296 /// SetBufferAndMode - Install the given buffer and mode.
297 void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode);
299 /// flush_nonempty - Flush the current buffer, which is known to be
300 /// non-empty. This outputs the currently buffered data and resets
301 /// the buffer to empty.
302 void flush_nonempty();
304 /// copy_to_buffer - Copy data into the buffer. Size must not be
305 /// greater than the number of unused bytes in the buffer.
306 void copy_to_buffer(const char *Ptr, size_t Size);
309 //===----------------------------------------------------------------------===//
310 // File Output Streams
311 //===----------------------------------------------------------------------===//
313 /// raw_fd_ostream - A raw_ostream that writes to a file descriptor.
315 class raw_fd_ostream : public raw_ostream {
319 /// Error This flag is true if an error of any kind has been detected.
323 /// Controls whether the stream should attempt to use atomic writes, when
325 bool UseAtomicWrites;
329 /// write_impl - See raw_ostream::write_impl.
330 void write_impl(const char *Ptr, size_t Size) override;
332 /// current_pos - Return the current position within the stream, not
333 /// counting the bytes currently in the buffer.
334 uint64_t current_pos() const override { return pos; }
336 /// preferred_buffer_size - Determine an efficient buffer size.
337 size_t preferred_buffer_size() const override;
339 /// error_detected - Set the flag indicating that an output error has
340 /// been encountered.
341 void error_detected() { Error = true; }
344 /// raw_fd_ostream - Open the specified file for writing. If an error occurs,
345 /// information about the error is put into ErrorInfo, and the stream should
346 /// be immediately destroyed; the string will be empty if no error occurred.
347 /// This allows optional flags to control how the file will be opened.
349 /// As a special case, if Filename is "-", then the stream will use
350 /// STDOUT_FILENO instead of opening a file. Note that it will still consider
351 /// itself to own the file descriptor. In particular, it will close the
352 /// file descriptor when it is done (this is necessary to detect
354 raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
355 sys::fs::OpenFlags Flags);
357 /// raw_fd_ostream ctor - FD is the file descriptor that this writes to. If
358 /// ShouldClose is true, this closes the file when the stream is destroyed.
359 raw_fd_ostream(int fd, bool shouldClose, bool unbuffered=false);
363 /// close - Manually flush the stream and close the file.
364 /// Note that this does not call fsync.
367 /// seek - Flushes the stream and repositions the underlying file descriptor
368 /// position to the offset specified from the beginning of the file.
369 uint64_t seek(uint64_t off);
371 /// SetUseAtomicWrite - Set the stream to attempt to use atomic writes for
372 /// individual output routines where possible.
374 /// Note that because raw_ostream's are typically buffered, this flag is only
375 /// sensible when used on unbuffered streams which will flush their output
377 void SetUseAtomicWrites(bool Value) {
378 UseAtomicWrites = Value;
381 raw_ostream &changeColor(enum Colors colors, bool bold=false,
382 bool bg=false) override;
383 raw_ostream &resetColor() override;
385 raw_ostream &reverseColor() override;
387 bool is_displayed() const override;
389 bool has_colors() const override;
391 /// has_error - Return the value of the flag in this raw_fd_ostream indicating
392 /// whether an output error has been encountered.
393 /// This doesn't implicitly flush any pending output. Also, it doesn't
394 /// guarantee to detect all errors unless the stream has been closed.
395 bool has_error() const {
399 /// clear_error - Set the flag read by has_error() to false. If the error
400 /// flag is set at the time when this raw_ostream's destructor is called,
401 /// report_fatal_error is called to report the error. Use clear_error()
402 /// after handling the error to avoid this behavior.
404 /// "Errors should never pass silently.
405 /// Unless explicitly silenced."
406 /// - from The Zen of Python, by Tim Peters
413 /// outs() - This returns a reference to a raw_ostream for standard output.
414 /// Use it like: outs() << "foo" << "bar";
417 /// errs() - This returns a reference to a raw_ostream for standard error.
418 /// Use it like: errs() << "foo" << "bar";
421 /// nulls() - This returns a reference to a raw_ostream which simply discards
423 raw_ostream &nulls();
425 //===----------------------------------------------------------------------===//
426 // Output Stream Adaptors
427 //===----------------------------------------------------------------------===//
429 /// raw_string_ostream - A raw_ostream that writes to an std::string. This is a
430 /// simple adaptor class. This class does not encounter output errors.
431 class raw_string_ostream : public raw_ostream {
434 /// write_impl - See raw_ostream::write_impl.
435 void write_impl(const char *Ptr, size_t Size) override;
437 /// current_pos - Return the current position within the stream, not
438 /// counting the bytes currently in the buffer.
439 uint64_t current_pos() const override { return OS.size(); }
441 explicit raw_string_ostream(std::string &O) : OS(O) {}
442 ~raw_string_ostream();
444 /// str - Flushes the stream contents to the target string and returns
445 /// the string's reference.
452 /// raw_svector_ostream - A raw_ostream that writes to an SmallVector or
453 /// SmallString. This is a simple adaptor class. This class does not
454 /// encounter output errors.
455 class raw_svector_ostream : public raw_ostream {
456 SmallVectorImpl<char> &OS;
458 /// write_impl - See raw_ostream::write_impl.
459 void write_impl(const char *Ptr, size_t Size) override;
461 /// current_pos - Return the current position within the stream, not
462 /// counting the bytes currently in the buffer.
463 uint64_t current_pos() const override;
465 /// Construct a new raw_svector_ostream.
467 /// \param O The vector to write to; this should generally have at least 128
468 /// bytes free to avoid any extraneous memory overhead.
469 explicit raw_svector_ostream(SmallVectorImpl<char> &O);
470 ~raw_svector_ostream();
472 /// resync - This is called when the SmallVector we're appending to is changed
473 /// outside of the raw_svector_ostream's control. It is only safe to do this
474 /// if the raw_svector_ostream has previously been flushed.
477 /// str - Flushes the stream contents to the target vector and return a
478 /// StringRef for the vector contents.
482 /// raw_null_ostream - A raw_ostream that discards all output.
483 class raw_null_ostream : public raw_ostream {
484 /// write_impl - See raw_ostream::write_impl.
485 void write_impl(const char *Ptr, size_t size) override;
487 /// current_pos - Return the current position within the stream, not
488 /// counting the bytes currently in the buffer.
489 uint64_t current_pos() const override;
492 explicit raw_null_ostream() {}
496 } // end llvm namespace