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