LEARN VOID

Binary values and memory streams

Choose a byte order before storing a number or reading a protocol field.

binary-memory.voidDownload source
use encoding/binary as binary

func entry(identifier: i32) -> i32:
    var packet = binary.encode(identifier as u16, binary.byte_order.big)
    return packet[0] as i32
Input 258Expected result 1

Read the first byte

Encoding the unsigned value 258 in big-endian order gives bytes 1 and 2. The example returns the first byte. Include width and byte order in a file format so a reader on another machine can decode it.

Use a memory cursor

use io/memory as memory supplies memory.stream(). Write typed values, seek back to the beginning and read using the same order. These operations return results. Check a failed seek or short read before using its value.

Keep an independent snapshot

to_bytes() returns a copy of the stream contents. Use read_exact(count) for fixed-size fields and read_bytes(max_count) when a shorter block is acceptable.

Decode from a cursor

The stream starts at offset zero with little-endian order. Reading two bytes advances the cursor. A low byte of two and a high byte of one represent 258.

read-field.voidDownload source
use io/memory as memory

func entry(low_byte: i32) -> i32:
    var field: [u8] = [low_byte as u8, 1]
    var packet = memory.stream(field)
    if packet.read<u16>() is Ok(var number):
        return number as i32
    return -1
Input 2Expected result 258

Continue learning with Files and paths.