Streams

Bounded Operations

All public stream operations have a bounded wait. The timeout and buffer sizes are selected through erbsland::stream::InputStreamSettings or erbsland::stream::OutputStreamSettings when the stream is opened. The default timeout is one second.

Use erbsland::stream::InputStream::isReady or erbsland::stream::OutputStream::isReady for a pure readiness check. Use waitForReady() to apply back pressure for up to the configured timeout. Fully blocking behavior belongs in caller code as a loop over these bounded operations.

File Positioning

OutputStream::fileIdentity() returns the identity captured when a file stream was opened. Buffered byte and encoded text wrappers forward the same value, while non-file streams return an invalid identity. Comparing it with PathInfo::fileIdentity() detects replacement without exposing native handles.

Streams opened for regular files support optional byte positioning unless the output file was opened in append mode. ByteBlockInputStream also supports positioning and exposes a retained copy-on-write byte block through immediate bounded reads. Check erbsland::stream::StreamPositioning::supportsPositioning before using the positioning methods. Pipes, terminals, standard-stream proxies, append-only output streams, and in-memory text builders do not promise this capability.

The erbsland::stream::StreamPositioning::position method returns a logical encoded-byte position. Native input read-ahead does not change it, while bytes consumed into an incomplete retained read do. Replaying such retained input does not count the bytes twice. Accepted output advances the position immediately even while it is still queued. For text input, a consumed byte-order mark and the original bytes of decoded characters count toward the position; undecoded look-ahead does not.

Use setPosition() for an absolute position or movePosition() with erbsland::stream::StreamPositionOrigin for a movement relative to the start, logical current position, or current end. Positions beyond the end are allowed. A later write can therefore create a sparse file. Negative, invalid, overflowing, or non-native positions raise erbsland::err::ParameterError.

Position changes are bounded operations. A timeout leaves the logical position unchanged. Successful input positioning discards read-ahead, decoder state, retained aggregate input, and end-of-stream state. Output positioning waits for all accepted output to reach the native stream in order, but does not replace flush().

Text positions must lie on an encoded code-point boundary. A misaligned position is handled by the configured input encoding mode on the next read. Generic UTF-16 and UTF-32 input must resolve its byte order before moving away from byte zero; use an explicit endian encoding when immediate random access is required. Returning to byte zero enables normal byte-order-mark detection or output again, while movement to a nonzero position never inserts or consumes an interior byte-order mark.

Read Results

Read methods return erbsland::stream::StreamReadResult values. The result derives from erbsland::stream::StreamReadStatus and provides typed tests such as hasData(), isFinished(), and isTimeout(). It also works with isSuccessful() and isFailure(). Data and Finished are successful states; Timeout is a failure state. Only Data has a caller-visible payload through data() or takeData().

Short reads are normal. readExact(), text readLine(), and readAll() retain incomplete input internally on timeout. Repeat the same operation to resume it without joining fragments. Selecting another read operation replays retained input in order. read() returns one chunk, readExact() completes only at its exact length, and readAll() aggregates until end-of-stream or its maximum. The no-argument byte and text readAll() methods have a 10 MiB default maximum. Process large inputs with repeated bounded chunk reads instead of collecting them with readAll().

Sensitive Input

Set InputStreamSettings::setSensitive(true) before opening a file stream when decoded or raw input should use securely erased library-owned buffers. Opening configures the shared byte and text implementations with ordinary or protected runtime storage. Ordinary streams allocate only ordinary buffers and do not pay the protected-storage or secure-erasure cost. Owned byte reads from a sensitive stream automatically return a marked ByteBlock from read(), readExact(), readAll(), and their coroutine variants. Generic text reads return marked UTF-8 strings when the stream setting is sensitive. Transport, decoder, and retained buffers follow the same policy. The final byte block or UTF-8 string retains its mark; conversions to other representations are ordinary.

For process-native standard input, SensitiveInputScope counts one process-wide request. Nested requests may finish in any order; the last stop erases and discards unread native input. Native standard input is the intentional runtime-switching exception: its unified decoder changes storage policy in place, while a protected, epoch-checked byte transfer prevents an in-flight read from publishing data after a transition. Manual code can pair startSensitiveInput() with a consuming stopSensitiveInput(std::move(token)) call. Redirected stdIn() targets are intentionally unaffected.

Atomic Output and Back Pressure

Text and byte writes never report a partially accepted request. Output streams enqueue the complete request into a fixed front ring and a bounded growing back ring. A request larger than the configured hard limit throws erbsland::stream::StreamError before accepting data.

When isReady() is true, there is no queued back-buffer data. For a single producer, a following write whose encoded size fits backBufferLimit() can be accepted without waiting unless the stream state changes. Concurrent producers inspect every result. Success means the complete request was queued for asynchronous delivery; it does not mean the native target was flushed. Timeout means nothing from that write was accepted, so retry the whole unchanged call. Large producers should wait for readiness between chunks. flush() and close() can return timeout results while background work continues.

Coroutine Operations

Byte and text streams provide co -prefixed methods for owned block, aggregate, line, and atomic write operations. Each method returns an eager CoTask and runs the matching bounded synchronous operation away from the caller thread. Its result keeps the same stream status, including Timeout, and stream or encoding errors are rethrown when the task result is retrieved or awaited.

Coroutine operations retain shared ownership of the stream until the bounded call finishes. Library-provided concrete streams are therefore factory-created and shared-owned. Custom stream subclasses can still live on the stack for synchronous tests and algorithms, but invoking an inherited coroutine method without shared ownership throws LogicError.

coReadBlocks() generates owned byte or text blocks, while coReadLines() generates text lines. These lazy CoAsyncGenerator sequences yield both data and timeout results and terminate at end-of-stream. Text blocks end at decoded code-point boundaries, and lines preserve the synchronous line-ending behavior.

Owned asynchronous output is useful when a producer coroutine or event-loop callback may otherwise wait for output back-pressure. Successful writes still mean that the complete atomic request was accepted, not that native output was flushed. Coroutine continuations run on the coroutine worker service without caller-thread affinity.

Lifecycle

close() starts or continues graceful close. Repeating it after a timeout observes the same close operation. abort() abandons pending work and returns immediately. Destruction always aborts and never waits for native I/O, which prevents teardown from hanging on a deadlocked file, pipe, terminal, or network share.

Stream Errors

erbsland::stream::StreamError carries a erbsland::stream::StreamErrorContext with a title, description, recovery help, and the stream path when one is available. The title states what failed and the description explains why it failed. Stream wrappers delegate error-context creation to their backing stream, so errors such as a text-decoding positioning failure retain the path of the file-backed stream. Native operating-system details are embedded directly in the context, keeping diagnostics flat instead of creating a nested platform-error cause.

Interface

class AnyStringBuilderStream : public erbsland::stream::TextOutputStream

A stream to build strings.

Public Functions

explicit AnyStringBuilderStream(text::StringKind stringKind, ConstructionToken token)

Internal constructor used by create().

Parameters:
  • stringKind – The kind of string to use for the output.

  • token – The private factory token.

text::StringKind kind() const noexcept

Get the target string kind.

unit::CpLength length() const noexcept

Get the current decoded code-point length.

bool isEmpty() const noexcept

Test if this builder is empty.

void clear() noexcept

Clear all built text while keeping the target kind.

text::U8String toU8String() const

Create a UTF-8 string copy.

text::U8String toString() const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

text::U16String toU16String() const

Create a UTF-16 string copy.

text::U32String toU32String() const

Create a UTF-32 string copy.

text::AnyString toAnyString() const

Create an “any” string copy.

text::U8StringEditor toU8StringEditor() const

Create an editable UTF-8 string copy.

text::StringEditor toStringEditor() const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

text::U16StringEditor toU16StringEditor() const

Create an editable UTF-16 string copy.

text::U32StringEditor toU32StringEditor() const

Create an editable UTF-32 string copy.

text::AnyStringEditor toAnyStringEditor() const

Create an editable type-erased string copy.

text::U8String takeU8String()

Move out a UTF-8 string and reset this builder.

text::String takeString()

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

text::U16String takeU16String()

Move out a UTF-16 string and reset this builder.

text::U32String takeU32String()

Move out a UTF-32 string and reset this builder.

text::AnyString takeAnyString()

Move out “any” string and reset this builder.

text::U8StringEditor takeU8StringEditor()

Move out an editable UTF-8 string and reset this builder.

text::StringEditor takeStringEditor()

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

text::U16StringEditor takeU16StringEditor()

Move out an editable UTF-16 string and reset this builder.

text::U32StringEditor takeU32StringEditor()

Move out an editable UTF-32 string and reset this builder.

text::AnyStringEditor takeAnyStringEditor()

Move out an editable type-erased string and reset this builder.

inline virtual const OutputStreamSettings &outputSettings() const noexcept override

Get the immutable settings selected when this stream was created.

virtual StreamState state() const noexcept override

Get the lifecycle state.

virtual bool isReady() const noexcept override

Test if the stream has no queued back-buffer data.

For a single producer, a following write within backBufferLimit() can be accepted without waiting unless the stream state changes. Concurrent producers must inspect each write result.

virtual StreamWaitStatus waitForReady() override

Wait up to the configured timeout for the stream to become ready.

virtual StreamWriteStatus flush() override

Flush buffered output.

Throws:

stream::StreamError – If the backing target reports a flush error.

virtual StreamCloseStatus close() override

Start or continue graceful close and wait up to the configured timeout.

virtual void abort() noexcept override

Immediately abandon queued output and pending native work without waiting.

virtual text::StringEncoding encoding() const noexcept override

Get the encoding configured for the stream.

virtual text::StringEncoding effectiveEncoding() const noexcept override

Get the effective encoding used by the stream.

virtual StreamWriteStatus write(text::Char character) override

Write one character.

Parameters:

character – The character to write.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the character was accepted, or Timeout if nothing was accepted.

virtual StreamWriteStatus write(const text::String &text) override

Write text.

Parameters:

text – The text to write.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if all text was accepted, or Timeout if nothing was accepted.

virtual StreamWriteStatus writeLine() override

Write a line-feed character.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the line feed was accepted, or Timeout if nothing was accepted.

virtual StreamWriteStatus writeLine(const text::String &text) override

Write text followed by a line-feed character.

Parameters:

text – The text to write before the line-feed.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the complete line was accepted, or Timeout if nothing was accepted.

Public Static Functions

static inline AnyStringBuilderStreamPtr create(text::StringKind stringKind = text::StringKind::U8)

Create a new string builder stream with the given string kind as shared pointer.

Parameters:

stringKind – The kind of string to use for the output.

Returns:

A shared-owned string builder stream.

class ByteBlockInputStream : public erbsland::stream::ByteInputStream

An immediate positional byte input stream retaining one copy-on-write byte block.

Public Functions

explicit ByteBlockInputStream(mem::ByteBlock data, InputStreamSettings settings = {})

Create an open stream retaining the supplied bytes.

Parameters:
  • data – The byte block retained as the stream source.

  • settings – The immutable input settings.

virtual const InputStreamSettings &inputSettings() const noexcept override

Get the immutable settings selected when this stream was created.

virtual StreamState state() const noexcept override

Get the lifecycle state.

virtual bool isReady() const noexcept override

Test if a read can immediately return data or a final state.

virtual StreamWaitStatus waitForReady() override

Wait up to the configured timeout for a read to become ready.

virtual StreamCloseStatus close() override

Start or continue graceful close and wait up to the configured timeout.

virtual void abort() noexcept override

Immediately abandon pending work without waiting.

class ByteInputStream : public erbsland::stream::InputStream

A stream that reads raw bytes.

Chunk reads return currently available data and may be short. Logical reads retain partial input internally across timeouts, so exact blocks and integer values never require caller-side reassembly.

Subclassed by erbsland::stream::ByteBlockInputStream, erbsland::stream::impl::BufferedByteInputStream

Public Functions

mem::Endianness endianness() const noexcept

Get the byte order used by integer convenience methods.

void setEndianness(mem::Endianness endianness) noexcept

Set the byte order used by integer convenience methods.

virtual bool supportsPositioning() const noexcept override

Test if this stream supports positioning.

virtual unit::ByteIndex position() const override

Get the logical byte position.

Throws:

stream::StreamError – If positioning is not supported.

virtual StreamPositionStatus setPosition(unit::ByteIndex position) override

Set the logical byte position.

Parameters:

position – The absolute byte position. Positions beyond the current end are allowed.

Throws:
  • err::ParameterError – If position is invalid or outside native file-offset bounds.

  • stream::StreamError – If positioning is unsupported or fails.

Returns:

Success, or Timeout if the operation could not be serialized before the deadline.

virtual StreamPositionStatus movePosition(StreamPositionOrigin origin, unit::ByteOffset offset) override

Move the logical byte position.

Parameters:
  • origin – The reference point for the movement.

  • offset – The signed byte offset from origin.

Throws:
  • err::ParameterError – If the result is negative or outside native file-offset bounds.

  • stream::StreamError – If positioning is unsupported or fails.

Returns:

Success, or Timeout if the operation could not be serialized before the deadline.

StreamReadResult<unit::ByteLength> read(mem::ByteSpan destination)

Read bytes into a destination span.

Parameters:

destination – The destination bytes to fill.

Throws:

stream::StreamError – If the stream is closed or the backing source fails.

Returns:

The status and number of bytes read.

StreamReadResult<mem::ByteBlock> read(unit::ByteLength maximumLength)

Read up to maximumLength bytes and return them as a byte block.

Parameters:

maximumLength – The maximum number of bytes to read.

Throws:
  • err::ParameterError – If maximumLength is infinite.

  • stream::StreamError – If the stream is closed or the backing source fails.

Returns:

The status and bytes that were read.

StreamReadResult<mem::ByteBlock> readExact(unit::ByteLength length)

Read exactly length bytes.

Parameters:

length – The number of bytes to read. Partial bytes are retained by the stream after timeout or premature end-of-stream. Repeating this operation continues it; selecting another read operation makes retained bytes available to that operation in order.

Throws:
  • err::ParameterError – If length is infinite.

  • stream::StreamError – If the stream is closed or the backing source fails.

Returns:

Data with exactly length bytes, or an empty Timeout/Finished result.

StreamReadResult<mem::Byte> readByte()

Read one byte.

Throws:

stream::StreamError – If the stream is closed or the backing source fails.

Returns:

The status and next byte.

StreamReadResult<mem::ByteBlock> readAll()

Read remaining bytes up to cDefaultByteReadMaximum.

Throws:

stream::StreamError – If the stream is closed or the backing source fails.

Returns:

The status and bytes read before the limit, end, or timeout.

StreamReadResult<mem::ByteBlock> readAll(unit::ByteLength maximumLength)

Read remaining bytes up to maximumLength.

Parameters:

maximumLength – The maximum number of bytes to aggregate.

Throws:
  • err::ParameterError – If maximumLength is infinite.

  • stream::StreamError – If the stream is closed or the backing source fails.

Returns:

The status and bytes read before the limit, end, or timeout.

util::CoTask<StreamReadResult<mem::ByteBlock>> coRead(unit::ByteLength maximumLength)

Asynchronously read one owned byte block.

Parameters:

maximumLength – The maximum number of bytes to read.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • err::ParameterError – When the task result is observed if maximumLength is infinite.

  • stream::StreamError – When the task result is observed if the stream or backing source fails.

Returns:

A task with the same result as read(maximumLength).

util::CoTask<StreamReadResult<mem::ByteBlock>> coReadExact(unit::ByteLength length)

Asynchronously read exactly length bytes.

Parameters:

length – The number of bytes to read.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • err::ParameterError – When the task result is observed if length is infinite.

  • stream::StreamError – When the task result is observed if the stream or backing source fails.

Returns:

A task with the same result as readExact(length).

util::CoTask<StreamReadResult<mem::ByteBlock>> coReadAll()

Asynchronously read remaining bytes up to cDefaultByteReadMaximum.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • stream::StreamError – When the task result is observed if the stream or backing source fails.

Returns:

A task with the same result as readAll().

util::CoTask<StreamReadResult<mem::ByteBlock>> coReadAll(unit::ByteLength maximumLength)

Asynchronously read remaining bytes up to maximumLength.

Parameters:

maximumLength – The maximum aggregate length.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • err::ParameterError – When the task result is observed if maximumLength is infinite.

  • stream::StreamError – When the task result is observed if the stream or backing source fails.

Returns:

A task with the same result as readAll(maximumLength).

util::CoAsyncGenerator<StreamReadResult<mem::ByteBlock>> coReadBlocks()

Asynchronously generate byte blocks using the default maximum block length.

Timeout results are yielded; end-of-stream completes the generator.

Throws:
  • err::LogicError – When first advanced if this stream is not shared-owned.

  • stream::StreamError – When advancing if the stream or backing source fails.

Returns:

A lazy generator for bounded byte-block results.

util::CoAsyncGenerator<StreamReadResult<mem::ByteBlock>> coReadBlocks(unit::ByteLength maximumLength)

Asynchronously generate byte blocks.

Parameters:

maximumLength – The positive finite maximum for each block. Timeout results are yielded; end-of-stream completes the generator.

Throws:
  • err::ParameterError – When first advanced if maximumLength is zero or infinite.

  • err::LogicError – When first advanced if this stream is not shared-owned.

  • stream::StreamError – When advancing if the stream or backing source fails.

Returns:

A lazy generator for bounded byte-block results.

template<std::integral T>
inline StreamReadResult<T> readInteger()

Read an integer value.

Throws:

stream::StreamError – If the stream is closed or the backing source fails.

Returns:

The status and integer value.

inline StreamReadResult<int8_t> readInt8()

Read a signed 8-bit integer.

inline StreamReadResult<uint8_t> readUInt8()

Read an unsigned 8-bit integer.

inline StreamReadResult<int16_t> readInt16()

Read a signed 16-bit integer.

inline StreamReadResult<uint16_t> readUInt16()

Read an unsigned 16-bit integer.

inline StreamReadResult<int32_t> readInt32()

Read a signed 32-bit integer.

inline StreamReadResult<uint32_t> readUInt32()

Read an unsigned 32-bit integer.

inline StreamReadResult<int64_t> readInt64()

Read a signed 64-bit integer.

inline StreamReadResult<uint64_t> readUInt64()

Read an unsigned 64-bit integer.

Public Static Attributes

static constexpr auto cDefaultByteReadMaximum = unit::ByteLength{10U * 1024U * 1024U}

The default maximum for no-argument aggregate reads: 10 MiB.

class ByteOutputStream : public erbsland::stream::OutputStream

A stream that writes raw bytes.

Every write atomically accepts the complete request for asynchronous delivery. Timeout means no byte from that call was accepted, so the complete unchanged call can be retried.

Subclassed by erbsland::stream::TempByteOutputStream, erbsland::stream::impl::BufferedByteOutputStream

Public Functions

virtual mem::Endianness endianness() const noexcept

Get the byte order used by integer convenience methods.

virtual void setEndianness(mem::Endianness endianness) noexcept

Set the byte order used by integer convenience methods.

virtual StreamWriteStatus write(mem::Byte byte)

Write a single byte.

Parameters:

byte – The byte to write.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the byte was accepted, or Timeout if nothing was accepted.

virtual StreamWriteStatus write(mem::ConstByteSpan bytes) = 0

Write a byte span.

Parameters:

bytes – The bytes to write.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if all bytes were accepted, or Timeout if nothing was accepted.

virtual StreamWriteStatus write(const mem::ByteBlock &bytes)

Write a read-only byte block.

Parameters:

bytes – The bytes to write.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if all bytes were accepted, or Timeout if nothing was accepted.

util::CoTask<StreamWriteStatus> coWrite(mem::ByteBlock bytes)

Asynchronously write an owned byte block.

Parameters:

bytes – The bytes retained by the operation until it completes.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • stream::StreamError – When the task result is observed if the stream or backing target fails.

Returns:

A task with the same result as write(ByteBlock).

template<std::integral T>
inline StreamWriteStatus writeInteger(T value)

Write an integer value.

Parameters:

value – The integer value.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the complete integer was accepted, or Timeout if nothing was accepted.

inline StreamWriteStatus writeInt8(int8_t value)

Write a signed 8-bit integer.

inline StreamWriteStatus writeUInt8(uint8_t value)

Write an unsigned 8-bit integer.

inline StreamWriteStatus writeInt16(int16_t value)

Write a signed 16-bit integer.

inline StreamWriteStatus writeUInt16(uint16_t value)

Write an unsigned 16-bit integer.

inline StreamWriteStatus writeInt32(int32_t value)

Write a signed 32-bit integer.

inline StreamWriteStatus writeUInt32(uint32_t value)

Write an unsigned 32-bit integer.

inline StreamWriteStatus writeInt64(int64_t value)

Write a signed 64-bit integer.

inline StreamWriteStatus writeUInt64(uint64_t value)

Write an unsigned 64-bit integer.

class InputStream : public erbsland::stream::StreamPositioning, public std::enable_shared_from_this<InputStream>

The common base class for readable streams.

All public operations are bounded by the timeout fixed in the stream settings. Destruction never waits for pending native work; every concrete implementation must abort its backing operation from its destructor.

Subclassed by erbsland::stream::ByteInputStream, erbsland::stream::TextInputStream

Public Functions

virtual const InputStreamSettings &inputSettings() const noexcept = 0

Get the immutable settings selected when this stream was created.

virtual StreamState state() const noexcept = 0

Get the lifecycle state.

inline bool isOpen() const noexcept

Test if the stream is open for reading.

virtual bool isReady() const noexcept = 0

Test if a read can immediately return data or a final state.

virtual StreamWaitStatus waitForReady() = 0

Wait up to the configured timeout for a read to become ready.

virtual StreamCloseStatus close() = 0

Start or continue graceful close and wait up to the configured timeout.

virtual void abort() noexcept = 0

Immediately abandon pending work without waiting.

using erbsland::stream::InputStreamPtr = std::shared_ptr<InputStream>

Shared pointer for InputStream.

class InputStreamSettings

Settings fixed when an input stream is created.

Public Functions

inline time::TimeDelta timeout() const noexcept

Get the maximum wait for one public operation.

inline InputStreamSettings &setTimeout(time::TimeDelta value) noexcept

Set the maximum wait for one public operation.

inline StreamBuffering buffering() const noexcept

Get the intended balance between memory use and throughput.

inline InputStreamSettings &setBuffering(StreamBuffering value) noexcept

Set the intended balance between memory use and throughput.

inline bool isSensitive() const noexcept

Test if library-owned input buffers use secure erasure.

inline InputStreamSettings &setSensitive(bool value) noexcept

Enable or disable secure erasure for library-owned input buffers.

class OutputStream : public erbsland::stream::StreamPositioning, public std::enable_shared_from_this<OutputStream>

The common base class for writable streams.

Output streams atomically accept complete write requests. Public operations wait at most for the timeout fixed in the settings. Destruction never waits for pending native work; every concrete implementation must abort from its destructor. A successful write is queued for delivery; only a successful flush() confirms native flushing.

Subclassed by erbsland::stream::ByteOutputStream, erbsland::stream::TextOutputStream

Public Functions

inline virtual system::FileIdentity fileIdentity() const noexcept

Get the identity captured when the backing file was opened.

Non-file streams return an invalid identity.

Returns:

The opened file’s identity, or an invalid identity for a non-file stream.

virtual const OutputStreamSettings &outputSettings() const noexcept = 0

Get the immutable settings selected when this stream was created.

virtual StreamState state() const noexcept = 0

Get the lifecycle state.

inline bool isOpen() const noexcept

Test if the stream is open for writing.

virtual bool isReady() const noexcept = 0

Test if the stream has no queued back-buffer data.

For a single producer, a following write within backBufferLimit() can be accepted without waiting unless the stream state changes. Concurrent producers must inspect each write result.

virtual StreamWaitStatus waitForReady() = 0

Wait up to the configured timeout for the stream to become ready.

virtual StreamWriteStatus flush() = 0

Flush buffered output.

Throws:

stream::StreamError – If the backing target reports a flush error.

virtual StreamCloseStatus close() = 0

Start or continue graceful close and wait up to the configured timeout.

virtual void abort() noexcept = 0

Immediately abandon queued output and pending native work without waiting.

using erbsland::stream::OutputStreamPtr = std::shared_ptr<OutputStream>

Shared pointer for OutputStream.

class OutputStreamSettings

Settings fixed when an output stream is created.

Public Functions

inline time::TimeDelta timeout() const noexcept

Get the maximum wait for one public operation.

inline OutputStreamSettings &setTimeout(time::TimeDelta value) noexcept

Set the maximum wait for one public operation.

inline StreamBuffering buffering() const noexcept

Get the intended balance between memory use and throughput.

inline OutputStreamSettings &setBuffering(StreamBuffering value) noexcept

Set the intended balance between memory use and throughput.

unit::ByteLength backBufferLimit() const noexcept

Get the effective hard back-ring limit.

inline OutputStreamSettings &setBackBufferLimit(unit::ByteLength value) noexcept

Set the hard back-ring limit.

inline OutputStreamSettings &clearBackBufferLimit() noexcept

Clear the explicit hard back-ring limit and use the selected buffering preset.

class SensitiveInputToken

A diagnostic handle for one active native standard-input sensitivity request.

The token is move-only and does not stop the request when destroyed. Use SensitiveInputScope for RAII.

Public Functions

SensitiveInputToken &operator=(SensitiveInputToken &&other) noexcept

Move another sensitive-input token into this token.

inline uint64_t id() const noexcept

Get the unique diagnostic identifier, or zero for an invalid token.

inline std::source_location sourceLocation() const noexcept

Get the source location where the sensitivity request started.

inline bool isValid() const noexcept

Test if this token contains an identifier that can be submitted to stopSensitiveInput().

SensitiveInputToken erbsland::stream::io::startSensitiveInput(std::source_location location = std::source_location::current())

Start secure buffering for the process-native standard input pipeline.

Requests may be stopped in any order. Redirected stdIn() targets are not affected.

void erbsland::stream::io::stopSensitiveInput(SensitiveInputToken token)

Stop one native standard-input sensitivity request.

Throws:

err::LogicError – If the token is invalid or was already stopped.

class SensitiveInputScope

A move-only scope that enables secure buffering for process-native standard input.

Public Functions

explicit SensitiveInputScope(std::source_location location = std::source_location::current())

Start a sensitivity request at the caller’s source location.

~SensitiveInputScope()

Stop the owned sensitivity request.

SensitiveInputScope &operator=(SensitiveInputScope &&other) noexcept

Move another sensitive-input scope into this scope.

inline bool isActive() const noexcept

Test if this object owns an active request.

void reset() noexcept

Stop the owned request now. Repeated calls have no effect.

class StandardStreamRedirect

A scoped replacement for one or both process standard text streams.

Destroying or resetting this guard restores the stream targets that were active when the guard was created.

Public Functions

StandardStreamRedirect() noexcept = default

Create an inactive guard.

StandardStreamRedirect &operator=(StandardStreamRedirect &&other) noexcept

Move the standard-stream redirection into this instance.

~StandardStreamRedirect()

Restores the standard streams when this guard is active.

bool isActive() const noexcept

Test if this guard still owns an active replacement.

void reset() noexcept

Restore the previous stream target now.

TextInputStreamPtr erbsland::stream::stdIn()

Get the process standard input stream.

The returned stream is cached and shared by the whole process. Calling close() on this stream has no effect.

Throws:

stream::StreamError – If the process standard input stream is not available.

Returns:

The standard input stream.

TextOutputStreamPtr erbsland::stream::stdOut()

Get the process standard output stream.

The returned stream is cached and shared by the whole process. Calling close() on this stream has no effect.

Throws:

stream::StreamError – If the process standard output stream is not available.

Returns:

The standard output stream.

TextOutputStreamPtr erbsland::stream::stdErr()

Get the process standard error stream.

The returned stream is cached and shared by the whole process. Calling close() on this stream has no effect.

Throws:

stream::StreamError – If the process standard error stream is not available.

Returns:

The standard error stream.

StandardStreamRedirect erbsland::stream::redirectStdIn(TextInputStreamPtr input)

Replace the process standard input stream for the lifetime of the returned guard.

Existing pointers returned by stdIn() keep using the active replacement.

Parameters:

input – The replacement input stream.

Throws:

stream::StreamError – If input is empty.

Returns:

The guard that restores the previous input stream target.

StandardStreamRedirect erbsland::stream::redirectStdOut(TextOutputStreamPtr output)

Replace the process standard output stream for the lifetime of the returned guard.

Existing pointers returned by stdOut() keep using the active replacement.

Parameters:

output – The replacement output stream.

Throws:

stream::StreamError – If output is empty.

Returns:

The guard that restores the previous output stream target.

StandardStreamRedirect erbsland::stream::redirectStdErr(TextOutputStreamPtr error)

Replace the process standard error stream for the lifetime of the returned guard.

Existing pointers returned by stdErr() keep using the active replacement.

Parameters:

error – The replacement error stream.

Throws:

stream::StreamError – If error is empty.

Returns:

The guard that restores the previous error stream target.

StandardStreamRedirect erbsland::stream::redirectStandardStreams(TextOutputStreamPtr output, TextOutputStreamPtr error)

Replace both process standard text streams for the lifetime of the returned guard.

Existing pointers returned by stdOut() and stdErr() keep using the active replacements.

Parameters:
  • output – The replacement output stream.

  • error – The replacement error stream.

Throws:

stream::StreamError – If a replacement stream is empty.

Returns:

The guard that restores both previous stream targets.

inline StreamWriteStatus erbsland::stream::io::write(text::Char character)

Write one character.

Parameters:

character – The character to write.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the character was accepted, or Timeout if nothing was accepted.

inline StreamWriteStatus erbsland::stream::io::write(const text::String &text)

Write text.

Parameters:

text – The text to write.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if all text was accepted, or Timeout if nothing was accepted.

inline StreamWriteStatus erbsland::stream::io::writeLine()

Write a line-feed character.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the line feed was accepted, or Timeout if nothing was accepted.

inline StreamWriteStatus erbsland::stream::io::writeLine(const text::String &text)

Write text followed by a line-feed character.

Parameters:

text – The text to write before the line-feed.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the complete line was accepted, or Timeout if nothing was accepted.

template<typename ...tArgs>
StreamWriteStatus erbsland::stream::io::print(const tArgs&... args)

Print one or more arguments to the stream.

This is a convenience helper for small output. For large text, prefer the low-level write... methods. Valid arguments are chars, string types, integers, floating-point values, booleans, values with toString() const returning text::String, and values with toRawValue() const returning a supported non-character integer. If both conversion methods exist, toString() is used. Change the integer or floating-point format by adding a format specifier before the affected value.

Parameters:

args – The arguments to print.

Returns:

Success if the complete formatted output was accepted, or Timeout if nothing was accepted.

template<typename ...tArgs>
StreamWriteStatus erbsland::stream::io::printLine(const tArgs&... args)

Print one or more arguments to the stream and add a line-break.

See also

print() for all details.

Parameters:

args – The arguments to print.

Returns:

Success if the complete formatted line was accepted, or Timeout if nothing was accepted.

template<typename ...tArgs>
StreamWriteStatus erbsland::stream::io::printError(const tArgs&... args)

Print one or more arguments to the stream.

This is a convenience helper for small output. For large text, prefer the low-level write... methods. Valid arguments are chars, string types, integers, floating-point values, booleans, values with toString() const returning text::String, and values with toRawValue() const returning a supported non-character integer. If both conversion methods exist, toString() is used. Change the integer or floating-point format by adding a format specifier before the affected value.

Parameters:

args – The arguments to print.

Returns:

Success if the complete formatted output was accepted, or Timeout if nothing was accepted.

template<typename ...tArgs>
StreamWriteStatus erbsland::stream::io::printErrorLine(const tArgs&... args)

Print one or more arguments to the stream and add a line-break.

See also

print() for all details.

Parameters:

args – The arguments to print.

Returns:

Success if the complete formatted line was accepted, or Timeout if nothing was accepted.

enum class erbsland::stream::StreamBuffering

Selects the intended balance between stream memory use and throughput.

Values:

enumerator MinimalMemory

Minimize retained memory, accepting more frequent I/O.

enumerator Interactive

Favor responsive streams with modest buffering.

enumerator Balanced

Balance memory use and throughput for general use.

enumerator Throughput

Favor throughput with larger buffers.

enumerator Bulk

Maximize throughput for large sequential transfers.

class StreamCloseStatus : public erbsland::util::Result

The status of a bounded stream close operation.

Public Functions

inline constexpr bool operator==(const StreamCloseStatus &other) const noexcept

Compare two stream-close statuses.

inline constexpr bool isClosed() const noexcept

Test if the stream is closed.

inline constexpr bool isTimeout() const noexcept

Test if closing did not finish within its bounded wait.

inline constexpr Result(const Value value)

Create a new result.

Parameters:

value – The value of the result.

Public Static Attributes

static const StreamCloseStatus Closed = Value::success<0>()

The stream is closed.

static const StreamCloseStatus Timeout = Value::failure<0>()

Closing continues, but did not finish before the deadline.

class StreamError : public erbsland::err::RuntimeError

An error related to a stream operation.

Public Functions

explicit StreamError(StreamErrorContext context, std::exception_ptr cause = {}) noexcept

Create a stream error with complete diagnostic context.

virtual err::DiagnosticConstPtr diagnostic() const override

Convert the error with all its details into a structured diagnostic.

inline const text::String &title() const noexcept

Get the operation title.

inline const text::String &description() const noexcept

Get the operation description.

inline text::String help() const noexcept

Get explicit or category-derived help.

inline const text::String &path() const noexcept

Get the stream path, or an empty view.

inline const system::PlatformErrorContextConstPtr &platformContext() const noexcept

Get the immutable native failure context, if available.

inline const StreamErrorContext &context() const noexcept

Get the complete stream error context.

class StreamErrorContext

User-facing context for a stream-domain error.

Public Functions

explicit StreamErrorContext(text::String title, text::String description) noexcept

Create context for a failed stream operation.

Parameters:
  • title – A short developer-authored title.

  • description – A developer-authored explanation of the failure.

inline const text::String &title() const noexcept

Get the operation title.

StreamErrorContext &setTitle(text::String title) noexcept

Set the operation title.

inline const text::String &description() const noexcept

Get the operation description.

StreamErrorContext &setDescription(text::String description) noexcept

Set the operation description.

text::String help() const noexcept

Get explicit help or category-derived help when available.

StreamErrorContext &setHelp(text::String help) noexcept

Set explicit help, overriding category-derived help.

inline const text::String &path() const noexcept

Get the stream path, or an empty view if none was provided.

StreamErrorContext &setPath(text::String path) noexcept

Set the stream path.

inline const system::PlatformErrorContextConstPtr &platformContext() const noexcept

Get the immutable native failure context, if available.

StreamErrorContext &setPlatformContext(system::PlatformErrorContextConstPtr platformContext) noexcept

Set the immutable native failure context.

class StreamErrorSource

Extension interface for reporting errors from a stream or a stream adapter.

Stream implementations override the context factory to add source-specific information, such as a file path. Callers normally use the stream operation that failed; wrappers use this interface to delegate context creation.

Subclassed by erbsland::stream::StreamPositioning, erbsland::stream::impl::NativeByteStream, erbsland::stream::impl::NativeOutputStream

Public Functions

void throwError(text::String title, text::String description) const

Throw an error with a user-facing title and explanation.

Parameters:
  • title – What operation failed.

  • description – Why the operation failed.

virtual StreamErrorContext createErrorContext() const noexcept

Create a diagnostic context for errors reported by this source.

Implementations can add source-specific data or delegate to a wrapped source.

class StreamPositioning : public virtual erbsland::stream::StreamErrorSource

Optional byte-based positioning for streams.

Positioning is a stable capability of a stream. The logical position excludes native input read-ahead and includes output accepted for delivery. Unsupported operations throw StreamError.

Subclassed by erbsland::stream::InputStream, erbsland::stream::OutputStream

Public Functions

virtual bool supportsPositioning() const noexcept

Test if this stream supports positioning.

virtual unit::ByteIndex position() const

Get the logical byte position.

Throws:

stream::StreamError – If positioning is not supported.

virtual StreamPositionStatus setPosition(unit::ByteIndex position)

Set the logical byte position.

Parameters:

position – The absolute byte position. Positions beyond the current end are allowed.

Throws:
  • err::ParameterError – If position is invalid or outside native file-offset bounds.

  • stream::StreamError – If positioning is unsupported or fails.

Returns:

Success, or Timeout if the operation could not be serialized before the deadline.

virtual StreamPositionStatus movePosition(StreamPositionOrigin origin, unit::ByteOffset offset)

Move the logical byte position.

Parameters:
  • origin – The reference point for the movement.

  • offset – The signed byte offset from origin.

Throws:
  • err::ParameterError – If the result is negative or outside native file-offset bounds.

  • stream::StreamError – If positioning is unsupported or fails.

Returns:

Success, or Timeout if the operation could not be serialized before the deadline.

enum class erbsland::stream::StreamPositionOrigin : uint8_t

The reference point for moving a stream position.

Values:

enumerator Start

Move relative to byte position zero.

enumerator Current

Move relative to the logical current position.

enumerator End

Move relative to the current end of the stream.

class StreamPositionStatus : public erbsland::util::Result

The status of a bounded stream positioning operation.

Public Functions

inline constexpr bool operator==(const StreamPositionStatus &other) const noexcept

Compare two stream-position statuses.

inline constexpr bool isSuccess() const noexcept

Test if the stream position was changed.

inline constexpr bool isTimeout() const noexcept

Test if positioning did not complete within its bounded wait.

inline constexpr Result(const Value value)

Create a new result.

Parameters:

value – The value of the result.

Public Static Attributes

static const StreamPositionStatus Success = Value::success<0>()

The stream position was changed.

static const StreamPositionStatus Timeout = Value::failure<0>()

Positioning did not complete before the deadline.

template<typename tData>
using erbsland::stream::StreamReadResult = util::ResultWithData<tData, StreamReadStatus>

A bounded stream read result with transported data.

It derives from StreamReadStatus, so use typed predicates or compare it directly with that status. Only Data has a caller-visible payload; Timeout and Finished transport the default/empty data value.

Template Parameters:

tData – The transported data type.

class StreamReadStatus : public erbsland::util::Result

The status of a bounded stream read operation.

Public Functions

inline constexpr bool operator==(const StreamReadStatus &other) const noexcept

Compare two stream-read statuses.

inline constexpr bool hasData() const noexcept

Test if the result contains caller-visible data.

inline constexpr bool isFinished() const noexcept

Test if the stream reached its normal end without returning data.

inline constexpr bool isTimeout() const noexcept

Test if the operation did not complete within its bounded wait.

inline constexpr Result(const Value value)

Create a new result.

Parameters:

value – The value of the result.

Public Static Attributes

static const StreamReadStatus Data = Value::success<0>()

Data was read.

static const StreamReadStatus Finished = Value::success<1>()

The stream reached its normal end.

static const StreamReadStatus Timeout = Value::failure<0>()

No complete result was available before the deadline.

enum class erbsland::stream::StreamState : uint8_t

The lifecycle state of a stream.

Values:

enumerator Open

Operations are accepted.

enumerator Closing

Graceful closing is in progress.

enumerator Closed

The stream is closed.

enumerator Failed

A native stream operation failed.

class StreamWaitStatus : public erbsland::util::Result

The status of waiting for a stream to become ready.

Public Functions

inline constexpr bool operator==(const StreamWaitStatus &other) const noexcept

Compare two stream-wait statuses.

inline constexpr bool isReady() const noexcept

Test if the stream reached its ready state.

inline constexpr bool isTimeout() const noexcept

Test if the stream did not become ready within its bounded wait.

inline constexpr Result(const Value value)

Create a new result.

Parameters:

value – The value of the result.

Public Static Attributes

static const StreamWaitStatus Ready = Value::success<0>()

The stream reached its ready state.

static const StreamWaitStatus Timeout = Value::failure<0>()

The stream did not become ready before the deadline.

class StreamWriteStatus : public erbsland::util::Result

The status of a bounded stream write or flush operation.

Public Functions

inline constexpr bool operator==(const StreamWriteStatus &other) const noexcept

Compare two stream-write statuses.

inline constexpr bool isSuccess() const noexcept

Test if the complete output operation succeeded.

inline constexpr bool isTimeout() const noexcept

Test if the output operation did not complete within its bounded wait.

inline constexpr Result(const Value value)

Create a new result.

Parameters:

value – The value of the result.

Public Static Attributes

static const StreamWriteStatus Success = Value::success<0>()

The complete output operation succeeded.

static const StreamWriteStatus Timeout = Value::failure<0>()

The output operation did not complete before the deadline.

class TempByteOutputStream : public erbsland::stream::ByteOutputStream

A byte output stream for a temporary file.

A successful close removes the file synchronously. Destruction never closes or waits: it aborts immediately and schedules removal, unless release() was called or automatic cleanup was disabled.

Public Functions

TempByteOutputStream() = default

Create an empty temporary byte output stream.

~TempByteOutputStream() override

Abort without waiting and schedule cleanup of the temporary file.

bool isEmpty() const noexcept

Test if this stream has no temporary file path.

const path::Path &path() const noexcept

Access the temporary file path.

bool removeOnClose() const noexcept

Test if the file is removed when the stream is closed or destroyed.

void setRemoveOnClose(bool value) noexcept

Set whether to remove the file when the stream is closed or destroyed.

path::Path release() noexcept

Disable automatic cleanup and return the file path.

virtual const OutputStreamSettings &outputSettings() const noexcept override

Get the immutable settings selected when this stream was created.

virtual StreamState state() const noexcept override

Get the lifecycle state.

virtual bool isReady() const noexcept override

Test if the stream has no queued back-buffer data.

For a single producer, a following write within backBufferLimit() can be accepted without waiting unless the stream state changes. Concurrent producers must inspect each write result.

virtual StreamWaitStatus waitForReady() override

Wait up to the configured timeout for the stream to become ready.

virtual StreamWriteStatus flush() override

Flush buffered output.

Throws:

stream::StreamError – If the backing target reports a flush error.

virtual StreamCloseStatus close() override

Start or continue graceful close and wait up to the configured timeout.

virtual void abort() noexcept override

Immediately abandon queued output and pending native work without waiting.

virtual StreamErrorContext createErrorContext() const noexcept override

Create a diagnostic context for errors reported by this source.

Implementations can add source-specific data or delegate to a wrapped source.

virtual mem::Endianness endianness() const noexcept override

Get the byte order used by integer convenience methods.

virtual void setEndianness(mem::Endianness endianness) noexcept override

Set the byte order used by integer convenience methods.

virtual StreamWriteStatus write(mem::ConstByteSpan bytes) override

Write a byte span.

Parameters:

bytes – The bytes to write.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if all bytes were accepted, or Timeout if nothing was accepted.

void throwError(text::String title, text::String description) const

Throw an error with a user-facing title and explanation.

Parameters:
  • title – What operation failed.

  • description – Why the operation failed.

class TempTextOutputStream : public erbsland::stream::TextOutputStream

A text output stream for a temporary file.

A successful close removes the file synchronously. Destruction never closes or waits: it aborts immediately and schedules removal, unless release() was called or automatic cleanup was disabled.

Public Functions

TempTextOutputStream() = default

Create an empty temporary text output stream.

~TempTextOutputStream() override

Abort without waiting and schedule cleanup of the temporary file.

bool isEmpty() const noexcept

Test if this stream has no temporary file path.

const path::Path &path() const noexcept

Access the temporary file path.

bool removeOnClose() const noexcept

Test if the file is removed when the stream is closed or destroyed.

void setRemoveOnClose(bool value) noexcept

Set whether to remove the file when the stream is closed or destroyed.

path::Path release() noexcept

Disable automatic cleanup and return the file path.

virtual const OutputStreamSettings &outputSettings() const noexcept override

Get the immutable settings selected when this stream was created.

virtual StreamState state() const noexcept override

Get the lifecycle state.

virtual bool isReady() const noexcept override

Test if the stream has no queued back-buffer data.

For a single producer, a following write within backBufferLimit() can be accepted without waiting unless the stream state changes. Concurrent producers must inspect each write result.

virtual StreamWaitStatus waitForReady() override

Wait up to the configured timeout for the stream to become ready.

virtual StreamWriteStatus flush() override

Flush buffered output.

Throws:

stream::StreamError – If the backing target reports a flush error.

virtual StreamCloseStatus close() override

Start or continue graceful close and wait up to the configured timeout.

virtual void abort() noexcept override

Immediately abandon queued output and pending native work without waiting.

virtual StreamErrorContext createErrorContext() const noexcept override

Create a diagnostic context for errors reported by this source.

Implementations can add source-specific data or delegate to a wrapped source.

virtual text::StringEncoding encoding() const noexcept override

Get the encoding configured for the stream.

virtual text::StringEncoding effectiveEncoding() const noexcept override

Get the effective encoding used by the stream.

virtual StreamWriteStatus write(text::Char character) override

Write one character.

Parameters:

character – The character to write.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the character was accepted, or Timeout if nothing was accepted.

virtual StreamWriteStatus write(const text::String &text) override

Write text.

Parameters:

text – The text to write.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if all text was accepted, or Timeout if nothing was accepted.

virtual StreamWriteStatus writeLine() override

Write a line-feed character.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the line feed was accepted, or Timeout if nothing was accepted.

virtual StreamWriteStatus writeLine(const text::String &text) override

Write text followed by a line-feed character.

Parameters:

text – The text to write before the line-feed.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the complete line was accepted, or Timeout if nothing was accepted.

void throwError(text::String title, text::String description) const

Throw an error with a user-facing title and explanation.

Parameters:
  • title – What operation failed.

  • description – Why the operation failed.

class TextInputStream : public erbsland::stream::InputStream

A stream that reads decoded Unicode text.

Chunk reads return available decoded text. Line and aggregate reads retain partial text internally across timeouts, so callers repeat the same operation without joining fragments. Bounded allocating methods require a finite maximum; no-argument convenience methods use cDefaultTextReadMaximum.

Subclassed by erbsland::stream::impl::EncodedTextInputStream, erbsland::stream::impl::StandardInputStreamProxy

Public Functions

virtual text::StringEncoding encoding() const noexcept = 0

Get the encoding configured for the stream.

virtual text::StringEncoding effectiveEncoding() const noexcept = 0

Get the effective encoding used by the stream.

For BOM-detecting encodings, this returns the resolved concrete byte order after it is known.

StreamReadResult<text::String> read()

Read up to cDefaultTextReadMaximum decoded characters.

Throws:
  • stream::StreamError – If the stream is closed or the backing source fails.

  • text::EncodingError – If the stream was configured to throw on decoding errors and decoding fails.

Returns:

The status and decoded text. Timeout and Finished results have no caller-visible payload.

StreamReadResult<text::String> readLine()

Read one line using cDefaultTextReadMaximum as the maximum length.

The returned line includes its line ending when one is present. Partial text is retained after a timeout. Repeating the call continues the same line operation.

Throws:
  • stream::StreamError – If the stream is closed or the backing source fails.

  • text::EncodingError – If the stream was configured to throw on decoding errors and decoding fails.

Returns:

Data with a line, maximum-length chunk, or final unterminated line; otherwise an empty status.

StreamReadResult<text::String> readAll()

Read all remaining text using cDefaultTextReadMaximum as the maximum length.

Throws:
  • stream::StreamError – If the stream is closed or the backing source fails.

  • text::EncodingError – If the stream was configured to throw on decoding errors and decoding fails.

Returns:

Aggregated text, or an empty Timeout/Finished result.

virtual StreamReadResult<text::Char> readChar() = 0

Read one decoded character.

Throws:
  • stream::StreamError – If the stream is closed or the backing source fails.

  • text::EncodingError – If the stream was configured to throw on decoding errors and decoding fails.

Returns:

The status and next character.

virtual StreamReadResult<text::String> read(unit::CpLength maximum) = 0

Read up to maximum decoded characters.

Parameters:

maximum – The maximum number of decoded characters to read.

Throws:
  • err::ParameterError – If maximum is infinite.

  • stream::StreamError – If the stream is closed or the backing source fails.

  • text::EncodingError – If the stream was configured to throw on decoding errors and decoding fails.

Returns:

The status and decoded text. A data result may contain fewer than maximum characters.

virtual StreamReadResult<text::String> readLine(unit::CpLength maximum) = 0

Read one line.

The returned line includes its line ending when one is present.

Parameters:

maximum – The maximum number of decoded characters to read.

Throws:
  • err::ParameterError – If maximum is infinite.

  • stream::StreamError – If the stream is closed or the backing source fails.

  • text::EncodingError – If the stream was configured to throw on decoding errors and decoding fails.

Returns:

A complete line, maximum-length chunk, final unterminated line, or an empty status.

virtual StreamReadResult<text::String> readAll(unit::CpLength maximum) = 0

Read all remaining text.

Parameters:

maximum – The maximum number of decoded characters to read.

Throws:
  • err::ParameterError – If maximum is infinite.

  • stream::StreamError – If the stream is closed or the backing source fails.

  • text::EncodingError – If the stream was configured to throw on decoding errors and decoding fails.

Returns:

Aggregated text up to the finite maximum or end-of-stream, or an empty status.

util::CoTask<StreamReadResult<text::String>> coRead()

Asynchronously read one text block using the default maximum.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • stream::StreamError – When the task result is observed if the stream or backing source fails.

  • text::EncodingError – When the task result is observed if configured decoding fails.

Returns:

A task with the same result as read().

util::CoTask<StreamReadResult<text::String>> coRead(unit::CpLength maximum)

Asynchronously read one text block at a code-point boundary.

Parameters:

maximum – The maximum decoded code-point length.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • err::ParameterError – When the task result is observed if maximum is infinite.

  • stream::StreamError – When the task result is observed if the stream or backing source fails.

  • text::EncodingError – When the task result is observed if configured decoding fails.

Returns:

A task with the same result as read(maximum).

util::CoTask<StreamReadResult<text::String>> coReadLine()

Asynchronously read one line using the default maximum.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • stream::StreamError – When the task result is observed if the stream or backing source fails.

  • text::EncodingError – When the task result is observed if configured decoding fails.

Returns:

A task with the same result as readLine().

util::CoTask<StreamReadResult<text::String>> coReadLine(unit::CpLength maximum)

Asynchronously read one line.

Parameters:

maximum – The maximum decoded code-point length.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • err::ParameterError – When the task result is observed if maximum is infinite.

  • stream::StreamError – When the task result is observed if the stream or backing source fails.

  • text::EncodingError – When the task result is observed if configured decoding fails.

Returns:

A task with the same result as readLine(maximum).

util::CoTask<StreamReadResult<text::String>> coReadAll()

Asynchronously read all remaining text using the default maximum.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • stream::StreamError – When the task result is observed if the stream or backing source fails.

  • text::EncodingError – When the task result is observed if configured decoding fails.

Returns:

A task with the same result as readAll().

util::CoTask<StreamReadResult<text::String>> coReadAll(unit::CpLength maximum)

Asynchronously read all remaining text.

Parameters:

maximum – The maximum decoded code-point length.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • err::ParameterError – When the task result is observed if maximum is infinite.

  • stream::StreamError – When the task result is observed if the stream or backing source fails.

  • text::EncodingError – When the task result is observed if configured decoding fails.

Returns:

A task with the same result as readAll(maximum).

util::CoAsyncGenerator<StreamReadResult<text::String>> coReadBlocks()

Asynchronously generate text blocks using the default maximum block length.

Data and timeout results are yielded; end-of-stream completes the generator.

Throws:
  • err::LogicError – When first advanced if this stream is not shared-owned.

  • stream::StreamError – When advancing if the stream or backing source fails.

  • text::EncodingError – When advancing if configured decoding fails.

Returns:

A lazy generator for bounded text-block results.

util::CoAsyncGenerator<StreamReadResult<text::String>> coReadBlocks(unit::CpLength maximum)

Asynchronously generate text blocks at code-point boundaries.

Parameters:

maximum – The positive finite maximum for each block. Data and timeout results are yielded; end-of-stream completes the generator.

Throws:
  • err::ParameterError – When first advanced if maximum is zero or infinite.

  • err::LogicError – When first advanced if this stream is not shared-owned.

  • stream::StreamError – When advancing if the stream or backing source fails.

  • text::EncodingError – When advancing if configured decoding fails.

Returns:

A lazy generator for bounded text-block results.

util::CoAsyncGenerator<StreamReadResult<text::String>> coReadLines()

Asynchronously generate lines using the default maximum line length.

Data and timeout results are yielded; end-of-stream completes the generator.

Throws:
  • err::LogicError – When first advanced if this stream is not shared-owned.

  • stream::StreamError – When advancing if the stream or backing source fails.

  • text::EncodingError – When advancing if configured decoding fails.

Returns:

A lazy generator for bounded line results.

util::CoAsyncGenerator<StreamReadResult<text::String>> coReadLines(unit::CpLength maximum)

Asynchronously generate lines.

Parameters:

maximum – The positive finite maximum for each returned line or line fragment. Data and timeout results are yielded; end-of-stream completes the generator.

Throws:
  • err::ParameterError – When first advanced if maximum is zero or infinite.

  • err::LogicError – When first advanced if this stream is not shared-owned.

  • stream::StreamError – When advancing if the stream or backing source fails.

  • text::EncodingError – When advancing if configured decoding fails.

Returns:

A lazy generator for bounded line results.

Public Static Attributes

static constexpr auto cDefaultTextReadMaximum = unit::CpLength{10U * 1024U * 1024U}

The default maximum for no-argument text reads: 10 Mi code points.

class TextOutputStream : public erbsland::stream::OutputStream

A stream that writes decoded Unicode text.

Text output streams write characters and read-only strings. writeLine appends a single line-feed character after the optional text. Every call is atomic: Timeout means none of its encoded output was accepted and the complete call can be retried. Encoding invalid text uses replacement behavior.

Subclassed by erbsland::cterm::TerminalStream, erbsland::stream::AnyStringBuilderStream, erbsland::stream::TempTextOutputStream, erbsland::stream::impl::EncodedTextOutputStream, erbsland::stream::impl::StandardStreamProxy, erbsland::stream::impl::StandardTextOutputStream

Public Functions

virtual text::StringEncoding encoding() const noexcept = 0

Get the encoding configured for the stream.

virtual text::StringEncoding effectiveEncoding() const noexcept = 0

Get the effective encoding used by the stream.

virtual StreamWriteStatus write(text::Char character) = 0

Write one character.

Parameters:

character – The character to write.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the character was accepted, or Timeout if nothing was accepted.

virtual StreamWriteStatus write(const text::String &text) = 0

Write text.

Parameters:

text – The text to write.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if all text was accepted, or Timeout if nothing was accepted.

virtual StreamWriteStatus writeLine() = 0

Write a line-feed character.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the line feed was accepted, or Timeout if nothing was accepted.

virtual StreamWriteStatus writeLine(const text::String &text) = 0

Write text followed by a line-feed character.

Parameters:

text – The text to write before the line-feed.

Throws:

stream::StreamError – If the stream is closed or the backing target fails.

Returns:

Success if the complete line was accepted, or Timeout if nothing was accepted.

util::CoTask<StreamWriteStatus> coWrite(text::String text)

Asynchronously write owned text.

Parameters:

text – The text retained by the operation until it completes.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • stream::StreamError – When the task result is observed if the stream or backing target fails.

Returns:

A task with the same result as write(String).

util::CoTask<StreamWriteStatus> coWriteLine()

Asynchronously write one line-feed character.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • stream::StreamError – When the task result is observed if the stream or backing target fails.

Returns:

A task with the same result as writeLine().

util::CoTask<StreamWriteStatus> coWriteLine(text::String text)

Asynchronously write owned text followed by a line-feed character.

Parameters:

text – The text retained by the operation until it completes.

Throws:
  • err::LogicError – If this stream is not shared-owned.

  • stream::StreamError – When the task result is observed if the stream or backing target fails.

Returns:

A task with the same result as writeLine(String).

template<typename ...tArgs>
inline StreamWriteStatus print(const tArgs&... args)

Print one or more arguments to the stream.

This is a convenience helper for small output. For large text, prefer the low-level write... methods. Valid arguments are chars, string types, integers, floating-point values, booleans, values with toString() const returning text::String, and values with toRawValue() const returning a supported non-character integer. If both conversion methods exist, toString() is used. Change the integer or floating-point format by adding a format specifier before the affected value.

Parameters:

args – The arguments to print.

Returns:

Success if the complete formatted output was accepted, or Timeout if nothing was accepted.

template<typename ...tArgs>
inline StreamWriteStatus printLine(const tArgs&... args)

Print one or more arguments to the stream and add a line-break.

See also

print() for all details.

Parameters:

args – The arguments to print.

Returns:

Success if the complete formatted line was accepted, or Timeout if nothing was accepted.

class TextPrintContext

The print context interface for the print commands in the text streams.

You only need this interface if you implement a custom text stream subclass that uses an unusual backend storage, for all other uses, rely the default implementation and implement the write methods.

Subclassed by erbsland::stream::impl::PrintContextCommonBuilder

Public Functions

virtual StreamWriteStatus commit() = 0

Commit the printed content.

virtual void print(text::Char character) = 0

Print a character.

virtual void print(char character) = 0

Print a native character.

virtual void print(char8_t character) = 0

Print a UTF-8 code unit.

virtual void print(char16_t character) = 0

Print a UTF-16 code unit.

virtual void print(char32_t character) = 0

Print a UTF-32 code point.

virtual void print(const char *text) = 0

Print a null-terminated native string.

virtual void print(const char8_t *text) = 0

Print a null-terminated UTF-8 string.

virtual void print(const char16_t *text) = 0

Print a null-terminated UTF-16 string.

virtual void print(const char32_t *text) = 0

Print a null-terminated UTF-32 string.

virtual void print(std::nullptr_t) = 0

Print a null pointer as a null value.

virtual void print(std::string_view text) = 0

Print a native string view.

virtual void print(std::u8string_view text) = 0

Print a UTF-8 string view.

virtual void print(std::u16string_view text) = 0

Print a UTF-16 string view.

virtual void print(std::u32string_view text) = 0

Print a UTF-32 string view.

virtual void print(const text::String &text) = 0

Print an string.

virtual void print(const text::U16String &text) = 0

Print an UTF-16 string.

virtual void print(const text::U32String &text) = 0

Print an UTF-32 string.

virtual void print(bool value) = 0

Print a Boolean value.

virtual void print(double value) = 0

Print a double-precision floating-point value.

virtual void print(float value) = 0

Print a single-precision floating-point value.

virtual void print(int64_t value) = 0

Print a signed 64-bit integer.

virtual void print(uint64_t value) = 0

Print an unsigned 64-bit integer.

virtual void print(const mem::ByteBlock &bytes) = 0

Print a block of bytes.

virtual void print(text::BooleanFormat newFormat) = 0

Set the Boolean output format.

virtual void print(text::ByteFormat newFormat) = 0

Set the byte output format.

virtual void print(text::IntegerFormat newFormat) = 0

Set the integer output format.

virtual void print(text::FloatFormat newFormat) = 0

Set the floating-point output format.

template<std::size_t N>
inline void print(const char (&text)[N])

Print a native string literal.

template<std::size_t N>
inline void print(const char8_t (&text)[N])

Print a UTF-8 string literal.

template<std::size_t N>
inline void print(const char16_t (&text)[N])

Print a UTF-16 string literal.

template<std::size_t N>
inline void print(const char32_t (&text)[N])

Print a UTF-32 string literal.

inline void print(const std::string &text)

Print a native string without copying it.

inline void print(const std::u8string &text)

Print a UTF-8 string without copying it.

inline void print(const std::u16string &text)

Print a UTF-16 string without copying it.

inline void print(const std::u32string &text)

Print a UTF-32 string without copying it.

template<math::NativeInteger T>
inline void print(const T value)

Print a native integer.

template<impl::PrintObjectWithToString T>
inline void print(const T &value)

Print an object using its toString() result.

template<impl::PrintObjectWithRawInteger T>
inline void print(const T &value)

Print an object using its toRawValue() result.