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