bytes
import std::io::bytes; · source
Fixed-width integers to and from bytes, in a stated byte order. Each method is generic over the integer type and names its order in full — big_endian (most significant byte first, the network order of the wire protocols) or little_endian (least significant first) — so a call site says which layout it reads or writes, whatever the host's own order is. The width is the type's: a u16 is two bytes, an i64 eight.
import std::io::bytes::{ ByteReader, ByteWriter };
import std::io::error::{ IoError };
function round_trip() -> Result<u32, IoError> {
mut out: Array<u8> = Array::new();
mut writer: ByteWriter = ByteWriter::new(&out);
writer.write_big_endian::<u16>(0x0102);
writer.write_little_endian::<u32>(7);
mut reader: ByteReader = ByteReader::new(out.as_slice());
const tag: u16 = reader.read_big_endian::<u16>()?;
const length: u32 = reader.read_little_endian::<u32>()?;
return Result::Ok(length + (tag as u32));
}
function main() -> int {
return if (round_trip().unwrap() == 7 + 0x0102) { 0 } else { 1 };
}
Types
ByteReader
type struct ByteReader {
private bytes: &Slice<u8>;
private position: i64;
}
Walks a borrowed &Slice<u8> front to back, decoding one integer per call. The slice's storage must outlive the reader. A read that needs more bytes than remain fails with UnexpectedEof and leaves the position where it was. position() is the offset of the next byte, remaining() the bytes left, and set_position moves to an absolute offset — one past the end is allowed, and every read from there fails.
Constructors
static new(bytes: &Slice<u8>) -> ByteReader;
static new(bytes: &Slice<u8>) -> ByteReader;A reader at the first byte of bytes. The slice is borrowed: its storage must outlive the reader.
Methods
position(&this) -> i64;
position(&this) -> i64;The offset of the next byte a read takes.
set_position(mut &this, position: i64) -> void;
set_position(mut &this, position: i64) -> void;Move to the absolute offset position. An offset past the end is allowed, and every read from there fails; a negative one panics.
remaining(&this) -> i64;
remaining(&this) -> i64;The number of bytes left to read, 0 at or past the end.
read_big_endian<T>(mut &this) -> Result<T, IoError> where T: Integer;
read_big_endian<T>(mut &this) -> Result<T, IoError> where T: Integer;The next T, most significant byte first: as many bytes as T is wide. Like every read here, it fails with UnexpectedEof, and does not move, when too few bytes remain.
read_little_endian<T>(mut &this) -> Result<T, IoError> where T: Integer;
read_little_endian<T>(mut &this) -> Result<T, IoError> where T: Integer;The next T, least significant byte first: as many bytes as T is wide. Fails with UnexpectedEof, without moving, when too few bytes remain.
ByteWriter
type struct ByteWriter {
private array: mut Array<u8>*;
private region: mut &Slice<u8>;
private written: i64;
}
new(out) appends to a borrowed Array<u8>, after whatever it already holds; over(region) writes into a fixed region from its first byte — a header packed into a buffer a C call reads, a digest's output block. Writes return nothing: a write panics if the array cannot grow, or if it would pass the end of an over region. position() is how many bytes have been written.
Constructors
static new(out: mut &Array<u8>) -> ByteWriter;
static new(out: mut &Array<u8>) -> ByteWriter;A writer appending to out, after whatever it already holds.
static over(region: mut &Slice<u8>) -> ByteWriter;
static over(region: mut &Slice<u8>) -> ByteWriter;A writer into region, from its first byte: a header packed into a buffer a C call reads, a digest's output block.
Methods
position(&this) -> i64;
position(&this) -> i64;How many bytes this writer has written - into a region, the offset of the next write.
write_big_endian<T>(mut &this, value: T) -> void where T: Integer;
write_big_endian<T>(mut &this, value: T) -> void where T: Integer;Write value most significant byte first, as many bytes as T is wide. Like every write here, it panics when a writer made by over runs past the end of its region.
write_little_endian<T>(mut &this, value: T) -> void where T: Integer;
write_little_endian<T>(mut &this, value: T) -> void where T: Integer;Write value least significant byte first, as many bytes as T is wide.
import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
type struct ByteReader {}Decodes integers from a borrowed byte slice, advancing past each one.
std::io::bytestype struct ByteWriter {}Encodes integers onto the end of a borrowed Array<u8> (new), or into a fixed region of memory from its first byte (over). A write panics if the array cannot grow, as Array.push does, or if it would pass the end of the region.
type struct IoError {
kind: IoErrorKind;
os_code: i32;
}The error of a failed I/O operation: its kind, the operating system's own code, and, when the operation named one, what it was doing and the path. It prints as could not open config.toml: not found.
function name<T>(param: Type) -> Ret { ... }Declares a function. Parameters are written name: Type and are never inferred; the return type follows -> and defaults to void. Declaration order does not matter: every signature is collected before any body is checked, so functions may call each other freely and recurse.
function round_trip() -> Result<u32, IoError>type enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
mut name: Type = value;A mutable binding, reassignable after declaration - mutability is opt-in, const is the default. At module level it declares mutable global state. Before & it marks an exclusive reference or receiver instead.
mut out: Array<u8>type struct Array<T, A = GlobalAllocator> where A: Allocator {}A growable sequence of Ts stored contiguously, owning its elements; A is the allocator its storage comes from. Indexing out of range panics; get answers None instead.
static Array::new() -> Array<T, GlobalAllocator>Empty array backed by GlobalAllocator.
mut writer: ByteWriterstatic ByteWriter::new(out: mut &Array<u8>) -> ByteWriterA writer appending to out, after whatever it already holds.
mut out: Array<u8>mut writer: ByteWriterByteWriter::write_big_endian<T>(mut &this, value: T) -> void
where T: IntegerWrite value most significant byte first, as many bytes as T is wide. Like every write here, it panics when a writer made by over runs past the end of its region.
ByteWriter::write_little_endian<T>(mut &this, value: T) -> void
where T: IntegerWrite value least significant byte first, as many bytes as T is wide.
mut reader: ByteReaderstatic ByteReader::new(bytes: &Slice<u8>) -> ByteReaderA reader at the first byte of bytes. The slice is borrowed: its storage must outlive the reader.
const name: Type = value;An immutable binding: it cannot be reassigned after initialisation. The annotation may be omitted when an initialiser is present - the binding takes the initialiser's concrete type, inferred locally. Mutability is opt-in through mut.
const tag: u16mut reader: ByteReaderByteReader::read_big_endian<T>(mut &this) -> Result<T, IoError>
where T: IntegerThe next T, most significant byte first: as many bytes as T is wide. Like every read here, it fails with UnexpectedEof, and does not move, when too few bytes remain.
value?Error propagation. On a Result<T, E> it yields the T of an Ok and otherwise returns the Err(e) from the enclosing function unchanged; on an Option<T> it yields the T of a Some or returns None. It works on any type implementing Try, in a function whose return type implements FromResidual of it; an error of another type converts through From.
const length: u32ByteReader::read_little_endian<T>(mut &this) -> Result<T, IoError>
where T: IntegerThe next T, least significant byte first: as many bytes as T is wide. Fails with UnexpectedEof, without moving, when too few bytes remain.
return value;Leaves the current function with the given value. A function whose return type is not void must return one; a bare return; is for void. In an async function it completes the future with the value.
Result::Ok(T)const length: u32const tag: u16value as TypeExplicit conversion: between numeric types, or reinterpreting one pointer type as another. Cryo never converts implicitly, and as inserts no range checks - a narrowing cast is the programmer's responsibility.
function main() -> intif (condition) { ... } else if (condition) { ... } else { ... }Branches on a parenthesised boolean condition. Bodies are always braced; there is no single-statement form. Used as an expression, both arms are required and must produce the same type: const sign = if (n < 0) { -1 } else { 1 };.
function round_trip() -> Result<u32, IoError>Result::unwrap(this) -> TThe Ok value, aborting on Err. Consumes the result: the value moves out to the caller and the error, if any, is released.
if (condition) { ... } else { ... }The branch taken when every preceding if condition is false; else if chains another condition. In expression form the else arm is mandatory, so the expression always has a value.
type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct ByteReader {}Decodes integers from a borrowed byte slice, advancing past each one.
private type struct Name { ... }
private:Confined to the module that declares it - for items and members alike. A private field or function reached from another module is E0353, and a private type named there is E0503. private: opens a block of such members.
ByteReader.bytes: &Slice<u8>type struct Slice<T> {}The elements are reached through ptr, declared read-only: through a mut &Slice<T> it reads as a writable pointer, through a &Slice<T> as the read-only one it is.
ByteReader.position: i64type struct ByteWriter {}Encodes integers onto the end of a borrowed Array<u8> (new), or into a fixed region of memory from its first byte (over). A write panics if the array cannot grow, as Array.push does, or if it would pass the end of the region.
ByteWriter.array: mut Array<u8>*ByteWriter.region: mut &Slice<u8>mut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
ByteWriter.written: i64IoErrorKind::UnexpectedEofByteReader::remaining(&this) -> i64The number of bytes left to read, 0 at or past the end.
std::io::bytesByteReader::set_position(mut &this, position: i64) -> voidMove to the absolute offset position. An offset past the end is allowed, and every read from there fails; a negative one panics.
static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
(parameter) bytes: &Slice<u8>&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
(parameter) position: i64where T: Ord + Clone, U: HashConstrains generic parameters to types that implement the listed traits, which is what makes those traits' methods callable on T. Bounds on one parameter join with +; parameters separate with ,. A where on a single method narrows the type's parameter for that method only.
type trait Integer : Numeric {}The built-in integer types: i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128 and usize.
static ByteWriter::over(region: mut &Slice<u8>) -> ByteWriterA writer into region, from its first byte: a header packed into a buffer a C call reads, a digest's output block.
(parameter) out: mut &Array<u8>(parameter) region: mut &Slice<u8>(parameter) value: T