# Span\<T\>

`Span<T>` is a non-owning view of contiguous elements. It carries a pointer and length; it does not allocate or keep its owner alive. The caller must ensure that backing storage stays valid and appropriately borrowed for every use.

## A View of Owned Storage

This complete example obtains a view from a live `Vec`, gets a borrowed element, and checks the out-of-bounds case:

```vex [span-owned.vx]
fn main(): i32 {
    let! values = Vec.new<i32>();
    values.push(10); values.push(20); values.push(30);
    let view = values.asSpan();
    let middle = view.slice(1, 3);
    let value = match middle.get(0) {
        Some(item) => *item,
        None => { return 1; },
    };
    if value != 20 || middle.len() != 2 || view.get(3).isSome() { return 2; }
    $println(value);
    $println(middle.len());
    return 0;
}
```

Expected stdout is `20` followed by `2`, with exit status 0. Do not mutate, reallocate, or free backing storage while a view or reference requires it. A raw pointer does not carry this lifetime proof; preserve it explicitly when constructing a raw-backed view.

## Creating a View from Raw Storage

`Span.of<T>(p, len)`, `Span.ofPtr<T>`, and `Span.ofVec<T>` are `unsafe` constructors in the prelude. The latter name still takes a raw pointer and length; it does not prove that the pointer belongs to a live `Vec`. A raw view requires a correctly aligned, live range of `len` initialized valid elements and compatible aliasing for its entire use. A non-null pointer alone does not prove any of these conditions. See the [raw memory example](safety.md#raw-allocation-example).

`Span.empty<T>()` constructs an empty view. Empty ranges do not authorize dereference.

## Access and Mutation

- `get(index)` bounds-checks and returns `Option<&T>`; `first`, `last`, and `find` also return borrowed values in the inspected source.
- `getUnchecked(index)` has no bounds check. Although its declaration is not marked `unsafe` in that source, calling it out of bounds violates its precondition. Use `get` when the index is not already proven in range.
- Indexing checks bounds and panics on an invalid index in the inspected implementation. `slice(start, end)` clamps bounds; `take`, `skip`, and `splitAt` construct views, not owned copies.
- `fill`, `copyFromSpan`, `swap`, and `reverse` are unsafe mutations. A mutable binding for a copyable span does not establish exclusive write authority over its backing memory; the caller must prove it.
- `asPtr` and `toPtr` expose the address. A raw address does not carry a lifetime. `toVec` copies via the source's `Clone` bound; verify concrete type support.

The method contracts follow `lib/runtime/VexArch/src/prelude/span.vxc`.
Bounds checks do not validate a dangling or incorrectly constructed view.

## Choosing a view operation

| Need | Method and result |
| --- | --- |
| Optional element | `get(i): Option<&T>` |
| First/last element | `first()` / `last(): Option<&T>` |
| Up to `n` elements | `take(n): Span<T>` |
| Exactly `n` leading/trailing elements | `first(n)` / `last(n): Option<Span<T>>`; `None` when `n > len` |
| Remaining suffix | `skip(n): Span<T>`; empty when `n >= len` |
| Interval `[start, end)` | `slice(start, end): Span<T>`; both bounds clamp to `len`, reversed bounds give an empty view |
| Two views | `splitAt(i): SpanPair<T>` with `.first` and `.second`; the second is empty when `i >= len` |
| Independent owned sequence | `toVec()` / `collect(): Vec<T>` where `T: Clone` |

The distinction between `take(n)` and `first(n)` is useful for parsers:
`take` accepts a short remainder, while `first(n)` can express an exact-length
requirement. Neither copies the source elements.

`getOr(i, fallback)` returns an owned clone of a present element and requires
`T: Clone`; out of bounds, it returns the supplied fallback. This is different
from the shallow-copy accessors on `Vec`.

## Iteration, search, and owned transforms

`iter().next()` yields `Option<&T>`. `find` accepts `fn(&T): bool` and returns
the first borrowed match. The source allocation must remain alive throughout
the iterator and every retained item reference.

`map(fn(&T): U)` creates a new `Vec<U>`. `filter(fn(&T): bool)` creates a new
`Vec<T>` by cloning retained elements and therefore requires `T: Clone`.
A callback seeing a borrowed element cannot transfer that element out of the
source. Repeated reads do not consume a span's elements.

`chunks(size)` yields consecutive non-overlapping subviews, including a final
short chunk. `windows(size)` yields overlapping full-size windows. Both
reject size zero with a panic. These iterators copy view descriptors, not
backing elements; overlapping windows do not provide independent write access.

## Mutating a raw-backed view

A mutable `Span` binding permits changes to the descriptor but is not proof of
exclusive ownership of the memory it points at. Its mutation methods therefore
require an unsafe caller contract. Prefer the owning collection's checked
mutable accessor when it can express the operation.

- `copyFromSpan` copies the shorter length, requires `T: Copy`, and permits
  overlap through memmove semantics.
- `fill` clones its replacement for each element and drops each old element;
  it requires `T: Clone` and already initialized destination elements.
- `swap` checks both indices and transfers values without cloning them;
  `reverse`, `sort`, and `sortDesc` likewise require exclusive access to the
  backing range, with sorting additionally requiring `T: Ord`.

Creating additional copies of a span never strengthens these permissions.

## More Reading

- [Ownership workflows](ownership-workflows.md) — complete borrowed-parser and owned-report examples
- [Memory safety and raw allocation](safety.md)
- [Typed pointers](ptr-t.md)
- [Ownership](ownership.md)

<a id="overview"></a>
<a id="struct-definition"></a>
<a id="creating-spans"></a>
<a id="from-vec"></a>
<a id="from-ptr"></a>
<a id="from-raw-pointer"></a>
<a id="empty-span"></a>
<a id="element-access"></a>
<a id="bounds-checked-safe"></a>
<a id="unchecked-fast"></a>
<a id="first-last"></a>
<a id="with-fallback"></a>
<a id="index-operator"></a>
<a id="slicing-zero-copy"></a>
<a id="search"></a>
<a id="higher-order-search"></a>
<a id="comparison"></a>
<a id="converting-to-vec"></a>
<a id="iteration"></a>
<a id="raw-access"></a>
<a id="in-place-mutation"></a>
<a id="fill"></a>
<a id="copy-from-another-span"></a>
<a id="reverse"></a>
<a id="method-reference"></a>
<a id="constructors"></a>
<a id="properties"></a>
<a id="element-access-1"></a>
<a id="slicing"></a>
<a id="search-1"></a>
<a id="mutation-in-place"></a>
<a id="comparison-conversion"></a>
<a id="see-also"></a>
