Streams API
Declared by <huxerui/stream.h> in huxerui. Files, provider references, raw resources, and HTTP bodies use the same byte-stream operations; they differ in how a stream is opened and what authority it retains.
Results and errors
Section titled “Results and errors”IoResult<T> is Result<T, IoError>. Test Succeeded() before Value() or Error(); accessing the other alternative throws std::logic_error. IoResult<void> represents completion without a payload. Empty successful input means EOF; task cancellation suppresses result delivery and is neither EOF nor an error result.
IoError contains a stable code and diagnostic message. IoErrorCode includes NotFound, PermissionDenied, NotDirectory, IsDirectory, TooLarge, InvalidEncoding, Unsupported, Io, AlreadyExists, Timeout, and NoSpace. Sources report only applicable categories. Do not parse messages or assume a failure rolled back an already written prefix.
Choose and open a stream
Section titled “Choose and open a stream”| Source | Synchronous opening | Asynchronous opening |
|---|---|---|
| File | OpenRead() / OpenWrite(mode) return IoResult |
OpenReadAsync() / OpenWriteAsync(mode) return Task of IoResult |
| FileReference | OpenRead() / OpenWrite() return IoResult when supported by the provider |
OpenReadAsync() / OpenWriteAsync() return Task of IoResult |
| RawAsset | OpenRead() returns InputStream |
OpenReadAsync() returns Task of AsyncInputStream |
| HTTP response | Not exposed | HttpResponseStream::Body() borrows an already opened AsyncInputStream |
RawAsset opening uses resource exceptions and its later operations use IoResult. File opening can succeed even if a later read fails. Provider streams retain the reference’s access. Stream types are move-only and obtained from their sources.
InputStream and OutputStream
Section titled “InputStream and OutputStream”InputStream::Read(std::span<std::byte>) returns the valid byte count in the buffer’s prefix. Supply a nonempty scratch buffer. A short read is not EOF; zero is. Further reads after EOF return zero. CopyTo(OutputStream&, scratch) copies from the current position through EOF and returns a total byte count without closing either endpoint.
OutputStream::Write(std::span<const std::byte>) accepts the entire range on success; an empty write is valid. Close() finalizes output and is idempotent after success. A failed write or close makes that stream unusable. Destruction releases or aborts it but is not a successful close. Calls run on the calling thread and can block.
Random-access streams
Section titled “Random-access streams”Use OpenRandomAccess() on a File or a seekable FileReference for offset-based I/O. RandomAccessStream is move-only and keeps the opened resource and its grant alive. Serialize its synchronous operations, including closing and moving it to another thread. Run blocking work off the UI thread on platforms with workers.
| Operation | Contract |
|---|---|
ReadAt(offset, buffer) |
Read at an absolute byte offset into a nonempty buffer. A short read is valid and a successful zero means EOF at that offset. A failed read leaves the stream usable. |
WriteAt(offset, bytes) |
Write the whole range on success. A nonempty write beyond EOF extends the file and the gap reads as zeros. A backend failure can leave a written prefix and makes the stream unusable. |
Size() |
Returns IoResult<std::optional<std::uint64_t>>. An empty optional means the size is unknown, while zero means a known empty file. |
Close() |
Releases the resource on success and can then be called again. A failed close cannot be retried. Close does not roll back writes or promise power-loss durability. |
Offsets outside backend limits report TooLarge. Wrong access mode, moved-from handles, and use of failed or closed streams are logic errors. Android provider references require a compatible seekable descriptor. Browser-selected files use asynchronous streams. Persistent local Web paths reject writable random-access opening so changes can use the asynchronous persistence path.
#include <huxerui/huxerui.h>
using namespace huxerui;
IoResult<std::size_t> ReadHeader(const FileReference& reference, std::uint64_t offset, std::span<std::byte> buffer) { auto opened = reference.OpenRandomAccess(); if (!opened.Succeeded()) { return IoResult<std::size_t>::Failure(opened.Error()); } auto& stream = opened.Value(); auto read = stream.ReadAt(offset, buffer); auto closed = stream.Close(); if (read.Succeeded() && !closed.Succeeded()) { return IoResult<std::size_t>::Failure(closed.Error()); } return read;}Supply a nonempty buffer and inspect the returned byte count before parsing its prefix. For a sequential transfer or Web picker reference, use the async stream contract below.
AsyncInputStream and AsyncOutputStream
Section titled “AsyncInputStream and AsyncOutputStream”ReadAsync(maximum_bytes) returns a Task yielding owned Bytes, with a positive maximum chosen by the caller. WriteAsync(Bytes) retains its argument until completion. CopyToAsync(destination, maximum_read_size) transfers bounded chunks and yields the copied byte count. It does not close either endpoint; await CloseAsync() on the writer after a successful copy.
Each stream permits one outstanding operation. The slot is reserved when the operation method returns its Task, not only when awaited; an unstarted Task must be destroyed before another operation can begin. Copy reserves both endpoints. Keep handles alive while operations run. Invalid sizes throw std::invalid_argument; overlapping operations, moved-from values, or reusing failed streams throw std::logic_error.
Cancellation requests underlying cancellation and suppresses completion, but a platform operation may finish before releasing its resources. No operation promises rollback. Async continuations follow their Task execution context; async does not imply a dedicated worker thread.
Adapt a reader or writer
Section titled “Adapt a reader or writer”Use InputStream::FromReader or AsyncInputStream::FromReader for an application-owned source. The synchronous reader fills a borrowed span and returns a byte count. The asynchronous reader receives a stop token and a maximum byte count and returns owned bytes. Zero bytes mean EOF in both cases. A short nonzero read is allowed.
OutputStream::FromWriter and AsyncOutputStream::FromWriter require the callback to accept the full chunk on success. The optional close callback finalizes the destination. A discarded, unclosed stream calls the optional abort callback, which must not throw. Async writers take ownership of their chunk and receive a stop token. Keep the stream alive until its operation completes and keep overlapping operations off the same stream.
#include <huxerui/huxerui.h>
#include <memory>#include <vector>
using namespace huxerui;
OutputStream CollectBytes(std::shared_ptr<std::vector<std::byte>> buffer) { return OutputStream::FromWriter([buffer](std::span<const std::byte> chunk) { buffer->insert(buffer->end(), chunk.begin(), chunk.end()); return IoResult<void>::Success(); });}Copy a file with bounded memory
Section titled “Copy a file with bounded memory”#include <huxerui/huxerui.h>
using namespace huxerui;
Task<void> CopyDocument(File source, File destination, State<std::string> status) { auto input = co_await source.OpenReadAsync(); if (!input.Succeeded()) { status = input.Error().message; co_return; } auto output = co_await destination.OpenWriteAsync(); if (!output.Succeeded()) { status = output.Error().message; co_return; } auto copied = co_await input.Value().CopyToAsync(output.Value(), 64 * 1024); if (!copied.Succeeded()) { status = copied.Error().message; co_return; } auto closed = co_await output.Value().CloseAsync(); status = closed.Succeeded() ? "Copy complete" : closed.Error().message;}Launch from an owning TaskScope. Source and destination must be distinct files, including through aliases; opening the destination truncates it. Its parent must exist. Use an application-owned temporary destination when incomplete output must not replace a user’s document. Successful close completes the destination’s contract, not a universal transaction or power-loss guarantee.
Decode after reading
Section titled “Decode after reading”Streams operate on bytes: chunks can split UTF-8 characters, JSON tokens, or records. Use an incremental decoder or collect a bounded amount before decoding. Raw resources preserve bytes; File’s complete ReadString operation additionally validates UTF-8. A byte count is not a character count.

