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:
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 returnsOption<&T>;first,last, andfindalso return borrowed values in the inspected source.getUnchecked(index)has no bounds check. Although its declaration is not markedunsafein that source, calling it out of bounds violates its precondition. Usegetwhen 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, andsplitAtconstruct views, not owned copies. fill,copyFromSpan,swap, andreverseare unsafe mutations. A mutable binding for a copyable span does not establish exclusive write authority over its backing memory; the caller must prove it.asPtrandtoPtrexpose the address. A raw address does not carry a lifetime.toVeccopies via the source'sClonebound; 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.
copyFromSpancopies the shorter length, requiresT: Copy, and permits overlap through memmove semantics.fillclones its replacement for each element and drops each old element; it requiresT: Cloneand already initialized destination elements.swapchecks both indices and transfers values without cloning them;reverse,sort, andsortDesclikewise require exclusive access to the backing range, with sorting additionally requiringT: Ord.
Creating additional copies of a span never strengthens these permissions.
More Reading
- Ownership workflows — complete borrowed-parser and owned-report examples
- Memory safety and raw allocation
- Typed pointers
- Ownership