# Ownership Workflows

Choose the result's ownership before choosing its container. A parser can
return a view into input that remains alive; a report intended to outlive its
source needs owned data. The following complete programs show both designs,
including error paths and observable results.

| Result needed | Useful shape | Who keeps the data alive? |
| --- | --- | --- |
| Read part of an existing buffer | `Span<T>` | The original owner |
| Inspect an existing record | `&T` | The record's owner |
| Keep selected data after the source is released | `Vec<T>` containing owned values | The returned Vec |
| Remove a value from a collection | `Option<T>` from `pop` or `remove` | The caller, after a successful removal |

## Parse a frame without copying its payload

This small wire format has a three-byte header: magic byte `0x56`, a message
kind, and a payload length stored as one `u8`. It accepts exactly one complete
frame. A short header, an unknown magic byte, and a mismatched payload length
produce different errors.

`parseFrame` borrows the input through a `Span<u8>`. The returned `Packet`
contains a view of the payload, so the input Vec remains alive while the packet
is used. The parser creates no owned payload copy. The `wire` helper uses a
[typed variadic pack](../types/variadics.md) to build sample input.

```vex [borrowed-packet.vx]
struct Packet { kind: u8, payload: Span<u8> }
enum FrameError { TruncatedHeader, BadMagic, LengthMismatch }
fn parseFrame(bytes: Span<u8>): Result<Packet, FrameError> {
    if bytes.len() < 3 { return Err(FrameError.TruncatedHeader); }
    if bytes[0] != 0x56 { return Err(FrameError.BadMagic); }
    let length = bytes[2] as usize;
    if bytes.len() - 3 != length { return Err(FrameError.LengthMismatch); }
    return Ok(Packet { kind: bytes[1], payload: bytes.slice(3, bytes.len()) });
}
fn wire(values: ...u8): Vec<u8> {
    let! output = Vec.new<u8>();
    for value in values { output.push(*value); }
    return output;
}
fn main(): i32 {
    let input = wire(0x56, 1, 3, 10, 20, 30);
    let packet = match parseFrame(input.asSpan()) {
        Ok(value) => value,
        Err(_) => { return 1; },
    };
    let! total: u32 = 0;
    for value in packet.payload { total += *value as u32; }
    if packet.kind != 1 || packet.payload.len() != 3 || total != 60 { return 2; }
    $println(f"kind={packet.kind} bytes={packet.payload.len()} total={total}");
    let short = wire(0x56, 1);
    let badMagic = wire(0, 1, 0);
    let badLength = wire(0x56, 1, 2, 10);
    match parseFrame(short.asSpan()) { Err(FrameError.TruncatedHeader) => {}, _ => { return 3; }, };
    match parseFrame(badMagic.asSpan()) { Err(FrameError.BadMagic) => {}, _ => { return 4; }, };
    match parseFrame(badLength.asSpan()) { Err(FrameError.LengthMismatch) => {}, _ => { return 5; }, };
    $println("3 invalid frames rejected");
    return 0;
}
```

Run `vex run borrowed-packet.vx`. Expected stdout:

```text
kind=1 bytes=3 total=60
3 invalid frames rejected
```

The program exits 0 after checking the valid result and each error variant.
The header-size check occurs before indexing, and subtraction occurs only
once at least three bytes exist. Checking the exact length before `slice` is
important: `slice` clamps its bounds, which is useful for views but would not
itself reject a truncated frame. This format rejects trailing bytes too; a
stream parser would additionally return how much input it consumed.

Keep `input` alive and avoid changing its storage until the last use of
`packet.payload`. Copying a `Span` copies its descriptor and keeps the same
lifetime requirement. If the packet must outlive the input, use
`packet.payload.toVec()` to clone its bytes into an owned buffer and return
that owned buffer instead. See [Span](span-t.md) for exact-size and
clamped view operations, and [Error Handling](../error-handling.md) for
propagating a `Result`.

## Return a report that outlives its source

An inventory report often needs only a few fields from larger records.
`replenishment` borrows the inventory, selects items below their reorder level,
and clones their names into a new Vec. It leaves the inventory unchanged.

```vex [owned-report.vx]
struct Item { name: string, stock: i32, reorderAt: i32 }
fn replenishment(items: &Vec<Item>): Vec<string> {
    let! names = Vec.new<string>();
    for item in items {
        if item.stock < item.reorderAt { names.push(item.name.clone()); }
    }
    return names;
}
fn main(): i32 {
    let! items = Vec.new<Item>();
    items.push(Item { name: "paper", stock: 2, reorderAt: 5 });
    items.push(Item { name: "clips", stock: 10, reorderAt: 5 });
    items.push(Item { name: "ink", stock: 0, reorderAt: 2 });
    let report = replenishment(&items);
    Mem.drop(items);
    if report.len() != 2 || report[0] != "paper" || report[1] != "ink" { return 1; }
    for name in report { $println(name); }
    $println(f"{report.len()} items need replenishment");
    return 0;
}
```

Run `vex run owned-report.vx`. Expected stdout:

```text
paper
ink
2 items need replenishment
```

The result's names remain valid after `Mem.drop(items)` because each explicit
`string.clone()` produces an independent string. The returned Vec owns those
strings and releases them when it is destroyed. Iteration over `items` borrows
each `Item`; it does not remove records from the inventory.

Returning `Vec<&string>` instead would retain references into the original
records and would require the inventory to remain alive. Returning a shallow
copy of an owning string is not a substitute for cloning it. If processing
should consume records instead, design an API around `pop` or `remove` and
transfer the selected values into the result. See [Vec](../types/vec.md) for
borrowed access, cloning, and removal.

## Apply the same choice to other APIs

For a file reader, a view may borrow a buffer while the reader keeps it alive;
a queued message needs owned bytes if processing continues after that buffer
is reused. For a configuration query, `&string` is useful while the
configuration remains in scope; a cached value can use an explicit clone.
For a foreign image handle, a pixel span still depends on the foreign image's
lifetime and invalidation rules.

In each case, state three things in the API: whether inputs are borrowed or
consumed, whether results own their data, and which operation can invalidate
a retained view. Errors also need an ownership contract: a failed operation
must make clear whether the caller still owns the input.

## Related pages

- [Ownership](ownership.md)
- [Borrowing](borrowing.md)
- [Lifetimes](lifetimes.md)
- [Option](../types/option-api.md)
- [Foreign types and ownership](../types/extern-types.md)
