Mojo struct
Span
struct Span[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]]
A non-owning view of contiguous data.
Parameters
- mut (
Bool): Whether the span is mutable. - T (
AnyType): The type of the elements in the span. - origin (
Origin): The origin of the Span.
Implemented traits
AnyType,
Boolable,
Copyable,
Defaultable,
DevicePassable,
Hashable,
ImplicitlyCopyable,
ImplicitlyDestructible,
Iterable,
Movable,
RegisterPassable,
Sized,
TrivialRegisterPassable,
Writable
comptime members
device_type
comptime device_type = Span[T, origin]
The device-side type for this Span.
Immutable
comptime Immutable = Span[T, origin_of(_mlir_origin)]
The immutable version of the Span.
IteratorType
comptime IteratorType[iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]] = _SpanIter[T(Copyable), origin]
The iterator type for this Span.
Parameters
Methods
__init__
__init__() -> Self
Create an empty / zero-length span.
__init__(*, ptr: UnsafePointer[T, origin], length: Int) -> Self
Unsafe construction from a pointer and length.
Args:
- ptr (
UnsafePointer): The underlying pointer of the span. - length (
Int): The length of the view.
@implicit
__init__(ref[origin] list: List[T(Copyable)]) -> Self
Construct a Span from a List.
Args:
- list (
List): The list to which the span refers.
@implicit
__init__[array_origin: Origin[mut=mut], U: Copyable, size: Int, //](ref[mut] array: InlineArray[U, size]) -> Span[U, array_origin]
Construct a Span from an InlineArray.
Parameters:
- array_origin (
Origin): The origin of the array. - U (
Copyable): The type of the elements in theInlineArray. - size (
Int): The size of theInlineArray.
Args:
- array (
InlineArray): The array to which the span refers.
Returns:
__bool__
__bool__(self) -> Bool
Check if a span is non-empty.
Returns:
Bool: True if a span is non-empty, False otherwise.
__getitem__
__getitem__[I: Indexer](self, idx: I) -> ref[origin] T
Get a reference to an element in the span.
Parameters:
- I (
Indexer): A type that can be used as an index.
Args:
- idx (
I): The index of the value to return.
Returns:
ref: An element reference.
__getitem__(self, slc: ContiguousSlice) -> Self
Get a new span from a slice of the current span.
Allocation: This function allocates when the step is negative, to avoid a memory leak, take ownership of the value.
Args:
- slc (
ContiguousSlice): The slice specifying the range of the new subslice.
Returns:
Self: A new span that points to the same data as the current span.
__eq__
__eq__[_T: Equatable, //](self: Span[_T, origin], rhs: Span[_T, rhs.origin]) -> Bool
Verify if span is equal to another span.
Parameters:
- _T (
Equatable): The type of the elements must implement the traitsEquatable,Copyable.
Args:
- rhs (
Span): The span to compare against.
Returns:
Bool: True if the spans are equal in length and contain the same elements, False otherwise.
__ne__
__ne__[_T: Equatable, //](self: Span[_T, origin], rhs: Span[_T, rhs.origin]) -> Bool
Verify if span is not equal to another span.
Parameters:
- _T (
Equatable): The type of the elements in the span. Must implement the traitsEquatable,Copyable.
Args:
- rhs (
Span): The span to compare against.
Returns:
Bool: True if the spans are not equal in length or contents, False otherwise.
__contains__
__contains__[dtype: DType, //](self: Span[Scalar[dtype], self.origin], value: Scalar[dtype]) -> Bool
Verify if a given value is present in the Span.
Parameters:
- dtype (
DType): The DType of the scalars stored in the Span.
Args:
- value (
Scalar): The value to find.
Returns:
Bool: True if the value is contained in the list, False otherwise.
__contains__(self, value: T) -> Bool where conforms_to(T, AnyType & ImplicitlyDestructible & Equatable)
Verify if a given value is present in the span.
Performs a linear scan over all elements comparing with ==.
Args:
- value (
T): The value to find.
Returns:
Bool: True if the value is contained in the span, False
otherwise.
get_type_name
static get_type_name() -> String
Gets this type's name, for use in error messages when handing arguments to kernels.
Returns:
String: This type's name.
__iter__
__iter__(ref self) -> _SpanIter[T(Copyable), origin]
Get an iterator over the elements of the Span.
Returns:
_SpanIter: An iterator over the elements of the Span.
__reversed__
__reversed__(self) -> _SpanIter[T(Copyable), origin, False]
Iterate backwards over the Span.
Returns:
_SpanIter: A reversed iterator of the Span elements.
__len__
__len__(self) -> Int
Returns the length of the span. This is a known constant value.
Returns:
Int: The size of the span.
write_to
write_to(self, mut writer: T) where conforms_to(T, AnyType & ImplicitlyDestructible & Writable)
Write this span to a Writer.
Args:
- writer (
T): The object to write to.
write_repr_to
write_repr_to(self, mut writer: T) where conforms_to(T, AnyType & ImplicitlyDestructible & Writable)
Write this span to a Writer.
Args:
- writer (
T): The object to write to.
__hash__
__hash__[H: Hasher](self, mut hasher: H) where conforms_to(T, AnyType & Hashable)
Updates hasher with the hash of each element in the span.
Parameters:
- H (
Hasher): The hasher type.
Args:
- hasher (
H): The hasher instance.
get_immutable
get_immutable(self) -> Span[T, origin].Immutable
Return an immutable version of this Span.
Returns:
Span: An immutable version of the same Span.
unsafe_get
unsafe_get(self, idx: T) -> ref[origin] T
Get a reference to the element at index without bounds checking.
Safety:
- This function does not do bounds checking and assumes the provided index is in: [0, len(self)). Not upholding this contract will result in undefined behavior.
- This function does not support wraparound for negative indices.
Args:
- idx (
T): The index of the element to get.
Returns:
ref: A reference to the element at the specified index.
unsafe_ptr
unsafe_ptr(self) -> UnsafePointer[T, origin]
Retrieves a pointer to the underlying memory, or a dangling pointer if the span doesn't point to anything.
You should use the len of this Span to determine if the pointer
is valid for reads and writes.
Returns:
UnsafePointer: The pointer to the underlying memory.
as_ref
as_ref(self) -> Pointer[T, origin]
Gets a Pointer to the first element of this span.
Returns:
Pointer: A Pointer pointing at the first element of this span.
copy_from
copy_from[_T: Copyable & ImplicitlyDestructible, _origin: MutOrigin, //](self: Span[_T, _origin], other: Span[_T, other.origin])
Performs an element wise copy from all elements of other into all elements of self.
Parameters:
- _T (
Copyable&ImplicitlyDestructible): List element type that supports implicit destruction. - _origin (
MutOrigin): The inferred mutable origin of the data within the Span.
Args:
- other (
Span): TheSpanto copy all elements from.
fill
fill[_T: Copyable & ImplicitlyDestructible, //](self: Span[_T, self.origin], value: _T)
Fill the memory that a span references with a given value.
Parameters:
- _T (
Copyable&ImplicitlyDestructible): Span element type that supports implicit destruction.
Args:
- value (
_T): The value to assign to each element.
unsafe_swap_elements
unsafe_swap_elements[U: Movable](self: Span[U, self.origin], a: Int, b: Int)
Swap the values at indices a and b without performing bounds checking.
Safety:
- Both
aandbmust be in: [0, len(self)).
Parameters:
- U (
Movable): Span element type that must beMovable.
Args:
swap_elements
swap_elements[U: Movable](self: Span[U, self.origin], a: Int, b: Int)
Swap the values at indices a and b.
Parameters:
- U (
Movable): Span element type that must beMovable.
Args:
Raises:
If a or b are larger than the length of the span.
__merge_with__
__merge_with__[other_type: AnyStruct[Span[T, other_type.origin]]](self) -> Span[T, origin_of(origin, other_type.origin)]
Returns a pointer merged with the specified other_type.
Parameters:
- other_type (
AnyStruct): The type of the pointer to merge with.
Returns:
Span: A pointer merged with the specified other_type.
reverse
reverse[dtype: DType, //](self: Span[Scalar[dtype], self.origin])
Reverse the elements of the Span inplace.
Parameters:
- dtype (
DType): The DType of the scalars theSpanstores.
apply
apply[dtype: DType, //, func: def[w: Int](SIMD[dtype, w]) capturing -> SIMD[dtype, w]](self: Span[Scalar[dtype], self.origin])
Apply the function to the Span inplace.
Parameters:
- dtype (
DType): The DType. - func (
def[w: Int](SIMD[dtype, w]) capturing -> SIMD[dtype, w]): The function to evaluate.
apply[dtype: DType, //, func: def[w: Int](SIMD[dtype, w]) capturing -> SIMD[dtype, w], *, cond: def[w: Int](SIMD[dtype, w]) capturing -> SIMD[DType.bool, w]](self: Span[Scalar[dtype], self.origin])
Apply the function to the Span inplace where the condition is True.
Parameters:
- dtype (
DType): The DType. - func (
def[w: Int](SIMD[dtype, w]) capturing -> SIMD[dtype, w]): The function to evaluate. - cond (
def[w: Int](SIMD[dtype, w]) capturing -> SIMD[DType.bool, w]): The condition to apply the function.
count
count[dtype: DType, //, F: def[w: Int](v: SIMD[dtype, w]) -> SIMD[DType.bool, w]](self: Span[Scalar[dtype], self.origin], func: F) -> UInt where (eq F.dtype, dtype)
Count the amount of times the function returns True.
Parameters:
- dtype (
DType): The DType. - F (
def[w: Int](v: SIMD[dtype, w]) -> SIMD[DType.bool, w]): The function type to evaluate.
Args:
- func (
F): The function value to evaluate.
Returns:
UInt: The amount of times the function returns True.
unsafe_subspan
unsafe_subspan(self, *, offset: Int, length: Int) -> Self
Returns a subspan of the current span.
Safety: This function does not do bounds checking and assumes the current span contains the specified subspan.
Args:
- offset (
Int): The starting offset of the subspan (self._data + offset). - length (
Int): The length of the new subspan.
Returns:
Self: A new span representing the specified subspan.
binary_search_by
binary_search_by[func: def(T) -> Int](self) -> Optional[Int]
Finds an element using binary search with a custom comparison function.
The comparison function should return:
- A negative value if the element is less than the target
- Zero if the element matches the target
- A positive value if the element is greater than the target
Notes:
This function assumes that self is sorted according to the ordering
defined by func. If not sorted, the result is unspecified.
Example:
var data: List[String] = ["a", "bb", "ccc"]
var span = Span(data)
# Search for "bb"
def cmp(elem: String) -> Int:
if elem < "bb":
return -1
elif elem > "bb":
return 1
else:
return 0
var index = span.binary_search_by[cmp]()
if index:
print("Found at index: ", index.value())
else:
print("Not found")Parameters:
- func (
def(T) -> Int): A function that takes an element and returns an Int representing the comparison result.
Returns:
Optional: Returns the index of the matching element if found, None otherwise.
binary_search_by[FuncType: def(T) -> Int](self, func: FuncType) -> Optional[Int] where (eq FuncType.T, T)
Finds an element using binary search with a custom comparison function.
The comparison function should return:
- A negative value if the element is less than the target
- Zero if the element matches the target
- A positive value if the element is greater than the target
Notes:
This function assumes that self is sorted according to the ordering
defined by func. If not sorted, the result is unspecified.
Example:
def main():
var data: List[String] = ["a", "bb", "ccc"]
var span = Span(data)
# Search for "bb"
def cmp(elem: String) unified {} -> Int:
if elem < "bb":
return -1
elif elem > "bb":
return 1
else:
return 0
var index = span.binary_search_by(cmp)
if index:
print("Found at index: ", index.value())
else:
print("Not found")Parameters:
- FuncType (
def(T) -> Int): The type of the supplied function.
Args:
- func (
FuncType): A function that takes an element and returns an Int representing the comparison result.
Returns:
Optional: Returns the index of the matching element if found, None otherwise.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!