Skip to content
Systems programming for what’s next.
— Vex

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
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.

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 ​

NeedMethod and result
Optional elementget(i): Option<&T>
First/last elementfirst() / last(): Option<&T>
Up to n elementstake(n): Span<T>
Exactly n leading/trailing elementsfirst(n) / last(n): Option<Span<T>>; None when n > len
Remaining suffixskip(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 viewssplitAt(i): SpanPair<T> with .first and .second; the second is empty when i >= len
Independent owned sequencetoVec() / 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 ​

Released under the MIT License.