Skip to content
CryoCryo home
Stdlibcore

slice

import std::core::slice; — in the prelude · source

Types

Slice<T>

type struct Slice<T> {
    ptr:    T*;
    length: u64;

    static from_raw(ptr: T*, length: u64) -> Slice<T>;
    length(&this) -> u64;
    is_empty(&this) -> boolean;

    get(&this, index: u64) -> Option<T>
    where T: Copy;

    get_ref(&this, index: u64) -> Option<T*>;
    as_ptr(&this) -> T*;
    subslice(&this, start: u64, end: u64) -> Slice<T>;

    iter(&this) -> implement Iterator<T>
    where T: Copy;
}

A Slice<T> is a (pointer, length) pair: a borrowed view into a contiguous run of values. Algorithms take slices, collections hand them out with as_slice(), and so each algorithm gets written once. for (x in arr) over a fixed-size T[N] lowers to Slice::from_raw, which is why the module is in the prelude.

A slice does not own its storage. The backing memory has to outlive every slice pointing into it.

from_raw(ptr, length) is the constructor: you certify that the range is valid, initialized memory. subslice(start, end) is [start, end) and panics past either bound. as_ptr is the raw pointer to the first element — respect length.

get and iter are gated on T: Copy because they produce an independent bitwise duplicate while the backing storage still owns the element — sound only when T carries no drop obligation. For an owning T, walk by index with length() and get_ref.

Properties

PropertyType
ptrT*
lengthu64

Constructors

static from_raw(ptr: T*, length: u64) -> Slice<T>;

Construct from a raw pointer and length. The caller certifies that [ptr, ptr + length) is valid initialized memory for as long as the slice exists.

Methods

length(&this) -> u64;
is_empty(&this) -> boolean;
get(&this, index: u64) -> Option<T> where T: Copy;

Bounds-checked read by value. Gated on T: Copy: the result is an independent bitwise duplicate while the backing storage still owns the element, so this is only sound when T carries no Drop obligation. For owning T, borrow in place with get_ref.

get_ref(&this, index: u64) -> Option<T*>;

Bounds-checked borrow. Returns a pointer to the element in place, sound for every T. The pointer is valid only while the backing storage outlives the slice.

as_ptr(&this) -> T*;

Raw pointer to the first element. Callers must respect length.

subslice(&this, start: u64, end: u64) -> Slice<T>;

The sub-slice [start, end). Panics if start > end or end > length.

iter(&this) -> implement Iterator<T> where T: Copy;

Return an iterator that yields each element by value (bitwise copy). Gated on T: Copy for the same reason as get; for owning T, walk by index with length() + get_ref.

SliceIter<T>

type struct SliceIter<T> {
    ptr:       T*;
    remaining: u64;
}

The concrete type behind iter(): a pointer and a remaining count. Its count is O(1), where the trait default would walk the sequence.

Properties
PropertyType
ptrT*
remainingu64
implement<T> trait Iterator<T> for struct SliceIter<T>