//! returns: 0
//! A heap that the kernel provides is an owned pointer, which a record holds and which grows
//! slices of pointers.

/// The allocation error, which the compiler knows.
@language union AllocError: Copy { OutOfMemory }

/// A heap, which holds elements of any type.
@language record Heap {}

/// The allocator view of a heap, which provides plain elements.
@language record Allocator {}

@intrinsic fn pageHeap(handle: u64, out: &mut ?*Heap) -> i64;

/// A record that holds pointers, which only a heap can provide.
record Item {
    /// Owned pointer to a number.
    p: *u32,
}

/// A domain that keeps its heap in its state.
record Server {
    /// Heap of the server.
    heap: *Heap,
    /// Items that grow in the heap.
    items: *mut [Item],
}

/// Turn a Page into a heap, or nothing when the kernel refuses.
fn convert(handle: u64) -> ?*Heap {
    let mut heap: ?*Heap = nil;
    if pageHeap(handle, &mut heap) <> 0 {
        return nil;
    }
    return heap;
}

/// Grow the items of a server in its heap, through a shared reference.
fn add(s: &mut Server, item: Item) throws (AllocError) {
    try s.items.append(item, s.heap);
}

/// Start a server in a Page, and grow it.
fn start(handle: u64, item: Item) -> u32 {
    let heap = convert(handle) else {
        return 0;
    };
    let mut server = Server { heap, items: &mut [] };
    try add(&mut server, item) catch {
        return 0;
    };
    return server.items.len;
}

/// A heap view for plain elements.
fn plain(h: &Heap, xs: *mut [u32]) throws (AllocError) {
    let mut ys = xs;
    let a: &Allocator = h;
    try ys.append(1, a);
}

@default fn main() -> i32 {
    return 0;
}
