# `Box<T>`

`Box<T>` owns a heap-allocated value through a managed handle. It is available
from the prelude. Use it when a value needs indirection, when a recursive type
would otherwise have an infinite layout, or when an owned value must outlive
the stack frame that constructs it.

A box handle and its payload are distinct. Moving a handle transfers ownership;
cloning a box shares its payload. A clone is not an independent deep copy, and
a mutable binding does not make a shared payload writable.

## Construction and reads

```vex
fn main(): i32 {
    let number = Box.new<i32>(42);
    $println(number.get());
    $println(*number.getRef());
    return 0;
}
```

Expected stdout is `42` on each of two lines, with exit status 0. `Box(42)` is
also constructor syntax. `Box.new<T>(value)` makes the type argument explicit
and transfers an owning `value` into the allocation.

Choose a read operation according to the result you need:

| Operation | Result and effect |
| --- | --- |
| `get()` | Returns a value while leaving the box populated. The current prelude rejects payloads that need drop; use a borrow or an ownership transfer for them. |
| `getRef()` | Returns `&T`; the box must be populated and remain alive while the reference is used. |
| `getRefOpt()` | Returns `Option<&T>`; an empty box returns `None`. |
| `isValid()` | Reports whether the handle is populated. It does not establish uniqueness or authorize raw-pointer access. |

For example, inspect a `Box<Vec<i32>>` through `getRef()`; do not use `get()` to
copy its owning vector out. To make independent data, use the payload type's
explicit cloning or reconstruction operation and put that result in a new box.

## Exclusive mutation

The mutable operations require an exclusive borrow of the handle. They also
check whether another managed handle shares the payload:

| Operation | Populated, sole handle | Empty or shared handle |
| --- | --- | --- |
| `getRefMut()` | Returns `&T!` | Shared payload panics; an empty handle is not a valid receiver. Prefer the optional form when emptiness is possible. |
| `getRefMutOpt()` | Returns `Some(&T!)` | Returns `None`. |
| `set(value)` | Drops the previous payload and replaces it | Panics. It is not a way to refill an empty box. |

```vex
fn main(): i32 {
    let! number = Box.new<i32>(41);
    match number.getRefMutOpt() {
        Some(value) => { *value = *value + 1; },
        None => { return 1; },
    };
    $println(number.get());
    return 0;
}
```

The intended output is `42`, exit status 0. If the optional borrow returns
`None`, the program exits 1 instead of dereferencing an unavailable value.
All normal borrow rules still apply: uniqueness of a box handle does not
permit a write that conflicts with a live reference into its payload.

Shared ownership provides lifetime management, not synchronized mutable
access. Use channels, atomics, or an appropriate synchronization API for
shared state; do not bypass the check with a raw pointer.

## Taking ownership out

`take()` and `tryTake()` borrow the box mutably. On success they transfer the
payload out and **leave the existing box handle empty**. They do not make the
binding disappear.

```vex
fn main(): i32 {
    let! number = Box.new<i32>(42);
    let value = number.take();
    if number.isValid() { return 1; }
    if number.tryTake().isSome() { return 2; }
    $println(value);
    return 0;
}
```

Expected stdout is `42`, exit status 0. The value is now owned by `value`.
Dropping the empty box does not drop that value a second time.

| Operation | Success | Failure |
| --- | --- | --- |
| `take()` | Returns `T`; leaves the box empty | Panics if empty or another handle shares the payload. |
| `tryTake()` | Returns `Some(T)`; leaves the box empty | Returns `None` and leaves the box unchanged. |

To reuse an empty binding, assign a newly constructed box. Do not call
`getRef`, `get`, or `set` on the empty handle.

## Cloning, swapping, and cleanup

`clone()` creates another managed handle to the same payload. While both
handles exist, `getRefMutOpt()` and `tryTake()` return `None`. The panicking
mutation and take forms refuse the same sharing condition. Releasing the
other handles can restore uniqueness, subject to the ordinary borrow rules.

This complete example observes sharing, releases one handle, then mutates
through the remaining handle:

```vex [box-sharing.vx]
fn main(): i32 {
    let! owner = Box.new<i32>(41);
    let! alias = owner.clone();
    if owner.getRefMutOpt().isSome() { return 1; }
    if owner.tryTake().isSome() { return 2; }
    $println(*alias.getRef());
    alias.drop();
    match owner.getRefMutOpt() {
        Some(value) => { *value += 1; },
        None => { return 3; },
    };
    $println(owner.get());
    return 0;
}
```

Expected stdout is `41` followed by `42`, with exit status 0. The optional
operations leave the shared box unchanged. The explicit `alias.drop()` makes
the end of that handle visible; scope cleanup is sufficient when an earlier
release is unnecessary.

`swap(&other!)` swaps the **handles**, including their empty or populated
state; it does not mutate the two payloads in place. Each handle subsequently
owns the allocation it received.

Scope cleanup releases a handle. The payload is destroyed and its storage is
reclaimed when the final owning handle is released. Explicit `drop()` also
releases this handle and leaves it empty; normal scope-based cleanup is easier
to reason about unless early release is needed.

## Recursive types

Indirection makes a recursive representation finite:

```vex
enum List<T> {
    Cons(T, Box<List<T>>),
    Nil,
}
```

This is a type-definition fragment, not a full collection implementation.
Traversal and updates must still respect borrowing and sharing.

## Raw addresses and implementation boundaries

`asPtr()` borrows the address without transferring ownership. Do not free that
address or keep using it after the box's allocation is released. A raw address
also does not grant mutable access to a shared payload.

The prelude implementation contains `fromRaw` and `intoRaw` helpers, but they
are not exported as ordinary application API in the inspected source. Their
presence in source is not a portable FFI ownership-transfer recipe. Prefer an
explicitly documented foreign-resource wrapper; see [FFI](../ffi.md).

Representation, reference-count placement, and allocation elimination are
compiler decisions. The public contract is ownership and access to the
payload; it does not prescribe a binary layout or fixed allocation cost.

## See also

- [Ownership](ownership.md)
- [Borrowing](borrowing.md)
- [VUMM](vumm.md)
- [Typed raw pointers](ptr-t.md)
- [Vectors](../types/vec.md)
