Unsafe Code and Low-Level Programming

27.1 unsafe Blocks

Required for: pointer arithmetic, nil references, goto, unions, calling @[unsafe] fns, manual memory, indexing raw pointers, and more.

mut arr := [1, 2, 3]
unsafe {
	p := &arr[0]
	p2 := p + 1                  // pointer arithmetic
	println(*p2)                 // 2
	mut raw := malloc(16)
	vmemset(raw, 0, 16)
	free(raw)
}
@[unsafe]
fn dangerous() {}
unsafe { dangerous() }

27.2 Memory Functions

malloc, vcalloc, realloc, free, vmemcpy, vmemmove, vmemset, vmemcmp, memdup, sizeof(T), __offsetof(T, field), isreftype(T).

27.3 Low-Level Features

Inline assembly: asm amd64 { ... } with inputs and outputs (advanced, platform-specific).

Freestanding / bare-metal: -freestanding, -os options (used by Vinix), -gc none, -no-builtin.

@[packed]
struct Header {
	magic   u32
	version u8
	flags   u16
}
x := u32(0x12345678)
bytes := unsafe { *(&[4]u8(&x)) }        // reinterpret
import encoding.binary
mut buf := []u8{len: 4}
binary.big_endian_put_u32(mut buf, x)
println(binary.little_endian_u32(buf))
import math.bits
println(bits.ones_count_32(0b1011))
println(bits.leading_zeros_64(1))