Advanced Topics

⚠ Warning: This section covers low-level operations that bypass Zith's safety guarantees. Only use these when absolutely necessary and when you fully understand the implications.

What is "Raw & Unsafe"?

Zith's safety model handles 95% of use cases. The raw and unsafe features are reserved for situations where you need:

  1. FFI (Foreign Function Interface) — Calling C libraries directly
  2. Raw pointer arithmetic — Custom memory layouts and allocators
  3. Inline assembly — Platform-specific optimizations
  4. Custom allocators — Building your own memory management

Key Concepts

unsafe Blocks

Code inside an unsafe block bypasses Zith's safety checks:

unsafe {
    // All code here bypasses safety checks
    let ptr = 0x1000 as *u8;
    *ptr = 42;  // Direct memory write
}

Raw Functions

Functions declared with raw fn allow unsafe operations in their body:

raw fn readRegister(addr: opaque): u32 {
    let ptr = addr as *u32;
    *ptr
}

The Trust Capability

Trust lets you expose safe wrappers over unsafe internals:

trait MMIONode extends Trust {
    raw fn read(self, offset: u64): u32 {}
    raw fn write(self, offset: u64, val: u32) {}
}

fn safeCopy(src: view MMIONode, dst: lend MMIONode) {
    let v = src.read(0x00);
    dst.write(0x00, v);
}

When to Use Raw & Unsafe

Appropriate uses:

Avoid when:

Topics in This Section

Topic Description
How to Use Best practices for organizing raw/unsafe code
Traits Advanced trait usage with Trust and raw types
Generics Deep Dive Complex generic patterns
Metaprogramming Comptime and code generation
Macros Macro system with @ prefix
Data Structures Building custom data structures
Unsafe Operations Detailed unsafe block usage
Raw Pointers Complete raw pointer guide

Safety Guidelines

  1. Minimize unsafe scope — Keep unsafe {} blocks as small as possible
  2. Document invariants — Explain why the unsafe code is safe
  3. Add runtime checks — Validate inputs before entering unsafe blocks
  4. Write tests — Especially for unsafe code paths
  5. Review carefully — Unsafe code requires extra scrutiny

Example: Safe Wrapper Around Unsafe Code

fn getElement(arr: view [i32], index: usize): ?i32 {
    if (index >= arr.len()) ? none
    arr[index]
}

Next Steps


⚠ Caution: With great power comes great responsibility. Always prefer safe Zith constructs when possible.