Skip to content

Bytes and IO

Chloë Strainge edited this page Oct 14, 2026 · 1 revision

Bytes, files, readers, and writers

Strings represent text; std::io::Bytes represents arbitrary bytes. Construct it from UTF-8 text or integer bytes, then decode explicitly when text is intended.

import std::io
let $bytes = std::io::Bytes("λ")
echo $bytes.count $bytes.decode_utf8
let $raw = std::io::Bytes([65, 0, 66])
echo $raw.to_array...
2 λ
65 0 66

Bytes support counting, slicing, concatenation, Base64 encoding, and conversion to an integer array. UTF-8 decoding can fail; binary data need not be valid text.

Readers have a position

memory_reader reads Bytes. open_reader reads a file. A Reader's read returns Bytes or () at end; read_exact requires the requested length. read_all is bounded: its default limit is 16 MiB, and the supported maximum is 64 MiB.

import std::io
let $reader = std::io::memory_reader std::io::Bytes("station")
try
{
    echo ($reader.read_exact 3).decode_utf8
    echo $reader.read_all.decode_utf8
}
finally { $reader.close }
sta
tion

lines converts a reader to a String iterator; records supports byte separators. A line's terminator is consumed rather than becoming part of the returned text. Close adapters and owned readers when leaving a scope.

Files and ownership

read_bytes, read_text, write_bytes, and write_text are whole-file helpers. For incremental output, use open_writer, write, flush, and close. copy transfers a reader into a writer without routing binary content through text.

import std::io
std::io::write_text "note.txt" "bring a map"
echo (std::io::read_text "note.txt")
bring a map

Reader and Writer copies share their native handle and current position. They are resources, unlike ordinary array value copies. Some adapters hold a lease to prevent another consumer from reading the same source while an operation owns it. Use try/finally for deterministic closing.

ByteSource and byte sinks connect chunked operations to pipelines. read_file and write_file provide corresponding sources and sinks; these preserve bytes and avoid an unnecessary UTF-8 conversion.


Related: Errors and cleanup · Item streams · Networking

Clone this wiki locally